gpt4 book ai didi

javascript 跳跃字符不起作用

转载 作者:行者123 更新时间:2023-12-03 04:06:58 25 4
gpt4 key购买 nike

我的代码有一些问题。无法让我的立方体跳跃。看看我的代码,如果您能提供帮助,请告诉我。

我的左、右和鸭子能力目前都达到了所需的水平,但我无法让我的立方体跳跃。我已经尝试了三天,但在网上找不到任何东西。我的 javascript 嵌入在 html 页面的标签内。

var canvas = document.getElementById("gameCanvas");

var ctx = canvas.getContext("2d");

var coinRad = 8;
var coinX = 40;
var coinY = 80;

var x = 20;
var y = 510;
var w = 30;
var h = 50;

var rightPressed = false;
var leftPressed = false;

var ducked = false;
var jumping = false;

document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);

function keyDownHandler(e) {
if (e.keyCode == 39) {
rightPressed = true;
} else if (e.keyCode == 37) {
leftPressed = true;
} else if (e.keyCode == 40) {
ducked = true;
} else if (e.keycode == 32) {
jumping = true;
}
}


function keyUpHandler(e) {
if (e.keyCode == 39) {
rightPressed = false;
} else if (e.keyCode == 37) {
leftPressed = false;
} else if (e.keyCode == 40) {
ducked = false;
} else if (e.keycode == 32) {
jumping = false;
}
}

function drawCube() {
ctx.beginPath();
ctx.rect(x, y, w, h);
ctx.fillStyle = "Green";
ctx.fill();
ctx.closePath();
}

function run() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (leftPressed) {
if (x > 0) {
x -= 2.5;
}
} else if (rightPressed) {
if (x < canvas.width - w) {
x += 2.5;
}
}
if (jumping) {
y -= 10;
h -= 10;
}
if (ducked) {
y = 535;
h = 25;
} else {
y = 510;
h = 50;
}
drawCube();
}

setInterval(run, 10);
<canvas id="gameCanvas"></canvas>

最佳答案

此外,您的 keyCode 检查对于跳转条件的大小写不正确。

else if (e.keyCode == 40) {
ducked = false;
} else if (e.keycode == 32) { //should be keyCode
jumping = false;
}

关于javascript 跳跃字符不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44507262/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com