如果请求动画帧中的语句继续,即使不满足参数



我正在制作一个小视频游戏,背景(平台(随着我的角色(方块(的跳跃而向下移动。在第113行,我尝试了不同的策略来实现这一想法,这是它最接近奏效的一次。问题是,即使平方速度为0,平台速度也不是。我已经被困了一个星期,感觉javascript是个问题(尽管我知道不是(。


canvasmain.width  = window.innerWidth;
canvasmain.height = window.innerHeight;
//CHARACTER:
const square = {
height: 75,
jumping: true,
width: 75,
x: canvasmain.width / 2,
xVelocity: 0,
y: canvasmain.height / 2,
yVelocity: 0
};
//floor
const platform = {
height: 30,
width: 100,
x: square.x,
xVelocity: 0,
y: square.y + square.height,
yVelocity:0
}
//MOVEMENT:
const controller = {
left: false,
right: false,
up: false,
keyListener: function (event) {
let key_state = (event.type == "keydown") ? true : false;
switch (event.keyCode) {
case 37: // left arrow
controller.left = key_state;
break;
case 38: // up arrow
controller.up = key_state;
break;
case 39: // right arrow
controller.right = key_state;
break;
}
}
};
const loop = function () {
if (controller.up && square.jumping == false) {
square.yVelocity -= 30;
square.jumping = true;
}

if (controller.left) {
square.xVelocity -= 0.5;
}

if (controller.right) {
square.xVelocity += 0.5;
}

square.yVelocity += 1.5;// gravity
square.x += square.xVelocity;
square.y += square.yVelocity;
square.xVelocity *= 0.9;// friction
square.yVelocity *= 0.9;// friction
// if square is falling below floor line
if (square.y > canvasmain.height - 75) {

square.jumping = false;
square.y = canvasmain.height - 75;
square.yVelocity = 0;

}

// if square is going off the left of the screen
if (square.x < 0) {

square.x = 0;

} else if (square.x > canvasmain.width - 75) {// if square goes past right boundary

square.x = canvasmain.width - 75;

}
// Creates the backdrop for each frame
context.fillStyle = "#394129";
context.fillRect(0, 0, canvasmain.width, canvasmain.height); // x, y, width, height

// Creates and fills the cube for each frame
context.fillStyle = "#8DAA9D"; // hex for cube color
context.beginPath();
context.rect(square.x, square.y, square.width, square.height);
context.fill();

// Creates the "ground" for each frame
context.fillStyle = "#202020";
context.beginPath();
context.rect(platform.x, platform.y, platform.width, platform.height)
context.fill();
// call update when the browser is ready to draw again
window.requestAnimationFrame(loop);
//platform
platform.y += platform.yVelocity;
console.log(square.yVelocity)

if (square.yVelocity > 0.1 ) {
platform.yVelocity = 1.5
};

if (square.yVelocity < 0 ) {
platform.yVelocity = -1.5
};
}
window.addEventListener("keydown", controller.keyListener)
window.addEventListener("keyup", controller.keyListener);
window.requestAnimationFrame(loop);

您没有重置yVelocity的值。

明白了,伙计们,thx@Teemu,如果不是if,我只需要把它设置为0。当,真的花了一段时间。if (square.yVelocity > 0 ) {platform.yVelocity = 1.5} else{ platform.yVelocity = 0}; if (square.yVelocity < 0 ) {platform.yVelocity = -1.5} else { platform.yVelocity = 0} }edit:frick,它只在立方体上升时移动平台,而不是下降;-;

最新更新