为啥我不能让球跳起来?它像火箭一样飞起来
Posted
技术标签:
【中文标题】为啥我不能让球跳起来?它像火箭一样飞起来【英文标题】:Why can't I make the ball jump? It is shooting up like a rocket为什么我不能让球跳起来?它像火箭一样飞起来 【发布时间】:2021-01-10 05:05:13 【问题描述】:我正在使用一个名为 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.
【问题讨论】:
你认为我们可以如何测试这段代码?你读过How to create a Minimal, Reproducible Example??? 【参考方案1】:在条件变为 false 之前,它不会从像 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;
【讨论】:
代码实际上可以工作,但我不明白它是如何工作的。能给我解释一下吗? 不要在一帧中对 195 进行所有减法,而是跟踪帧中要执行的操作并执行此操作。 好吧,这是有道理的,但是为什么仅仅通过引入 bool 或 int(在这种情况下为 int)允许我们减去不同帧中的值。以上是关于为啥我不能让球跳起来?它像火箭一样飞起来的主要内容,如果未能解决你的问题,请参考以下文章