为什么我的代码没有在我的HTML5游戏中定义渲染?

时间:2016-04-27 01:53:37

标签: javascript html5 canvas

这是我编程的第一年,我跟着这个HTML5 Game Development Series on YouTube

我跟他的代码一行一行,我的代码仍然会产生错误。

控制台日志说出以下内容: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 );

Coins Visual Aid

1 个答案:

答案 0 :(得分:2)

所以有一些事情:

根据@nduggers评论,您需要将您的i ++放在renderCoins中的数组访问器之后。您将获得game.js:105 Uncaught TypeError: Cannot read property 'render' of undefined,因为您在该循环的最后一次迭代中访问了无效索引

渲染功能中的下一步

function render() {
  renderCoins();     //you are rendering coins that have not been initted yet
  createCoins(20);   //you will create 20 new coins every time you render
  g.clearRect(0,0,width,height);   //you are clearing any coins you just rendered
  player.render();    //you are now rendering just the player on an empty canvas
}

所以你需要在渲染功能之外创建你的硬币,否则你将在每次渲染时创建20个新硬币。接下来,您需要将clear rect移动到渲染功能的顶部。然后渲染硬币和渲染播放器。那一切都应该是好的。