我的身高已定义,但显示为未定义

时间:2018-08-26 20:25:29

标签: javascript

所以我正在用帆布做游戏,但其中一个字符的对象没有出现。我的控制台没有显示任何错误,因此我决定检查我的asteroidList对象。我检查了一下,发现对象高度中的第一个字符未定义,但是我已经定义了它。有人可以告诉我问题是什么吗?这是我的代码:

var c = document.getElementById("game");
var ctx = c.getContext("2d");

  //variables
  pX = 1;
  pY = 40;
  pW = 54.6;
  pH = 52.6;
  hw = 100;
  hh = 10;
  asteroidSpeed = 0.05;

  //load image sprites
  var player = new Image();
  var aster = new Image();
  var enemy = new Image();
  var max = new Image();
  var animatedPlayer = new Image();

  player.src = "player.png";
  aster.src = "aster.png";
  enemy.src = "enemy.png";
  max.src = "max.png";
  animatedPlayer.src = "animatedPlayer.png";

  //keys
  document.addEventListener("keydown",function (e) {
    if (e.keyCode === 83) {
      moveDown();
    }

    else if(e.keyCode === 87) {
      moveUp();
    }
  })


  function moveDown() {
    pY += 2;
  }

  function moveUp() {
    pY -= 2;
  }

  //asteroid constructor

  asteroidList = {};

  function asteroid(id,x,y,img,width,height) {
    var asteroid = {
      x:x, 
      y:y,
      width:width,
      height:height,
      id:id   
    };

    asteroidList['A1'] = asteroid;
  }

  function updateAsteroid(asteroid) {
    asteroid.x -= asteroidSpeed;
    ctx.drawImage(aster, asteroid.x, asteroid.y, asteroid.width, asteroid.height);

  }

  function draw() {
    ctx.clearRect(0,0,c.width,c.height);

    //characters
    asteroid('A1', 250, 40, 29.6, 29.3);
    ctx.drawImage(player,pX,pY,pW,pH);

    setInterval(update, 40);

    function update() {

     //map collision

     if(pY < 0) {
       pY = 0;
     }

     if(pY > 100) {
       pY = 100;
     }

     //enemy loop
     for(var key in asteroidList) {
      updateAsteroid(asteroidList[key]);
    }

  }

    //hp 
    ctx.fillStyle = 'green';
    ctx.strokeStyle = 'black';

    ctx.beginPath();
    ctx.fillRect(199,139,hw,hh);
    ctx.strokeRect(199,139,100,10);

    //animation call
    requestAnimationFrame(draw);

  }

</script>

1 个答案:

答案 0 :(得分:0)

小行星函数定义中还有一个名为img的参数:

function asteroid(id, x, y, img, width, height) {
    var asteroid = {
      x:x, 
      y:y,
      width:width,
      height:height,
      id:id   
    };

    asteroidList['A1'] = asteroid;
}

所以当您这样称呼它时:

asteroid('A1', 250, 40, 29.6, 29.3);
// asteroid(id, x, y, img, width);

您缺少设置height的值,因此无法获得undefined