如何解决这个javascript代码?

时间:2016-06-04 16:54:41

标签: javascript

为什么当我运行此程序时,只有图片消失但位置仍然存在?因此,当我点击右,左,上,下按钮时,硬币的数量仍然增加(收集硬币游戏)。请给我一个正确代码的解释或示例。谢谢

//create coin
var coinReady = false;
var coinImage = new Image();
coinImage.onload = function() {
  coinReady = true;
}
coinImage.src = "coin1.png";

//first coordinates of coin
var coin = {
  x: 0,
  y: 0
};

var position = function() {
  //throw the coin somewhere on the screen randomly
  coin.x = 48 + (Math.random() * (canvas.width - 750 - 96));
  coin.y = 48 + (Math.random() * (canvas.height - 96));
};

//collision detection
if (char.x <= (coin.x + 48) && coin.x <= (char.x + 50) && char.y <= (coin.y + 48) && coin.y <= (char.y + 46)) {
  numberCoin += 1;
  position();
  effectSound.play();

  //draw image
  if (coinReady) {
    ctx.drawImage(coinImage, coin.x, coin.y);
  }

  //clear the image
  function Clear_1() {
    coinReady = false;
  }

  //show the coin1
  function Time_coin() {
    coin1Ready = true;
    Clear_1();
  }

  //function to call Time_coin or to make coin2 exits
  function timer1() {
    setInterval(Time_coin, 50000);
  }

  var main = function() {
    var now = Date.now();
    var delta = now - then;
    update(delta / 1000);
    render();
    timer1();
    then = now;
    //request to do this again as soon as possible
    requestAnimationFrame(main);
  };
  //Cross-browser support for requestAnimationFrame
  var w = window;
  requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;
  //Play the game
  var then = Date.now();
  position();
  main();
}

0 个答案:

没有答案