我正在用HTML5画布制作二维平台游戏风格的游戏。在角色中,角色可以使用箭头键跳转并左右移动,除了一个问题外,它可以很好地工作。当我跳到一边的同时,精灵上升,不会移动到一边。只有当它下降时,它才能正常移动。有没有办法解决它?我已经完成了其他“移动精灵对角”问题的研究,但根据我的代码;当我放开'向上'键时,精灵应该移动到一侧,对吧?看看我的代码,看看你的想法...如何用javascript对角地移动精灵?
**注:表现得好像我已经定义的变量,因为我有
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
}
你明白我的代码?我有没有留下什么?这是不是马虎?如果您有任何与问题无关的建议,请随时将其添加到评论中,我会很乐意接受。
回到手边的话题,我的代码是否正确?因为当我点击“向上”键,然后放开并按住“正确”的关键,我的性格的轨迹如下:
第1步:
^
|
|
|
|
|
|
|
**去了罚款,但不会移动到侧面,如预期
第2步:
|_
|_
|_
|_
|
|_
|
\/
**下来,并移动到另一边像它应该
你能帮我吗?如果你不明白我的解释的任何部分,我会接受评论中的批评,毕竟我想变得更好。
_ _
|@| |@|
/_
---___ ___---
---_______---
** thnx提前!!!
哇!棒极了!我会尝试在我的代码中实现它... –