我希望我的对象(此时为矩形)跳跃一次,以在上升过程中失去速度。当它快要停止时,我希望它转回去并在下降的过程中提高速度。当它再次撞到地面时,它应该停止。当我再次按下该键时,它应该再次执行相同的操作。 我尝试编写的代码实现了一个变量 当速度大于1时,应将速度乘以矩形的Y坐标,然后再降低速度,因为我将其乘以小于1的重力 引力大于1但为负,因此我在下一级求和的数字加起来而矩形变小。为了获得速度,速度乘以重力。 现在速度应该约为-1.2 ...,因此它小于-1,因此 然后重力应再次达到0.75,速度应达到10。 因此,矩形不是不断地跳(我认为)10像素,仅此而已。 答案 0 :(得分:1) 如果使用while循环来计算Y位置,则将无法可视化跳转模拟,因为所有数学运算都将在单个帧中进行计算。
要进行基于物理的跳跃模拟,您将需要有一个代表地面的变量(这是您的初始Y变量),而且,一旦玩家单击,就需要将速度变量赋予全速,然后每帧减小它检查您是否还没有到达地面的每一帧时的重力大小。
这是我写的一个示例,用来证明我尝试保留您的变量名:
float gravity = 0.75;
和一个跟踪速度float speed = 10;
的变量
else if (keyCode == UP|| key == 'w') {
while (speed >1 ) {
playerYPosition = playerYPosition-speed;
speed = speed * gravity;
}
gravity = -1.25;
speed = speed * gravity;
playerYPosition = playerYPosition-speed;
while(...)
应该可以工作。同样,它应该随着时间的流逝而提高速度,直到达到起始速度为止,只是负值并以此为起点。while (speed < -1 && speed > -10) {
playerYPosition = playerYPosition-speed;
speed = speed * gravity;
gravity = 0.75;
speed = 10;
float gravity = 0.75;
float speed = 10;
else if (keyCode == UP|| key == 'w') {
while (speed >1 ) {
playerYPosition = playerYPosition-speed;
speed = speed * gravity;
}
gravity = -1.25;
speed = speed * gravity;
playerYPosition = playerYPosition-speed;
while (speed < -1 && speed > -10) {
playerYPosition = playerYPosition-speed;
speed = speed * gravity;
}
gravity = 0.75;
speed = 10;
1 个答案:
final float gravity = 0.5;
final float jmp_speed = 10; //the speed which the square is going to jump
float speed = 0; //the actual speed every frame
final float ystart = 280; //the initial Y position ( which also represent the Y of the ground )
float playerYPosition = ystart; //give the player the Y of the ground on start
void setup(){
size(300,300);
}
void keyPressed() {
//also check that the player is on ground before jumping
if( (keyCode == UP || key == 'w') && (playerYPosition == ystart) )
{
speed=-jmp_speed; //when the player press jump and he is on ground we give speed the max value
}
}
void draw(){
background(150);
rect(150,playerYPosition,10,10);
//this code will be executed every frame
//check if the player Y position won't hit the ground if we increment it by speed
if(playerYPosition+speed < ystart)
{
playerYPosition+=speed;
speed+=gravity; //increment speed by gravity ( will make speed value go from negative to positive slowly)
}
else
{
//if the player is gonna hit the ground the next frame
playerYPosition = ystart; // put back the player on ground
speed=0; // make the speed 0
}
}