When two objects rebound after colliding with each other,
it is due to a spring force, even though it may not look
like it. When two billiard balls collide, the compression of the ball
is limited to a miniscule fraction of its width but it still happens.
Using a spring force requires higher model rates
to realistically collide faster, harder objects. The fps
display in the demo shows the actual frame rate. The
movie itself is set to 999 fps. On a 1.3 GHz P3 it
averages about 980 actual fps.
repeat with s = 1to4 if s <> me.spritenum
then
spOther = sprite(s)
--distance components
distX = (spOther.x) - x
distY = (spOther.y) - y
--pythagorean theorem
to get distance
dist = sqrt(power(distX,2)
+ power(distY,2))
--spring force
xSpring = 0
ySpring = 0
minDist = (sp.width
+ spOther.width) / 2.0
- 10 if dist <
minDist then
springF = (minDist - dist) * .02
xSpring = springF * -(distX/dist)
ySpring = springF * -(distY/dist) end if
xTotalForce = xTotalForce + xSpring
yTotalForce = yTotalForce + ySpring end if
end repeat
The algorithm is almost identical to general
gravity, so only the repeat loop is shown. Instead of calculating
gravity, it calculates spring force. Spring force only acts when the objects
are within a certain distance of each other, expressed as dist
< minDist.
The magnitude of the spring force is given by minDist
- dist. This is the restPosition - position equation
from the Spring Forces section. Scaling
by .02 puts the force into proportion with other values in the
animation. It can be considered the stiffness of the object,
the higher it is the stiffer the object.
This demo gives each object a mass,
and uses the mass in the accel = force / mass equation. The behavior of the large
object shows how mass affects acceleration. When two objects collide,
each experiences the same amount of force, acting in opposite directions.
This force translates into a smaller acceleration for more massive
objects.
Mass can be set however you'd like. In this demo it is
set to the cube of the sprite width, which would roughly correspond to
its mass if it was a
3-dimensional sphere.
The type of collision modelled in this demo is for round
objects with no friction between them. Friction or non-round
shape would cause part of the energy in the collision to go into rotational
velocity, making the objects spin.
For comments on the rest of the script, see General
Gravity.