【问题标题】:JavaScript: Object is causing bug?JavaScript:对象导致错误?
【发布时间】: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


【解决方案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;

【讨论】:

  • 您的意思是我应该将代码底部的对象重命名为其他名称吗?
  • 考虑为其添加前缀,例如 function GameObjectObject 是所有其他对象继承自的内置核心对象。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-07
  • 2013-06-12
  • 2015-03-06
  • 2020-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多