简体   繁体   中英

Bouncing ball gains momentum

I have the following functions running in a loop. It is a basic bouncing ball. My problem is that the balls dy increases every bounce. How would I make it so it bounces to the same height every time?

function ballUpdate(elapsed)
{
    var timeModifier = elapsed;
    ball.x += (ball.dx*timeModifier);
    ball.y += (ball.dy*timeModifier);
    if(ball.y <= 0)
    {
        ball.dy *= -1;
        ball.y = 0;
    }
    else if(ball.y > 0)
    {
        ball.dy += -.5*timeModifier;
    }
}

function draw()
{
    ball.update();
}

function main(elapsed)
{
    keyinput(elapsed);
    ballUpdate(elapsed);
}

animLoop(main,draw,15);
  1. The first obvious error is that you are trying to multiply the speed by the elapsed time... it doesn't work. What you gotta do is to add the speed (dx,dy) to your (x,y) on every iteration... so forget this elapsed .

  2. The acceleration will be always present... you don't need that if(ball.y > 0)

  3. Because of the adjustment ball.y = 0 when the ball touchs the limit (the floor), invert the speed is not enough. You have to consider the exact speed of the ball when it really touches the limit. In order to do that, you must use the potential energy + kinect energy concept here (Google for it if you wanna know the details of the equation).


Basically this is what you want.

function ballUpdate(elapsed)
{   
    var acceleration = -0.5;

    ball.x += ball.dx;
    ball.y += ball.dy;

    if ( ball.y <= 0 )
    {
        ball.dy = Math.sqrt( -2 * acceleration * ( ball.y - ball.dy ) + ball.dy * ball.dy );
        ball.y = 0;
    }

    ball.dy += acceleration;
}

Copy and paste. It should work. What I did here is to measure the TOTAL ENERGY of ball as the potential energy BEFORE it reaches the limit plus the kinect energy of the ball BEFORE it reaches the limit. After that, I converted this amount of energy totally back to kinect energy, so it gives me a new speedy that is the speed of the ball when it touches the limit. (like the floor or anything else).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM