All the forces applied to an object can be summed to make a single, equivalent force.
The gravity is easy to implement as it is constant and always present.
Other forces can vary according to the object's state (drag, buoyancy...), user inputs, links with other objects or time.
JavaScript implementation
// Gravity
gravity = Vector3(0, -10, 0);
// Particle
class Particle {
position;
velocity;
acceleration;
damping;
inverseMass;
forceAccum;
// Constructor
constructor(position, velocity, acceleration, damping, inverseMass){
this.position = position;
this.velocity = velocity;
this.acceleration = acceleration;
this.damping = damping;
this.inverseMass = inverseMass;
}
// Integrate
integrate(duration){
// We don’t integrate things with infinite mass
if(this.inverseMass <= 0) return;
// Update linear position
this.position.addScaledVector(this.velocity, duration);
// Sum forces applied to acceleration (user-defined + gravity)
var resultingAcc = this.acceleration;
resultingAcc.addScaledVector(this.forceAccum, this.inverseMass);
resultingAcc.addScaledVector(gravity, this.inverseMass);
// Update linear velocity from the acceleration
this.velocity.addScaledVector(resultingAcc, duration);
// Impose drag / damping
this.velocity.scale(this.damping ** duration);
// Reset forces accumulator
this.clearAccumulator();
}
// Add a force
addForce(force){
this.forceAccum.add(force);
}
// Clear accumulated forces
clearAccumulator(){
this.forceAccum = new Vector3(0,0,0);
}
}