1

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.
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Abhishek
  • 43
  • 1
  • 1
  • 8
  • How do you think we can test this piece of code? Have you read [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example)??? – Luis Colorado Jan 11 '21 at 16:53

1 Answers1

4

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;
        }
    }
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • The code is actually working but I didn't understand how it worked. Can you please explain it to me? – Abhishek Jan 10 '21 at 05:24
  • Instead of doing all subtraction toward 195 in one frame, keep track what to do in the frames and do that. – MikeCAT Jan 10 '21 at 05:26
  • Okay that makes sense but How come just by introducing a bool or an int (int this case) allowed us to subtract the values in different frames. – Abhishek Jan 10 '21 at 05:33