【发布时间】:2014-04-17 06:32:25
【问题描述】:
我正在用 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 GameObject("Character1NoAA.png",100,100,64,59);
var maxBlock = 4;
var block = new Array();
for (var i=0;i<=maxBlock;i++) {
block[i] = new GameObject("Block.png",i*62+100,300,62,62);
}
var img = new Image();
img.src = "Character1NoAA.png";
var isLeft = false;
var isRight = false;
var isUp = false;
player.Gravity = 20;
player.Weight = 0.3;
//EVENTS
function keyDown(e) {
if (String.fromCharCode(e.keyCode) === "%") isLeft = true;
if (String.fromCharCode(e.keyCode) === "'") isRight = true;
if (String.fromCharCode(e.keyCode) === " ") isUp = true;
}
function keyUp(e) {
if (String.fromCharCode(e.keyCode) === "%") isLeft = false;
if (String.fromCharCode(e.keyCode) === "'") isRight = false;
if (String.fromCharCode(e.keyCode) === " ") isUp = false;
}
//MAINLOOP
MainLoop();
function MainLoop() {
//PRE VARIABLE ADJUSTMENTS
player.X += player.Velocity_X;
player.Y += player.Velocity_Y;
player.Velocity_X = player.Velocity_X * 0.90
//LOGIC
if (isLeft) player.Velocity_X = -4;
if (isRight) player.Velocity_X = 4;
if (!isLeft && !isRight) player.Velocity = 0;
if (player.Velocity_Y < player.Gravity) player.Velocity_Y += player.Weight;
for (var i=0;i<=maxBlock;i++){
if (player.isColliding(block[i]) && player.Y + player.Height < block[i].Y + player.Velocity_Y) {
player.Y = block[i].Y - player.Height;
player.Velocity_Y = 0;
}
}
}
if (isUp && player.Velocity_Y === 0) {
player.Velocity_Y += -10;
}
//POST VARIABLE ADJUSTMENTS
//RENDERING
grafx.clearRect(0,0,gameCanvas.width, gameCanvas.height);
grafx.drawImage(player.Sprite,player.X,player.Y);
for (var i=0;i<=maxBlock;i++) {
grafx.drawImage(block[i].Sprite,block[i].X,block[i].Y);
setTimeout(MainLoop, 1000/60);
}
function GameObject(img,x,y,width,height) {
this.Sprite = new Image();
this.Sprite.src = img;
this.X = x;
this.Y = y;
this.Previous_X = this.X;
this.Previous_Y = this.Y;
this.Velocity_X = 0;
this.Velocity_Y = 0;
this.Width = width;
this.Height = height;
this.Gravity = 0;
this.Weight = 0;
this.isColliding = function(obj) {
if (this.X > obj.X + obj.Width) return false;
else if (this.X + this.Width < obj.X) return false;
else if (this.Y > obj.Y + obj.Height) return false;
else if (this.Y + this.Height < obj.Y) return false;
else return true;
}
}
</script>
</body>
在此代码中,//VARIABLES、//LOGIC 和 //RENDERING 处的 for 循环应该与代码底部的 GameObject 一起工作以生成 4 个副本(由 maxBlock 定义的数字变量),并将它们附加到数组block。我很确定我没有犯拼写错误,因为我已经检查了很多次并修复了我能找到的唯一错误。我该怎么做才能解决这个问题?
【问题讨论】:
-
被答案改变了。看看这是否有效。
-
请参阅下面关于将 setTimeout 移到 for 循环之外的修改后的答案。
标签: javascript html image loops object