c - 为什么我不能让球跳起来?它像火箭一样飞起来
问题描述
我正在使用一个名为 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)
在条件变为 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;
}
}
推荐阅读
- javafx-8 - 限制 JavaFX 浏览器中任何网站的移动视图
- mysql - Aurora rds -> MySQL rds 跨区域复制
- ansible - 如何在构建期间通过ansible访问打包机(IP /主机)
- r - 带有 R 包 Repmis 的重音字母
- laravel - Laravel - 查找名称并显示
- elasticsearch - 具有不同标记位置/偏移的模式捕获
- sql - Laravel:具有不同用户表名的不同列名
- ios - CALayer在不同的屏幕尺寸下绘制不同
- c++ - 如何正确结束 pthread?
- java - 用于 Google Action 的 Java Servlet 不工作,日志给出明显错误