Jeremy Dorazio
Jeremy Dorazio

Reputation: 23

javascript collision for game

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();

Upvotes: 2

Views: 71

Answers (1)

ssube
ssube

Reputation: 48267

To prevent the collision from firing again, you can use a simple flag set by the check (and its inverse):

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;
    });
  }
}

This will run once, set the collided flag on the player, and will not fire again until the player has left the collision radius.

Upvotes: 1

Related Questions