我正在学习制作一个简单的游戏并成功编写了一个非常基本的弹跳动作,其中在按下跳跃键之后,玩家再次回到地面并再次反弹,创造了一个有点愚蠢的物理错觉。我遇到的问题是如何实现它,以便玩家不会反弹一次而是反弹两次,第二次以较低的速度反弹。换句话说,现在的代码(我稍后会展示它)非常简单:有一个标记为"跳过",一旦跳转,标志变为真,然后开启在那里的下一帧是检查它是否真实,如果是,我只是在y轴速度上添加一些速度,并且玩家反弹。但我似乎无法找到一种方法来编码第二次反弹,因为所有事情都是逐帧发生的。我需要为第二次弹跳增加更少的速度,但只有在第一次弹跳发生之后,我现在所能得到的只是这些速度的总和而只是一次反弹。我不知道如何欺骗程序添加第一个速度,"等待"直到它撞到地面,然后添加第二帧,然后绘制下一帧。
这里是单次反弹的代码(可行)
if (y <= 48) { // if player is on the ground
yspeed = 0;
y = 48;
// Friction on ground
if ((!Keyboard.isKeyDown(Keyboard.KEY_LEFT)) && xspeed < 0) xspeed = xspeed * 0.925;
if ((!Keyboard.isKeyDown(Keyboard.KEY_RIGHT)) && xspeed > 0) xspeed = xspeed * 0.925;
if (jumped == true)
{
yspeed += 4.2;
jumped = false;
}
// Jump
if (Keyboard.isKeyDown(Keyboard.KEY_UP))
{
yspeed = 10;
jumped = true;
}
答案 0 :(得分:1)
我会重新安排代码是这样的:
boolean airborne = false;
while (true) // the main game loop
{
if (y <= 48 && airborne) // if player just hit the ground
{
// Perform the "bounce" by changing their vertical direction and decreasing its magnitude
ySpeed = -ySpeed/2.0;
// This will stop them from bouncing infinitely. After the bounce gets too small,
// they will finally land on the ground. I suggest you play around with this number to find one that works well
if (Math.abs(ySpeed) <= 0.5)
{
// Stop the bouncing
ySpeed = 0;
// Place them on the ground
airborne = false;
y = 48;
}
}
// Apply friction if they are on the ground
if (!airborne)
{
// Friction on ground
if ((!Keyboard.isKeyDown(Keyboard.KEY_LEFT)) && xspeed < 0) xspeed = xspeed * 0.925;
if ((!Keyboard.isKeyDown(Keyboard.KEY_RIGHT)) && xspeed > 0) xspeed = xspeed * 0.925;
}
// Apply a jump action if they're pressing the jump button while on the ground
if (Keyboard.isKeyDown(Keyboard.KEY_UP) && !airborne)
{
airborne = true;
yspeed = 10;
}
}
因此,在这种情况下,不是跟踪他们是否刚刚执行了跳跃,而是跟踪他们是否在空中。
我假设你有某种重力常数,你每帧都从ySpeed变量中减去。每个框架,如果它们在地面上,你会想要将它们的ySpeed重置为零,或者只是在它们在地面时不施加重力