【问题标题】:javascript collision for game游戏的javascript碰撞
【发布时间】:2017-12-28 01:03:11
【问题描述】:

我遇到的问题是当 npc 和玩家在 5 像素内时会触发碰撞,然后 npc 的库存会显示在控制台中。问题是 npc 库存只会显示一次。

我想让它每次玩家在 npc 5 像素以内时都会显示他们的库存。但我也不希望在玩家距离 npc 5 像素以内时不断触发碰撞,只有在他们第一次靠近时才触发一次。

这是我的代码...

// collision for npc and player
function npc2Collision(){
  for(var i = 0; i < 1; i++){
    game.addEventListener('enterframe', function() {
      //detects whether player sprite is within 5
      //pixels of the npc sprite
      if(player.within(npc2,5) && !npc2.isHit){
        console.table(npcInvObject);
        npc2.isHit = true;
      }
    });
  }
}
npc2Collision();

【问题讨论】:

    标签: javascript collision


    【解决方案1】:

    为了防止碰撞再次触发,您可以使用检查设置的简单标志(及其相反):

    function npc2Collision(){
      for(var i = 0; i < 1; i++){
        game.addEventListener('enterframe', function() {
          //detects whether player sprite is within 5
          //pixels of the npc sprite
          if(player.within(npc2,5) && !npc2.isHit){
            // split the checks so distance works well
            if (!player.collided) {
              console.table(npcInvObject);
              npc2.isHit = true;
              player.collided = true;
            }
          } else {
            player.collided = false;
        });
      }
    }
    

    这将运行一次,在玩家身上设置collided 标志,并且在玩家离开碰撞半径之前不会再次开火。

    【讨论】:

      猜你喜欢
      • 2018-05-26
      • 1970-01-01
      • 1970-01-01
      • 2016-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多