2015-11-08 114 views
0

好的,所以我正在開發一個簡單的Agar,但只有2個玩家。我已經獲得了大部分基本功能,除非我無法弄清楚如何同時處理來自兩個玩家的按鍵事件。 (一次只能移動一次)這是我的jsFiddle。有關片段:同時收聽多個按鍵事件

if (keysArr.toString() === "37,87") { 
    player.dir = "left"; 
    player2.dir = "up"; 
    keys = []; 
} 

if (keysArr.toString() === "38,87") { 
    player.dir = "up"; 
    player2.dir = "up"; 
} 

if (keysArr.toString() === "39,87") { 
    player.dir = "right"; 
    player2.dir = "up"; 
} 

if (keysArr.toString() === "40,87") { 
    player.dir = "down"; 
    player2.dir = "up"; 
} 

if (keysArr.toString() === "37,65") { 
    player.dir = "left"; 
    player2.dir = "left"; 
} 

if (keysArr.toString() === "38,65") { 
    player.dir = "up"; 
    player2.dir = "left"; 
} 

if (keysArr.toString() === "39,65") { 
    player.dir = "right"; 
    player2.dir = "left"; 
} 

if (keysArr.toString() === "40,65") { 
    player.dir = "down"; 
    player2.dir = "left"; 
} 

if (keysArr.toString() === "37,83") { 
    player.dir = "left"; 
    player2.dir = "down"; 
} 

if (keysArr.toString() === "38,83") { 
    player.dir = "up"; 
    player2.dir = "down"; 
} 

if (keysArr.toString() === "39,83") { 
    player.dir = "right"; 
    player2.dir = "down"; 
} 

if (keysArr.toString() === "40,83") { 
    player.dir = "down"; 
    player2.dir = "down"; 
} 

if (keysArr.toString() === "37,68") { 
    player.dir = "left"; 
    player2.dir = "right"; 
} 

if (keysArr.toString() === "38,68") { 
    player.dir = "up"; 
    player2.dir = "right"; 
} 

if (keysArr.toString() === "39,68") { 
    player.dir = "right"; 
    player2.dir = "right"; 
} 

if (keysArr.toString() === "40,68") { 
    player.dir = "down"; 
    player2.dir = "right"; 
} 

if (keysArr.toString() === "37") { 
    player.dir = "left"; 
} 

if (keysArr.toString() === "38") { 
    player.dir = "up"; 
} 

if (keysArr.toString() === "39") { 
    player.dir = "right"; 
} 

if (keysArr.toString() === "40") { 
    player.dir = "down"; 
} 

我想不出另一種方式,所以我只是用了一堆,如果的。

所以,這段代碼可以讓兩個玩家同時移動,但是在最初的一個之後,他們不能再次轉動。我該如何做到這一點,這樣既可以同時移動,又可以隨後轉向?

回答

1

第一個按下的第二個鍵被檢測到,因爲另一個玩家會移動。

您必須將所有ELSEIF更改爲簡單IF。將玩家2 elseif綁定到玩家1如果意味着如果玩家1按下一個鍵,它將永遠不會到達玩家2的elseif狀態。這將解決您的主要問題。

document.onkeydown和document.onkeyup偵聽器不需要每次重複初始化,只需要一次。

我修改了你的jsFiddle以反映這些變化。然後,我被帶走並將代碼放在document.onkeyup中,導致玩家停止移動,因爲它困擾着我。請享用! https://jsfiddle.net/wtqk7Lu2/1/

if (player2.dir === keys.w) { 
    player2.y -= player2.speed.y; 
} 
if (player.dir === keys.up) { 
    player.y -= player.speed.y; 
} 
if (player2.dir === keys.a) { 
    player2X -= player2.speed.x; 
} 
if (player.dir === keys.left) { 
    player1X -= player.speed.x; 
} 
if (player2.dir === keys.s) { 
    player2.y += player2.speed.y; 
} 
if (player.dir === keys.down) { 
    player.y += player.speed.y; 
} 
if (player2.dir === keys.d) { 
    player2X += player2.speed.x; 
} 
if (player.dir === keys.right) { 
    player1X += player.speed.x; 
} 
+1

完美,謝謝。然而,我重新編輯它以使它繼續移動,因爲這是使瓊脂具有挑戰性的原因;你不能停下來。 – Raiden