javascript collision for game

Viewed 65

The issue I'm having is when an npc and player are within 5 pixels a collision is triggered and then the npc's inventory is displayed in the console. The problem is that the npc inventory will only display this once.

I would like to make it so that every time the player is within 5 pixels of the npc their inventory is displayed. But also I don't want the collision to trigger constantly while the player is within 5 pixels of the npc, just once when they first get close.

Here's my code...

// 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();
1 Answers
Related