Luk*_*kas 3 processing physics
我希望我的对象(此时是一个矩形)跳一次,在上升的过程中失去速度。当它几乎停止时,我希望它在下降的过程中掉头并获得速度。当它再次撞击地面时,它应该停止。当我再次按下该键时,它应该再次执行相同的操作。
我尝试编写的代码实现了一个变量float gravity = 0.75;和一个跟踪速度的变量float speed = 10;
当速度大于 1 时,速度应该被矩形的 Y 坐标减去,然后速度应该变低,因为我将它乘以小于 1 的重力
else if (keyCode == UP|| key == 'w') {
while (speed >1 ) {
playerYPosition = playerYPosition-speed;
speed = speed * gravity;
}
Run Code Online (Sandbox Code Playgroud)
Gravity 高于 1 但为负,因此我 substrakt 的数字在 final 中相加,矩形变小。为了获得速度,速度乘以重力。
gravity = -1.25;
speed = speed * gravity;
playerYPosition = playerYPosition-speed;
Run Code Online (Sandbox Code Playgroud)
速度现在应该在 -1.2 左右......,所以它小于 -1,这while(...)应该可以工作。再次它应该随着时间的推移获得速度,直到它达到起始速度,只是负面的,并以此为起点。
while (speed < -1 && speed > -10) {
playerYPosition = playerYPosition-speed;
speed = speed * gravity;
Run Code Online (Sandbox Code Playgroud)
然后重力应该再次变为 0.75,速度变为 10。
gravity = 0.75;
speed = 10;
Run Code Online (Sandbox Code Playgroud)
所以不是这样做,矩形只是不断地跳跃(我认为)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;
Run Code Online (Sandbox Code Playgroud)
小智 5
如果您使用 while 循环来计算您的 Y 位置,您将无法可视化您的跳跃模拟,因为所有数学运算都将在单个帧中计算。要进行基于物理的跳跃模拟,您需要有一个代表地面的变量(这是您的初始 Y 变量),此外,一旦您的玩家单击,您将需要为速度变量提供全速,然后每一帧都会降低它如果您尚未到达地面,则在检查每一帧时根据您的重力大小。这是我写的一个例子来证明,我尝试保留你的变量名:
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
}
}
Run Code Online (Sandbox Code Playgroud)