1
votes

I have recently started programming games in java. I come from a C# / XNA background and i already have experience in game development. However I have a problem in my java game. I have a bouncing script which makes a in-game "particle" bounce upon collision with a solid surface, such as the ground. Here is a snippet of the code that manages the bouncing.

private final void respondY(Rectangle r)
{
    if(!r.intersects(getBounds())) // If not colliding, return
        return;

    if(Yvel > 0) // If falling...
    {
        if(r.y < Y + Height) //Another collision test
        {
            Y = r.y - Height; // Set Y to top of object
            Yvel *= -bounce; // Bounce (Here is the problem)
            onFloor = true;
        }
    }
    else if(Yvel < 0) // If hit ceiling
    {
        if(Y < r.y + r.height) // Collision test
        {
            Y = r.y + r.height; // Set Y to bottom of object
            Yvel = 0; // No bouncing here
        }
    }
}

The problem is that the object bounces upon the floor as it should, but after a while the object bounces constantly at the same height where I want it to stop bouncing when it got to that constant height.

NOTE:

  • Yvel is a int that is the vertical velocity of the object

  • Bounce is a float that controls how "bouncy" a object is. e.g. 0.5 means that it bounces half as high as it fell

Thanks in advance! Please note that this is my first post so if I make mistakes please point them out in a constructive manner.

1

1 Answers

1
votes

The float (and double) types are imprecise. This especially causes problems when dealing with very small numbers - in fact there's a smallest representable number and a finite quantity of possible numbers that can be represented (and bit like quantum physics). The number stored by a float is actually the closest number possible to represent to the calculation result.

What's happening is the velocity calculation never reaches zero, because the result of multiplying the smallest number float can represent by a value >= .5 is itself.

I would force it to zero by putting a low threshold on the calculation result:

Yvel = Yvel * -bounce;
if (Yvel < .000001F)
    Yvel = 0;