这是我在编程的第一年,我正在关注这个HTML5 Game Development Series on YouTube。为什么我的代码没有在HTML5游戏中定义渲染?
我跟着他的代码一行一行,我的代码仍然产生错误。
控制台日志说以下内容:game.js:105 Uncaught TypeError: Cannot read property 'render' of undefined
的目标是为黑色方能够有输入键移动,并为将要生成随机黄色硬币。硬币正在生成,但我不能再移动黑色方块。
有在的index.php没有任何问题,我会告诉我的game.js
width = 400;
height = 400;
var FPS = 60;
var canvas = document.getElementById("game");
var g = canvas.getContext("2d");
var x = 50;
var y = 50;
coins = [];
var player = {
x: 50,
y: 50,
speed: 3,
tick: function() {
if(Key.up && this.y > 0) this.y-= this.speed;
if(Key.down && this.y < height - 20) this.y+= this.speed;
if(Key.left && this.x > 0) this.x-= this.speed;
if(Key.right && this.x < width - 20) this.x+= this.speed;
},
render: function() {
g.fillStyle = "black";
g.fillRect(this.x,this.y,20,20);
}
};
var Key = {
up: false,
down: false,
left: false,
right: false
};
addEventListener("keydown", function(e) {
var keyCode = (e.keyCode) ? e.keyCode : e.which;
switch(keyCode) {
case 38: // up
Key.up = true;
break;
case 40: // down
Key.down = true;
break;
case 37: // left
Key.left = true;
break;
case 39: // right
Key.right = true;
break;
}
}, false);
addEventListener("keyup", function(e) {
var keyCode = (e.keyCode) ? e.keyCode : e.which;
switch(keyCode) {
case 38: // up
Key.up = false;
break;
case 40: // down
Key.down = false;
break;
case 37: // left
Key.left = false;
break;
case 39: // right
Key.right = false;
break;
}
}, false);
function Coin(x,y) {
this.x = x;
this.y = y;
this.size = 8;
this.render = function() {
g.fillStyle = "yellow";
g.fillRect(this.x,this.y,this.size,this.size);
};
this.tick = function() {
};
}
function createCoins(amount) {
var i = 0;
while(i < amount) {
i++;
coins.push(new Coin(Math.random()*width,Math.random()*height));
}
}
function renderCoins() {
var i = 0;
while(i < coins.length) {
i++;
coins[i].render();
}
}
function render() {
renderCoins();
createCoins(20);
g.clearRect(0,0,width,height);
player.render();
}
function tick() {
player.tick();
}
setInterval(function() {
render();
tick();
}, 1000/FPS);
在renderCoins的内部,交换while循环中的两行,意思是在渲染调用后放置“i ++”。 – ndugger
@ndugger我做了你的代码。黑箱随着键输入移动,但硬币现在消失。执行代码时,控制台日志中没有错误。 –
在绘制硬币之后但在绘制玩家之前,您正在清除整个矩形。清晰的矩形应该在硬币图上方 – karina