我在Javascript中制作一个侧滚动游戏,需要为我的角色实现重力。例如,角色需要向上跳,向右跳或向左跳,然后通过单独按下并释放向上箭头或使用向左或向右箭头键逐渐降低。到目前为止,这是我的代码:
var gameChar_x; //refers to the characters x position
var gameChar_y; //refers to the characters y position
var floorPos_y; //refers to the y position of the floor
var isJumping = false;
function draw()
if (isJumping == true && gameChar_y == floorPos_y) {
gameChar_y = gameChar_y - 9.8 //makes the character jump when on the floor
}
if (isJumping == false && gameChar_y != floorPos_y) {
gameChar_y = gameChar_y + 9.8 //makes the character come back down when
the up arrow key is released
function keyPressed()
if (keyCode == UP_ARROW && gameChar_y == floorPos_y) { //jump if character is on the floor
isJumping = true;
}
if (keyCode == UP_ARROW && keyCode == RIGHT_ARROW) {
isJumping = true;
}
if (keyCode == UP_ARROW && keyCode == LEFT_ARROW) {
isJumping = true;
}
我想要发生的事情是当按下并释放向上箭头时,角色会跳起并缓慢地一次向下返回到地面1个像素。谢谢你的帮助。
答案 0 :(得分:0)
您可以尝试使用间隔来模拟每100毫秒下降1个像素的动画:
// Max height a character can jump
const MAX_JUMP_HEIGHT = 10;
// Current position of the character
let x_position = 0;
let y_position = 0;
// Timer variable
let timer = null;
function render() {
// draw the character on the screen according to the current x_position and y_position
}
function onJump() {
// If we're already jumping, we want to cancel the previous jump timeout so gravity suddenly doesn't double.
if ( timer ) clearInterval( timer );
// Set our current position to max jumping height.
y_position = MAX_JUMP_HEIGHT;
timer = setInterval( function() {
// subtract one pixel from the the current position
y_position--;
// call a render function
render();
// Cancel the interval once we reach 0px jump height.
if ( !y_position ) clearInterval( timer );
}, 100 );
};
您可以稍微编辑一些数字以获得平台工作的内容,其中0px y_position并不总是基线,并且我们希望使用MAX_HEIGHT作为每次跳转的偏移量。