Notebook - Welcome to Notebook

Contact/Report Bugs
You can contact me at: bkenwright@xbdev.net












Rigid body with both normal and tangental forces Shows how the tangental force causes the object to sping roll down the slope versus just a normal fforce Try it Comment out the line for the addForce for the tangental force it still works but doesn t spin slides down the slope without spinning const canvas document createElement canvas document body appendChild canvas canvas width canvas height 500 canvas style border 1px solid gray const ctx canvas getContext 2d Simulation parameters const gravity 9 81 const timeStep 1 30 60 FPS const penaltyStiffness 1000 Penalty force constant Sphere object const sphere radius 20 position x 100 y 50 velocity x 0 y 0 angle 0 angularVelocity 0 mass 1 inertia 0 5 1 20 20 Sphere moment of inertia I 0 5 m r 2 Ground lines can represent slopes const groundLines start x 0 y 250 end x 300 y 300 Flat ground start x 300 y 300 end x 500 y 250 Sloped ground Utility function subtract vectors function subtract v1 v2 return x v1 x v2 x y v1 y v2 y Utility function normalize vector function normalize v const length Math sqrt v x v x v y v y return x v x length y v y length Utility function dot product function dot v1 v2 return v1 x v2 x v1 y v2 y Utility function perpendicular in 2D rotate 90 degrees function perpendicular v return x v y y v x Utility function length of vector function length v return Math sqrt v x v x v y v y Detect collision between sphere and a line function detectCollision sphere line const lineVec subtract line end line start const sphereToLineStart subtract sphere position line start const projectionLength dot sphereToLineStart lineVec dot lineVec lineVec const projectionPoint x line start x projectionLength lineVec x y line start y projectionLength lineVec y const distVec subtract sphere position projectionPoint const distToLine length distVec if distToLine sphere radius projectionLength 0 projectionLength 1 return point projectionPoint distance distToLine normal normalize distVec return null Global variables for accumulated forces let accumulatedForce x 0 y 0 let accumulatedTorque 0 For rotational forces Adds a force at a given world location and accumulates the total force and torque param Object force The force vector x y param Object worldLocation The point of application of the force in world coordinates x y function addForce force worldLocation Accumulate linear force accumulatedForce x force x accumulatedForce y force y Calculate the torque r worldLocation sphere position const r x worldLocation x sphere position x y worldLocation y sphere position y Torque r x F cross product in 2D r_x F_y r_y F_x const torque r x force y r y force x accumulatedTorque torque Integrate forces to update the sphere s velocity angular velocity position and angle function integrateForces Integrate linear velocity sphere velocity x accumulatedForce x sphere mass timeStep sphere velocity y accumulatedForce y sphere mass timeStep Integrate angular velocity sphere angularVelocity accumulatedTorque sphere inertia timeStep Update position and angle sphere position x sphere velocity x timeStep sphere position y sphere velocity y timeStep sphere angle sphere angularVelocity timeStep Clear accumulated forces and torque for the next step accumulatedForce x 0 y 0 accumulatedTorque 0 Apply physics gravity collision response rolling function applyPhysics Apply gravity as a force through the center of the sphere addForce x 0 y gravity sphere mass sphere position Collision detection with ground lines for let line of groundLines const collision detectCollision sphere line if collision Contact point const contactPoint collision point const contactNormal collision normal Calculate the penetration depth const penetrationDepth sphere radius collision distance Normal force penalty force to push the sphere out const normalForce x contactNormal x penetrationDepth penaltyStiffness y contactNormal y penetrationDepth penaltyStiffness Tangential direction and friction const contactTangent perpendicular contactNormal const relativeVelocity dot sphere velocity contactTangent Static friction threshold if relative velocity is very small stop the rotation const frictionThreshold 0 1 let tangentialForce x 0 y 0 if Math abs relativeVelocity frictionThreshold Static friction stop motion sphere angularVelocity 0 tangentialForce x sphere velocity x 10 Strong force to stop motion y sphere velocity y 10 else Dynamic friction case const frictionCoefficient 1 0 const tangentialForceMagnitude relativeVelocity frictionCoefficient tangentialForce x contactTangent x tangentialForceMagnitude y contactTangent y tangentialForceMagnitude Add forces at the contact point addForce normalForce contactPoint Normal force at contact point addForce tangentialForce contactPoint Tangential force friction at contact point Move the sphere out of penetration depth to avoid sinking sphere position x contactNormal x penetrationDepth sphere position y contactNormal y penetrationDepth Draw contact point normal and tangent drawContactDetails contactPoint contactNormal contactTangent Damping angular velocity to simulate friction stopping rotation over time const angularDamping 0 99 sphere angularVelocity angularDamping Integrate accumulated forces integrateForces Drawing functions function drawSphere Draw the sphere ctx beginPath ctx arc sphere position x sphere position y sphere radius 0 2 Math PI ctx fillStyle blue ctx fill ctx stroke Draw the rotation marker line from center to edge based on angle const markerLength sphere radius Length of the marker to the edge of the sphere const markerX sphere position x markerLength Math cos sphere angle const markerY sphere position y markerLength Math sin sphere angle ctx beginPath ctx moveTo sphere position x sphere position y ctx lineTo markerX markerY Draw the rotating line ctx strokeStyle white Color of the rotation marker ctx lineWidth 2 ctx stroke function drawGroundLines ctx lineWidth 2 ctx strokeStyle black groundLines forEach line ctx beginPath ctx moveTo line start x line start y ctx lineTo line end x line end y ctx stroke function drawContactDetails contactPoint normal tangent Draw contact point ctx beginPath ctx arc contactPoint x contactPoint y 5 0 2 Math PI ctx fillStyle red ctx fill Draw normal ctx strokeStyle green ctx beginPath ctx moveTo contactPoint x contactPoint y ctx lineTo contactPoint x normal x 50 contactPoint y normal y 50 ctx stroke Draw tangential direction ctx strokeStyle red ctx beginPath ctx moveTo contactPoint x 8 contactPoint y ctx lineTo contactPoint x 8 tangent x 50 contactPoint y tangent y 50 ctx stroke Animation loop function animate ctx clearRect 0 0 canvas width canvas height Draw everything drawSphere drawGroundLines Apply physics for let s 0 s 10 s applyPhysics Loop requestAnimationFrame animate Start the animation animate

ontact point const contactPoint collision point const contactNormal collision normal Calculate the penetration depth const penetrationDepth sphere radius collision distance Normal force penalty force to push the sphere out const normalForce x contactNormal x penetrationDepth penaltyStiffness y contactNormal y penetrationDepth penaltyStiffness Tangential direction and friction const contactTangent perpendicular contactNormal const relativeVelocity dot sphere velocity contactTangent Static friction threshold if relative velocity is very small stop the rotation const frictionThreshold 0 1 let tangentialForce x 0 y 0 if Math abs relativeVelocity frictionThreshold Static friction stop motion sphere angularVelocity 0 tangentialForce x sphere velocity x 10 Strong force to stop motion y sphere velocity y 10 else Dynamic friction case const frictionCoefficient 1 0 const tangentialForceMagnitude relativeVelocity frictionCoefficient tangentialForce x contactTangent x tangentialForceMagnitude y contactTangent y tangentialForceMagnitude Add forces at the contact point addForce normalForce contactPoint Normal force at contact point addForce tangentialForce contactPoint Tangential force friction at contact point Move the sphere out of penetration depth to avoid sinking sphere position x contactNormal x penetrationDepth sphere position y contactNormal y penetrationDepth Draw contact point normal and tangent drawContactDetails contactPoint contactNormal contactTangent Damping angular velocity to simulate friction stopping rotation over time const angularDamping 0 99 sphere angularVelocity angularDamping Integrate accumulated forces integrateForces Drawing functions function drawSphere Draw the sphere ctx beginPath ctx arc sphere position x sphere position y sphere radius 0 2 Math PI ctx fillStyle blue ctx fill ctx stroke Draw the rotation marker line from center to edge based on angle const markerLength sphere radius Length of the marker to the edge of the sphere const markerX sphere position x markerLength Math cos sphere angle const markerY sphere position y markerLength Math sin sphere angle ctx beginPath ctx moveTo sphere position x sphere position y ctx lineTo markerX markerY Draw the rotating line ctx strokeStyle white Color of the rotation marker ctx lineWidth 2 ctx stroke function drawGroundLines ctx lineWidth 2 ctx strokeStyle black groundLines forEach line ctx beginPath ctx moveTo line start x line start y ctx lineTo line end x line end y ctx stroke function drawContactDetails contactPoint normal tangent Draw contact point ctx beginPath ctx arc contactPoint x contactPoint y 5 0 2 Math PI ctx fillStyle red ctx fill Draw normal ctx strokeStyle green ctx beginPath ctx moveTo contactPoint x contactPoint y ctx lineTo contactPoint x normal x 50 contactPoint y normal y 50 ctx stroke Draw tangential direction ctx strokeStyle red ctx beginPath ctx moveTo contactPoint x 8 contactPoint y ctx lineTo contactPoint x 8 tangent x 50 contactPoint y tangent y 50 ctx stroke Animation loop function animate ctx clearRect 0 0 canvas width canvas height Draw everything drawSphere drawGroundLines Apply physics for let s 0 s 10 s applyPhysics Loop requestAnimationFrame animate Start the animation animate

2dracecargame
3dplot
a4print
about
acecustomkeywords
acecustomkeywords2
acejs
acejs2
acejs3
aessecurity
angularjs
animbackgroundimage
aseformat
assert
asteroidsjs
backgrounds01
backgrounds02
backgrounds03
barnsleyfern
base26
base64
bib
binary
bodypix
bouncy
box2dweb
breakoutjs
browserversion
buslanes
busybutton
bvhreader
calendar
candycrush
candycrush2
canvas
canvas2
canvas3
canvasmandelbrot
canvasmandelbrot2
canvasnumbers
canvaszoom
capsule
car2dsimulationphysics
car2dsimulationphysics2
changingimages
chaosgame
chaosrandom
chaosrandomhisto
chaosrandomhisto2
chatgptusingopenai
chatgptusingopenai2
chatgptusingopenai3
checkboxtoggle
chinesetiles
classes
classfeatures
clipboardbutton
clonenode
codedropdown
codemirror
codemirror2
collada
colorpick
columnresizer
contextmenu
convnet
cookiebanner
countdown
countdown2
countdown3
crop
css3dbarchart
css3dbarchart2
css3dbook
css3dscene
csscube
csscube2
csscube3
csscubevideos
cssfilelist
csshas
csspulse
cssresizeaspect
cssspin
csszooming
csvtoarray
curleffect
customcheckbox
customhexviewer
d3datamap
d3js
d3js10
d3js11
d3js2
d3js3
d3js4
d3js5
d3js6
d3js7
d3js8
d3js9
d3jsanimatedgrid
d3jsarctransition
d3jsarctransition2
d3jsaxis
d3jsaxischanging
d3jsbars
d3jsbrushing
d3jsbuslanes
d3jsbuslanes2
d3jscalendar
d3jscheat
d3jsclock
d3jscloudmap
d3jscogs
d3jscolors
d3jscovid
d3jscovid2
d3jscovid3
d3jsdashboard
d3jsdashboard2
d3jsdashboard3
d3jsdatakeyfunction
d3jsdensity
d3jsdragresizing
d3jsdragresizing2
d3jseach
d3jsease
d3jsevents
d3jsflower
d3jsforcegroups
d3jsforces
d3jsforces2
d3jsfractaltree
d3jsgeo
d3jsgroupbars
d3jsgroups
d3jsheatmap
d3jshex
d3jshierarchies
d3jshierarchies2
d3jshistogram
d3jshistogram2
d3jshistogram3
d3jshistogram4
d3jsinterpolate
d3jsjoin
d3jskmean
d3jskmean2
d3jsline
d3jsline2
d3jsline3
d3jsline4
d3jslinetransition
d3jslinetransition0
d3jslinetransition2
d3jsmaplocations
d3jsmaps
d3jsmaps2
d3jsmaps3
d3jsmisc
d3jsmisc2
d3jsmodule
d3jsmodulecolor
d3jsmultistyles
d3jsnobel
d3jsoverlappinggraphs
d3jspanel
d3jspie
d3jspieinterpolate
d3jssankey
d3jssankey2
d3jsscatter
d3jsshapes
d3jsslider
d3jsspending
d3jsspending2
d3jsspiralplot
d3jsspirograph
d3jssquare
d3jsstack
d3jsstackedbar
d3jsstackedbar2
d3jssunburst
d3jssunmoon
d3jssvglines
d3jssymbols
d3jstimelines
d3jsuk
d3jsvoronoi
d3scatterplot
d3timeline
d3timeline2
datalist
datamuse
date
dblclickhighlight
deviceorientation
dictionaryapi
dockermenu
doodlepad
downloadgif
dragdroplistitems
dragrotateresizediv
dragrotateresizediv2
dragrotateresizediv3
dragrotateresizediv4
dragrotateresizefontsize
dragselectbrush
drawlinesdiv
dropdown
dualquaternionimages
dynamicgrid
easefunctions
easeinterpolate3dplots
echart
echart2
echart3
encapsulation
epubviewer
errorstack
excalidraw
excalidraw2
excalidraw3
excalidraw5
expandable
faker
fetchplus
fileupload
fixedtopbar
fluiddynamics
fluiddynamics2
fluiddynamics3
fluidgaswatergl
fluidsmokedynamics
fluidsmokedynamics2
fonts
fonts2
footerbar
fractalcircles
fractalmaze
fractalmaze2
fractalnoiseimage
fractals
fractals2
fractaltree
freesvg
fresnel
froggerjs
gantt
gifgiphyapi
gifhex
gltffromscratch
gradients
griditems
griditems2
griditems3
griditems4
gridworms
happyfont
heat
hexview
hexview2
highlight
icons
icons2
iframes
ik
imagetracertosvg
imgur
inputfile
invadersjs
ipynb
ipynb2
ipynb3
ipynb4
isbn13
isbn2
jpghex
jquery
jquery2
jqueryui
jqueryui2
jsdraganddrop
jsfire
jslint
jsobfuscate
jsraytracer
jstree
jstree2
jszip
jszipimages
jszipread
keyboardpiano
keyframes
l2dwidget
lcpsolverrigidbodies
lda
leftmenu
less
less2
lineargradientimage
linenumbers
loadimagefromfile
makepdf
maps
markdown
markdown2
markdown3
markdownalerts
markdownalerts2
markdownbookmarks
markovimage
markovpixelblocks
mathjax
matrices
matsandvects
mazegamejs
md2tex
metrotiles
metrowindows
milestones
minkowski2dboxes
misc
misc2
modules
myipdetails
mymodplotly
neataptic
networkstructures
networkstructures2
neural_network_drawshape
neural_network_plot_in_vs_out
neuralnetworkarrays
neuralnetworkblocks
neuralnetworksinewave
neuralnetworksnolibs
neuralnetworkvisualization
noiseflowfield
noiseflowfield2
noiseflowfield3
noiseflowfield4
noiseflowfield5
noiseflowfield6
number
obj
objtojson
openaiimages
opencv
opencv2
opencv3
opencv4
opencv5
outline
p2
p5fractalleaf
p5fractalshape
p5js
p5js2
p5js3
p5jsanimatedcover
p5mengercube
p5snowflakes
palindrome
panel
parallax
paste
paste2
pasteimgfromurl
pdfjs
pdfjs2
pdfkit
pdfkit2
pdfkit3
pdfkit4
pdfkit5
pdfkit6
pdfmake
pdfmake2
pdfmake3
pdfmake4
pdfmake5
pdfmake6
perlin
perlin2
perlin3
perspective
pexels
pixelgridpattern
playground
plotly
plotlynoise
plotlyranddist
plyloader
plyloader2
pngtxtencoder
pongjs
pptxgenjs
prettycode
prism
prn
problems
progress
pseudorandom
px2svg
python
quotes
racergame
random
randomcalcpie
randomgenerator
randomprofilepatterns
randomsinhistogram
randomstring
rating
rayambient
raymonte
raymonteprogressive
raymonteprogressive2
raymontewarmstart
reexpcross
reexpcross2
regex
regexbib
regexpfixbib
regexpmultiline
repeatwordsregexp
resizabletable
resizabletable2
revealjs
revealjs2
revealjsmulti
rigidbodyspheres2d
rigidbodyspheres3
rigidbodysphereslopetangent
ritalanguage
ritalanguage2
ritalanguage3
rotateimg
rough
rsapublicprivatekeys
rss
rss2
sankey
scrappingsvg
scrolltext
scrolltext2
scrollwidth
sdf2dcanvas
sdfboxinboxtwist
sdfchessbishop
sdfchessking
sdfchessknight
sdfchesspawn
sdfchessqueen
sdfchessrook
sdfhollowbox
setintervalexception
shareurl
shuffle
sidecomment
similarity
simplehighlighter
simpleplatformgamejs
sinecanvas
sliderpopout
slides
smileys
snowfall
snowman
sound
soundsignal
sphererayintersection
springs
sqljs
steganography
stereogram
stringmatching
sudoku
sudoku2
sudoku3
svg
svgchaos
svgdragresize
svgdragresize2
svgdragresize3
svgdragrotate
svgdrawing
svglines
svglines2
svglines3
svglines4
svglines5
svglinesmandelbrot
svgpathsdragrotate
svgpathsdragrotateresize
svgpie
svgpie2
svgpie3
svgpiepath
svgpiepath2
svgrandomfaces
symbolcanvas
symbols
synaptic
synaptic2
synonyms
tablerotatecells
tablerotatecells2
tablerotatecells3
tablerotatecells3b
tablerotatecells4
tables
tablezebra
tabularjs
tabularjs2
tabulatordownload
tagcanvas
tensorflowdenoiseencoder
tensorflowgan
tensorflowjs
tensorflowjsbasic
tensorflowjscnn
tensorflowjssinewave
tensorflowjssound
tensorflowmobilenet
tetrahedronfractal
tetrahedronfractalfolding
tetris
textarea
textareaauto
textareadiv
textareadiv2
textmaskimage
theirorthere
thesaurus
threejs
threejs2
threejs3
threejs4
threejsgltf
threejstokyo
tiles
toaster
tooltip
transition
transitionexpandabledropdown
treeview
treeview2
tricks
tshirt
tshirt2
tshirt3
turningpages
unsplash
urlblob
urlblob2
userdefinepoints
vector
videos
videos2
visualsort
vue
w2ui
w2uientertextdialog
webcam
webgl
webgl2
webgl3
webgl4
webgl5
webglbasic1
webglbasic2
webglcube
webglfov
webglfrustum
webgljson
webglleaves
webgllighting
webglorthographic
webglpoints1
webglpoints2
webglpoints3
webglsquare
webgltexture1
webgltexture2
webgltexture3
webgltransforms
webgltriangle
webgpu
webgpu10
webgpu11
webgpu12
webgpu13
webgpu14
webgpu15
webgpu16
webgpu17
webgpu2
webgpu3
webgpu4
webgpu5
webgpu6
webgpu7
webgpu8
webgpu9
webgpubars
webgpubuffers
webgpubuffers2
webgpucellnoise
webgpuclouds
webgpuclydescope
webgpucompute
webgpucubemap
webgpucubemap2
webgpudeferred
webgpudepth
webgpudof
webgpudrops
webgpuetha
webgpufire
webgpufractalcubes
webgpuglassrain
webgpugltf
webgpugltf2
webgpugrass
webgpugrid
webgpukernel
webgpukleinian
webgpulabupdates
webgpulighting
webgpumandelbrot
webgpumeta3d
webgpumetaballs
webgpumouse
webgpunoise
webgpunormalmapping
webgpuobj
webgpuparallax
webgpuparallax2
webgpuparallax3
webgpuparallaxshadow
webgpuparallaxshadow2
webgpupixel
webgpuquad
webgpuray1
webgpuraytracing
webgpuraytracing2
webgpushadowmaps
webgpushadowmaps2
webgpusierpinski2d
webgpusierpinski3d
webgpusinusoid
webgpussao
webgpustadiumobj
webgpuswirl
webgputestpipe3
webgputoon
webgputopology
webgputt
webgpuvolcloud
webgpuwater
webgpuwireframe
webgpuwireframe2
webnn
webnn2
webnnconv2d
webnnlstm
webnnpytorch
webnntraining
webnnwithsynaptic
webnnwithsynaptic2
webnnwithsynapticsinwave
webnnwithtensorflow
webpcanvas
webworkers
webxr
webxr2
wiggly
wikipedia