所以我试图从头开始制作一个贪吃蛇游戏,作为用 javascript 制作游戏的练习。我已经在 Canvas 内制作了正方形,现在我正在尝试让它移动。这是我为此编写的代码。
<!DOCTYPE html>
<html>
<body>
<canvas id = "gameCanvas" width="700" height="600" style="border:4px solid black; background-color: yellow"></canvas>
<script type = "text/javascript">
var myCanvas = document.getElementById("gameCanvas");
var ctx = myCanvas.getContext("2d");
this.x = 0;
this.y = 0;
var snake = ctx.fillRect(this.x,this.y,10,10);
myMovement = function(){
var moveUp = event.keyCode;
if(moveUp == 39){
snake = ctx.fillRect(this.x + 1, this.y,10,10);
}
}
</script>
</body>
</html>
不幸的是,当我按下按钮时,什么也没有发生。我的代码有什么问题。
最佳答案
您的代码存在一些问题。
- 您在要引用全局对象的地方使用
this
(在本例中为window
)。 - 您的
myMovement
函数没有附加到任何东西,这意味着它没有设置为事件监听器,按下按键时需要调用它 - 即使您的 myMovement 已设置,它也没有将
event
对象定义为参数,因此您的函数会出错,因为不会有event
> 要访问的对象
对于1,如果您想要跟踪 x,y,您可以将它们放在一个对象中并从那里访问它们:
var rect={
x:0,
y:0
};
//then when needing to use them access them like rect.x, rect.y
//also fillRect doesn't return anything so no need for "var snake = "
ctx.fillRect(rect.x, rect.y, 10, 10);
对于2和3,您可以使用各种按键*事件来实现您的功能。您可以使用 addEventListener 附加该函数。最后为您的函数定义一个 event
参数,以便您实际上拥有一个可以使用的事件对象:
function myMovement(event) {
var moveUp = event.keyCode;
if(moveUp == 39){
//++rect.x adds one and assigns the new value to rect.x
//and again fillRect doesn't return a value so no need for "snake ="
ctx.fillRect(++rect.x, rect.y,10,10);
}
}
window.addEventListner("keydown",myMovement);
<小时/>
演示
var myCanvas = document.getElementById("gameCanvas");
var ctx = myCanvas.getContext("2d");
var rect = {
x: 0,
y: 0
};
ctx.fillRect(rect.x, rect.y, 10, 10);
window.onkeydown = function(event) {
var moveUp = event.keyCode;
if (moveUp == 39) {
//erase last fill
ctx.clearRect(rect.x, rect.y, 10, 10);
ctx.fillRect(++rect.x, rect.y, 10, 10);
}
}
<canvas id="gameCanvas" width="100%" height="100%" style="border:4px solid black; background-color: yellow"></canvas>
关于javascript - 为什么当我按下按键时我的矩形不会移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52508445/