How physics engines calculate physics ?
Demo: http://www.yourfilelink.com/get.php?fid=278491
( Use "http://www.yourfilelink.com/check.js" for AbBlock. )
Sources included.
Delphi + GLScene
It works with static boxes and dynamic spheres.
Physics calculation loop consist of two parts.
1) Detect collisions, and accumulate forces for dynamic objects.
2) Add accumulated force to dynamic objects, and calculate new acceleration, velocity, position and etc for them.
1) How to add force for collided objects.
I calculate a direction of a dynamic object movement. If it moves out of static body, i do nothing. If it moves inside static body, i add force:
[pascal]PsObj[phObjInd].Force := VectorAdd( PsObj[phObjInd].Force,
VectorScale(intNorm,
PsObj[phObjInd].Mass *Depth1 / aDeltaTime
) );
Force := Force +Normal of collision * mass of object * penetration depth * time;[/pascal]
2) How to add accumulated force to a dynamic object.
[pascal] // Add gravity to Force accumulator.
// Force1 := Force1 +Gravity.
Force1 := VectorAdd(PsObj[psInd].Force, Gravity);
PsObj[psInd].Force := Force1;
// Acceleration. Get Acceleration from Force and mass.
// a1 := F / Mass; F := m*a1;
a1 := VectorScale(Force1, 1/PsObj[psInd].Mass);
// Velocity. Get Velocity from acceleration and time.
// dV := a1 *t1 a = dv/dt t1 = dt = deltaTime
dV := VectorScale(a1, aDeltaTime);
// Add new velocity to old.
// v := v0 +dV;
v1 := VectorAdd(PsObj[psInd].Speed, dV);
PsObj[psInd].Speed := v1;
// Change position. Add to position s := V1*t.
// Pos1 := Pos1 +V1*t;
with PsObj[psInd].GLSphere.Position do begin
Pos1 := VectorAdd(AsAffineVector, VectorScale(v1, aDeltaTime) );
SetPoint(Pos1);
end;[/pascal]
I know that it works bad. How to improve? And how to add nice rotations?
Bookmarks