为什么我不能让球跳?它像火箭一样飞起来

问题描述

我正在使用一个名为 raylib 的库,但这对您来说应该不是问题,因为我尝试编写的代码应该使球跳起来,并且在达到一定高度后球应该下降,就像重力一样。 问题是我的代码只是向上射球,球只是传送到顶部然后正常地落下。现在我希望球像落下一样向上。

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.

解决方法

它不会从像 while(MyBall.y >= 200) 这样的 while 循环中退出,直到条件变为假,所以退出这个循环后 Myball.y 将是 195

看来你应该引入一个变量来管理状态。

示例:

// 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;
        }
    }