我正在用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提前!!!
哇!棒極了!我會嘗試在我的代碼中實現它... –