【发布时间】:2015-09-05 15:28:07
【问题描述】:
我正在使用 HTML5 画布制作一款 2-D 平台风格的游戏。在其中,角色可以使用箭头键跳跃和左右移动,除了一个问题外,它工作正常。当我同时跳跃并移动到一边时,精灵会上升并且不会移动到一边。只有当它下降时,它才会正确移动。有没有办法解决它?我已经对其他“对角移动精灵”问题进行了研究,但根据我的代码;当我松开“向上”键时,精灵应该移到一边,对吗?看看我的代码,看看你的想法......
**注意:就像我已经定义了变量一样,因为我已经定义了
window.addEventListener("keydown", checkKeyPressed, false);
//^don't proceed if you don't know what this means^
function checkKeyPressed(e) {
if (e.keyCode == "38" && jumpTime == 0) {
//checks if 'up' key is pressed then initiates the 'jump' sequence
refreshIntervalId = setInterval(jumpUp, 5);//calls the jump function
setTimeout(stopRefresh, 500);//sets time until character stops jumping
jumpCal();//temporarily disables jumping, and therefore a double-jump
}else if (e.keyCode == "37") {
//checks if 'left' key is pressed then moves sprite to the side
charX = charX - 8;//piece 1,
a = a - 8;//2,
c = c - 8;//and 3
}else if (e.keyCode == "39") {
//same thing, except to the right...
charX = charX + 8;
a = a + 8;
c = c + 8;
}
}
function jumpUp() {
charY = charY - 5;//moves up pieces 1,
b = b - 5;//2,
d = d - 5;//and 3, since the sprite is composed of three images
}
function stopRefresh() {
clearInterval(refreshIntervalId);
//stops the character from jumping
}
function jumpCal() {
jumpTime = 1;
setTimeout(jumpRes, 1750);
//times out the jumping action
}
function jumpRes() {
jumpTime = 0;
//resets the jumping action
}
function gravityControl() {
if (charY <= platformDetect) {
//checks if touching platform then moves all pieces down
charY = charY + 3;//piece 1
b = b + 3;//piece 2
d = d + 3;//piece 3
//this function is called multiple times in an unspecified piece of code, so no, I did not make an error here
}
}
function detectPlatform() {
platformDetect = 160;
//I've added this function because there will be platforms later in the game
}
你看懂我的代码了吗?我有遗漏什么吗?是不是太草率了?如果您有任何与问题无关的建议,请随时将其添加到 cmets,我将很乐意接受。
回到手头的话题,我的代码对吗?因为当我点击“向上”键然后松开并按住“向右”键时,我的角色轨迹如下:
第 1 步:
^
|
|
|
|
|
|
|
**上升良好,但没有像预期的那样移动到一边
第 2 步:
|_
|_
|_
|_
|
|_
|
\ /
**像它应该的那样下来并移到一边
你能帮帮我吗?如果你不理解我的解释的任何部分,我会接受在 cmets 中的批评,毕竟我确实想变得更好。
_ _
|@| |@|
/_
---___ ___---
---_______---
**提前!!!
【问题讨论】:
标签: javascript html html5-canvas keypress