首页 > 解决方案 > 为什么我不能让球跳起来?它像火箭一样飞起来

问题描述

我正在使用一个名为 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.

标签: craylib

解决方案


while(MyBall.y >= 200)在条件变为 false 之前,它不会从 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;
        }
    }

推荐阅读