我正在尝试使用 C++ 实现非常基本的平台/精灵行为。
到目前为止,我已经成功渲染了 2 个平台和一个可以移动和跳跃的精灵。下面是一段模拟跳跃和重力的代码片段。
如果我2,3, & 6
从注释为“//gravity”的片段中注释掉行,我不能完美地从下面跳过平台,但我无法登陆它......如果我让它们保持在下面,(使用check_collision
功能),我可以成功跳上平台并左右移动。不幸的是,如果我再按一次跳跃 ( key119
),我会从平台上掉下来,有时甚至会粘在平台下面而不是再跳一次。
我忘记实现什么来让精灵再跳一次?
if(keyDown[119]){ //While 'w' key is pressed and not colliding
if(!check_collision(sprite,platform) //If not colliding...
&& !check_collision(sprite,platform2)){
y_Pos += jumpHeight; //Jump up
if(keyDown[97] ){x_Pos -= velocity*jumpLength;} //While 'w' and 'a' are pressed, simulate arc of jump/gravity
if(keyDown[100]){x_Pos += velocity*jumpLength;} //While 'w' and 'd' are pressed, simulate arc of jump/gravity
}
else //Else you must be colliding, bounce off
y_Pos -= jumpHeight;
}
if(keyDown[115]){y_Pos -= velocity;} //While 's' key is pressed
if(keyDown[97] ){x_Pos -= velocity;} //While 'a' key is pressed
if(keyDown[100]){x_Pos += velocity;} //While 'd' key is pressed
//gravity
if(y_Pos>0){ //If above ground
if(!check_collision(sprite,platform) //And not colliding
&& !check_collision(sprite,platform2)){
gravity-=5*delta; //Calculate gravity force
y_Pos+=gravity; //Descend to ground
}
if(keyDown[97] ){x_Pos -= velocity*2;} //While off ground, whilst 'a' is pressed, move left
if(keyDown[100]){x_Pos += velocity*2;} //While off ground, whilst 'd' is pressed, move right
}
else{gravity=0;} //Else, on ground, so gravity force is zero
请原谅我的天真并耐心等待,我正在自学,我们都必须从某个地方开始。谢谢。
代码太多,无法发布整个程序,但如果您有兴趣,可以在这里找到完整的源代码