Search code examples
processing

Update value once using if/then statements


I'm trying to implement a score counter, called scoreCount, that updates when the two shapes touch. I'm using if/then statements to check if the two shapes are touching, and if they are, update the score. What happens is the code will keep running for as long as they are touching, I've been struggling to find a way to make it only update once.

int player1PosX = 32;
int player1PosY = 30;

int player2PosX = 608;
int player2PosY = 570;

int scoreCount = 0;

void draw() {
  drawPlayingField();
  drawPlayers();
  drawScoreBar();
  isTagged(player1PosX, player1PosY, player2PosX, player2PosY);
}

void isTagged(int p1X, int p1Y, int p2X, int p2Y) {
  println(p1X, p1Y, p2X, p2Y);
  if (p1X == p2X && p1Y == p2Y) {
    text("Tag, you're it!", 225, 300);
    scoreCounter += 1;
  }
}

I've tried using booleans to check if they're touching and then resetting the bool after, but it still didn't work.


Solution

  • You have to check if the objects have touched each other in the previous frame and only increment the score if they are touching now but have not touched before:

    bool tagged = false;
    
    void isTagged(int p1X, int p1Y, int p2X, int p2Y) {
      
      bool taggedNow = p1X == p2X && p1Y == p2Y;
      if (!tagged && taggedNow) {
        text("Tag, you're it!", 225, 300);
        scoreCounter += 1;
      }
      tagged = taggedNow;
    }