Imagine a spring with one end anchored to a surface,
and the other with an object attached. If you push or pull on the
object and let it go, it will oscillate back and forth
because of the force that the spring exerts on it. The spring is
trying to return the object to its resting position.
While surface gravity is a constant force, and friction
depends on velocity, a spring's force depends on position.
Particularly, the position in relation to the resting position.
The basic idea is springForce = restingPosition - position.
How could this be expressed in terms of the
variables of the physics
model? For the y axis it would be ySpringForce
= yRestPosition - y; same with x variables
for the x axis. The rest position depends on the
animation.
Many kinds of objects exert this type of force to
some extent, especially elastic objects. In this
demo, the object is a rubber ball and spring force is combined
with gravity.
property
sp, spHeight property y, yVelo,
yAccel --pos,vel,acc property yGrav, ySpring --force
y components
y = sp.locv--initialize
position
yVelo = 0 --object
starts at rest
yGrav = .2 --gravity
is constant downward
ySpring = 0 end
onexitframe() --set spring force
dist = (the stage).rect.height
- y if dist <
spHeight then
ySpring = -(spHeight - dist) * .08 else
ySpring = 0 end if
--acceleration is sum
of forces yAccel = yGrav + ySpring
--increment velocity and position
yVelo = yVelo + yAccel
y = y + yVelo
--set sprite position sp.locv = y
--squish effect
squishBall end
Spring forces - source
movie - The squishBall handler is not shown here
The registration point of the ball
has been set to the top middle of the cast member.
This is not necessary, but makes the code a little simpler.
In this animation, the rest position
is spHeight above the bottom of the
stage. The farther the ball passes this rest position, the greater
the spring force pushes upward. Multiplying by .08
in calculating the spring force was to scale it down
so that the animation looked correct. It could be considered the
stiffness of the object. If the stiffness were
1, look at what yAccel would be.
A new idea in this demo is applying a force
only under certain conditions. In this case, the spring
force only acts when the ball is touching the bottom edge,
and otherwise its value is zero.
Because of this, the oscillating nature of spring
force isn't apparent. Try removing the
conditional and applying spring force all the time to see
the oscillation:
The squishing of the ball is separate from
the physics model. Try removing the call to squishBall
to see what this means.
Oscillating Motion Using the concept of a spring force is a general
way of achieving oscillating motion. The value of restPosition
will be the center of the oscillation, and the
amount that (restPosition - position) is scaled by
will determine the speed of the oscillation.