【发布时间】:2014-03-12 15:46:51
【问题描述】:
我一直在关注this video,了解如何使用 JavaScript 制作平台游戏。在这个视频之前,一切都很好。我已经能够让我的精灵出现在画布上,但是当我编写按键代码时,它停止了工作;当我尝试运行它时,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 注释下),图片看起来很好。我在这里做错了什么?这变得非常令人沮丧。
【问题讨论】:
-
检查浏览器控制台是否存在 JavaScript 错误
-
看来
var player = new Object("Character1NoAA.png", 100, 100);行正在创建一个字符串。检查this小提琴... -
如果没有indentation,您的代码很难阅读。
标签: javascript html object