Current time:0:00Total duration:2:50

0 energy points

# 2D spring-mass system

Video transcript

- So far we've limited our simulation to vertical motion only, but we want our hairs to
sway in various directions so we'll need to update
our code to include two dimensions of motion. It's fairly easy to do
this, we just need to double-up many of our variables so that we'll have both
an X and Y component. Right now we only have an initial vertical position called "position Y" So I am going to add a new
one called "position X." I am also going to add
a new variable to store the horizontal component of the velocity. I'll call this "velocity X" it should be initialized to
zero, the same as velocity Y because our particle starts from rest. Now I'll move into our draw function and duplicate each equation, so we have a horizontal component as well. Currently, there is springForce
Y, but not springForce X I'll add that now. SpringForce X equals negative K, times position X minus anchor X. I'm going to add a new variable
called "dampingForce X" I'll set it equal to
damping times velocity X. With these new variables I can add a new net force calculation in the
X direction called "force X" it will be slightly different than force Y because we can ignore gravity, since the force of gravity only acts in the vertical direction. So, force X equals springForce
X minus dampingForce X. Now lets move on to acceleration. I'll add a new variable
called "acceleration X" and it will be equal to
force X divided by mass. Let's do the same thing
with the resulting velocity. I'll add a new variable
called "velocity X" which is equal to velocity X, plus acceleration X, times timeStep. Finally we can update the
position so it can have a horizontal component too. I'll do this with a
variable called "position X" which equals position X plus
velocity X times timeStep. Now we have X and Y components
for force, acceleration, velocity, and position. We just need to update our
draw code so that the circle representing our particle,
and the line representing our spring, can move in the X direction. I'll simply add position
X to the end of the line connected to the mass. And for the circle representing our mass, I'll add position X to
its center position. Now watch what happens
when I run the code. Ah-hah! 2D motion. To make our movies we
do the same thing in 3D using a third Z component. That's a fun bonus project
to start thinking about. But let's pause here so
you can get comfortable with this code before
moving on to the last step.