2017-06-12 3 views
1

キャンバスでシンプルなアルカノイドゲームを作りたいと思います。すべてが大丈夫ですが、左または右のキーを押すと、移動する方法がわかりません。キャンバス長方形の動きでキーダウン

var c = document.getElementById("game"); 
var ctx = c.getContext("2d"); 
document.addEventListener("keydown", Keys); 
var x = 180; 
var rx = 10; 

function init() { 
    drawBackground("#000000"); 
    drawPlayer(); 
} 

function drawBackground(color) { 
    ctx.fillStyle = color; 
    ctx.fillRect(0, 0, 500, 250); 
} 

function drawPlayer() { 
    ctx.fillStyle = "red"; 
    ctx.fillRect(x, 220, 150, 10); 
} 

function moveTo(x) { 
    ctx.clearRect(x, 220, 150, 10); 
} 

function Keys(e) { 
    switch (e.keyCode) { 
     case 37: 
      moveTo(x - rx); 
      break; 
     case 39: 
      moveTo(x + rx) 
    } 
} 

init(); 

これはthe resultです。

ありがとうございます!

答えて

0
var c = document.getElementById("game"); 
var ctx = c.getContext("2d"); 
document.addEventListener("keydown", Keys); 
var x = 180; 
var rx = 10; 

function init() { 
    drawBackground("#000000"); 
    drawPlayer(); 
} 

function drawBackground(color) { 
    ctx.fillStyle = color; 
    ctx.fillRect(0, 0, 500, 250); 
} 

function drawPlayer() { 
    ctx.fillStyle = "red"; 
    ctx.fillRect(x, 220, 150, 10); 
} 

function moveTo(xP) { // changed parameter name 
    x = xP; // update variable x 
    init(); // redraw background and player 
} 

function Keys(e) { 
    switch ((e.keyCode || e.which)) { // some browsers use e.which 
     case 37: 
      moveTo(x - rx); 
      break; 
     case 39: 
      moveTo(x + rx) 
    } 
} 

init(); 

これは正しいコードです。 x変数を設定する必要があり、バックグラウンドを再描画する必要があります。

+0

ありがとうございます! :D – xF4B

関連する問題