Search code examples
c#2dgame-physicsphysics

Rare physics edge case with 2D movement


I'm building a space ship based game and I have an intermittent issue where my Force's sky rocket to infinity. I'm assuming the issue is related to these relation ships:

  • Acceleration depends on Force
  • Velocity depends on Acceleration
  • DragForce (Force) depends on Velocity

Here's the ship game: http://shootr.signalr.net

And here's a re-factoring (to make it not as large, combined some functions down) of the physics equation behind the movement.

double PercentOfSecond = (DateTime.UtcNow - LastUpdated).TotalMilliseconds / 1000;

// Mass = 50
_acceleration += Forces / Mass;

Position += Velocity * PercentOfSecond + _acceleration * PercentOfSecond * PercentOfSecond;
Velocity += _acceleration * PercentOfSecond;

_acceleration = new Vector2();
Forces = new Vector2();

// DRAG_COEFICCIENT = .2,  DRAG_AREA = 5
Vector2 direction = new Vector2(Rotation), // Calculates the normalized vector to represent the rotation
        dragForce = .5 * Velocity * Velocity.Abs() * DRAG_COEFFICIENT * DRAG_AREA * -1;

Forces += direction * ENGINE_POWER; // Engine power = 110000

LastUpdated = DateTime.UtcNow;

Solution

  • First of all, you have an inappropriate operation which will only work if you assume the vectors are initialized to the zero vector. eg:

    _acceleration += Forces / Mass; // your code
    _acceleration = Forces / Mass; // what it should be
    

    Your Forces should also be:

    Forces = direction * ENGINE_POWER + dragForce;
    

    If that does not help with your problem, then you have issues with the calculation of the direction vector. Ensure that it is normalized. Your dragForce equation looks fine. However, make sure you add it and not subtract as you have already multiplied dragForce by -1.