2017-06-12 54 views
1

我想用帆布做一個簡單的打火機遊戲。一切都很好,但是當我按左右鍵時,我不知道如何讓它移動。帆布在Keydown上的矩形運動

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

ohh謝謝!! D: – xF4B