0

I tried creating a simple physics based "game" where you can spawn balls and they then get affected by different natural force, like gravity.

But I have a problem, when the ball reaches the floor, and it keeps getting affected by gravity. It kind of vibrates. Here's a quick example of how it looks.

And here is the code for collision detection and the gravity calculation.

public void CheckBounds(int maxHeight, int maxWidth)
{
    if (this.position.Y + (radius + radius) > maxHeight)
        this.velocity.Y = -Math.Abs(velocity.Y * 0.65f); // 0.65 is the "bouncyness"
}

Here is the main Update section

for (int i = 0; i < balls.Count; i++ )
{
    Ball b = balls[i];

    for (int k = 0; k < balls.Count; k++) // check for collision with other balls
    {
        if (balls[i] == balls[k])
            continue;

        if (balls[i].Colliding(balls[k]))
            balls[i].Collide(balls[k]);
    }

    b.velocity.Y += gravitationalPull; // a gravity constant
    b.CheckBounds();
    b.position = Vector2.Add(b.position, b.velocity);
}

Does anyone know how to fix the vibration? I tried setting a minimum value of velocity that the gravity would be calculated (if velocity.y < some value then dont calculate), but then the ball stopped mid air at collisions and even at spawn.

Rufus L
  • 36,127
  • 5
  • 30
  • 43
Tokfrans
  • 1,939
  • 2
  • 24
  • 56
  • There are different ways, one way is to set a bounding box below the box to check with before applying gravity. Otherwise, you must only set the velocity of the ball once at the end of the loop, when it is ok to apply velocity to it – Sayse Oct 29 '14 at 20:27
  • 5
    I think you're getting a bit of floating point error. You might want to make sure that you're setting the ball's velocity and position to 0 after you've detected that the ball has effectively come to a stop. In other words, make sure that once the velocity is < some threshold (e.g. 0.01), then just set the velocity to 0. – jwir3 Oct 29 '14 at 20:31
  • I agree with jwir3 just few days back i answered similar(not the same) question http://stackoverflow.com/a/26270570/2521214 see bullet 1. – Spektre Oct 30 '14 at 08:21
  • same happened to me when i was using velocity * 0.96 to slow down space ship. so when velocity was near 0 i set it to exact 0 otherwise it was allways slightly moving. – Davor Mlinaric Oct 30 '14 at 14:33
  • @DavorMlinaric The thing is: sometimes a ball collides with an other ball at low velocity, which can make it freeze in the air especially since I tracked the "vibration" magnitudes and they are spanning from about -2 to 2.5, which makes the whole thing very tricky to solve – Tokfrans Oct 30 '14 at 15:08

0 Answers0