I'm building a physics engine and i had some sort of "pseudo-verlet" thing going and i wanted to upgrade it to "real" verlet. So i found an article and set to work. After i added what i think is a good approximation, the engine doesn't work anymore. Can someone help me understand what i'm doing wrong?
My main physics body class's update, apply force, and apply impulse systems:
public void Update(float timestepLength)
{
if (!this._isStatic)
{
Vector2 velocity = Vector2.Subtract(_position, _lastPosition);
Vector2 nextPos = _position + (_position - _lastPosition) + _acceleration * (timestepLength * timestepLength);
_lastPosition = _position;
_position = nextPos;
_acceleration = Vector2.Zero;
}
}
public void ApplyForce(Vector2 accelerationValue)
{
if (!this._isStatic)
_acceleration += (accelerationValue) * _mass;
}
public void ApplyImpulse(Vector2 impulse)
{
if (!this._isStatic)
_acceleration +=-1 * impulse;
}
Edit: I've fixed it and it works like a charm, but i have two questions about the following code:
- Is the impulse application code correct, and if not what should it be?
- How do i change the position property so that setting it preserves the current velocity of the body?
Here is the code:
public Vector2 Position
{
get { return _position; }
set { _position = value;}
}
public void Update(float timestepLength)
{
if (!this._isStatic)
{
Vector2 velocity = Vector2.Subtract(_position, _lastPosition);
Vector2 velocityChange = Vector2.Subtract(velocity, Vector2.Subtract(_lastPosition, _twoStepsAgoPosition));
Vector2 nextPos = _position + (_position - _lastPosition) + _acceleration * (timestepLength * timestepLength);
_twoStepsAgoPosition = _lastPosition;
_lastPosition = _position;
_position = nextPos;
_acceleration = Vector2.Multiply(velocityChange, timestepLength);
}
}
public void ApplyForce(Vector2 force)
{
if (!this._isStatic)
_lastPosition -= force;
}
public void ApplyImpulse(Vector2 impulse)
{
if (!this._isStatic)
_acceleration +=-1 * impulse;
}