我一直关注如何在JavaScript中制作平台游戏的this video。在这段视频之前,一切都很顺利。我已经能够让我的精灵出现在画布上,但是当我编写按键代码时,它停止了工作;当我尝试运行它时,HTML页面变为空白。我已经弄清楚哪一行是问题,但我不知道如何解决它。这是HTML文件:
<body onkeydown="keyDown(event)" onkeyup="keyUp(event)">
<canvas id="graphics" width=600 height=400 style="position:absolute;top:0;left:0;"></canvas>
<script>
//VARIABLES
var gameCanvas = document.getElementById("graphics");
var grafx = gameCanvas.getContext("2d");
var player = new Object("Character1NoAA.png",100,100);
var img = new Image();
img.src = "Character1NoAA.png";
var isLeft = false;
var isRight = false;
//EVENTS
function keyDown(e) {
if (String.fromCharCode(e.keyCode) === "%") isLeft = true;
if (String.fromCharCode(e.keyCode) === "'") isRight = true;
}
function keyDown(e) {
if (String.fromCharCode(e.keyCode) === "%") isLeft = false;
if (String.fromCharCode(e.keyCode) === "'") isRight = false;
}
//MAINLOOP
MainLoop();
function MainLoop() {
//PRE VARIABLE ADJUSTMENTS
player.X += player.Velocity_X;
player.Y += player.Velocity_Y;
//LOGIC
if (isLeft) player.Velocity_X = -3;
if (isRight) player.Velocity_X = 3;
if (!isLeft && !isRight) player.Velocity = 0;
//POST VARIABLE ADJUSTMENTS
player.X += player.Velocity_X;
player.Y += player.Velocity_Y;
//RENDERING
grafx.clearRect(0,0,gameCanvas.width, gameCanvas.height);
grafx.drawImage(player.Sprite,player.X,player.Y);
setTimeout(MainLoop, 1000/60);
}
function Object(img,x,y) {
this.Sprite = new Image();
this.Sprite.src = img;
this.X = x;
this.Y = y;
this.Previous_X;
this.Previous_Y;
this.Velocity_X;
this.Velocity_Y;
}
</script>
</body>
我注意到,当我从代码中删除player.X += player.Velocity_X;
和player.Y += player.Velocity_Y;
行(位于//PRE VARIABLE ADJUSTMENTS
评论下)时,图片显示正常。我在这做错了什么?这变得非常令人沮丧。
答案 0 :(得分:1)
this.Previous_X;
this.Previous_Y;
this.Velocity_X;
this.Velocity_Y;
这些行什么都不做。它当然没有定义那些属性。因此,当“预变量调整”代码第一次运行时,它会尝试访问导致NaN
坐标的未定义属性。
尝试:
this.Previous_X = this.X;
this.Previous_Y = this.Y;
this.Velocity_X = 0;
this.Velocity_Y = 0;