Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

c - Why can't I make the ball jump? It is shooting up like a rocket

I am using a library called raylib but that should not be a problem to you because the code I am trying to write should make the ball jump up and after reaching a certain height the ball should come down, just like gravity works. The thing is my code is just shooting the ball upwards, the ball is just teleporting to the top and then coming down just normal. Now I want the ball to go up just like it is coming down.

if(MyBall.y < 340) MyBall.y += 5; // This will attract the ball towards ground once it is up in the air or once it's vertical coordinate value is greater than 340
if(IsKeyPressed(KEY_SPACE) && MyBall.y == 340)  //This if statement will be activated only when ball is grounded and spacebar is pressed.
{
    while(MyBall.y >= 200)  // Here is the problem. while the ball's y coordinate is greater than or equal to 200, that is while the ball is above 200, subtract 5 from its y coordinate. But this code just teleports the ball instead of making it seem like a jump.
    {
        MyBall.y -= 5;
    }
}
if(IsKeyDown(KEY_LEFT) && MyBall.x >= 13) MyBall.x -= 5; //This code is just to move the vall horizontally
if(IsKeyDown(KEY_RIGHT) && MyBall.x <= SCREENWIDTH-13) MyBall.x += 5; //This also moves the ball horizontally.
question from:https://stackoverflow.com/questions/65650280/why-cant-i-make-the-ball-jump-it-is-shooting-up-like-a-rocket

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It won't get out from while loops like while(MyBall.y >= 200) until the condition becomes false, so Myball.y will be 195 after exiting from this loop.

It seems you should introduce a variable to manage status.

Example:

// initialization (before loop)
int MyBall_goingUp = 0;

// inside loop
    if (MyBall_goingUp)
    {
        MyBall.y -= 5;
        if (MyBall.y < 200) MyBall_goingUp = 0;
    }
    else
    {
        if(MyBall.y < 340) MyBall.y += 5; // This will attract the ball towards ground once it is up in the air or once it's vertical coordinate value is greater than 340
        if(IsKeyPressed(KEY_SPACE) && MyBall.y == 340)  //This if statement will be activated only when ball is grounded and spacebar is pressed.
        {
            MyBall_goingUp = 1;
        }
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...