1

I wanted to create a game where I have to return a baby when baby goes to Y position at 12 using an button. I want it to be move 2 position from 12 i.e. 10 and move from 10 to 6 but the code move the baby directly to 6. Note: grammar error doesn't let me post icon and baby as a same. It is a variable name.

if (baby_posY==12) {
    if (baby_posY==12) {
      tiles[baby_posX][baby_posY].setIcon(null);
      baby_posY=baby_posY-2;
      tiles[baby_posX][baby_posY].setIcon(icon Baby);   
    }
    if (baby_posY==10) {
      tiles[baby_posX][baby_posY].setIcon(null);
      baby_posY=baby_posY-4;
      tiles[baby_posX][baby_posY].setIcon(icon Baby);
    }
}
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
John Bista
  • 11
  • 4
  • 1) For better help sooner, [edit] to add a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). 2) One way to get image(s) for an example is to hot link to images seen in [this Q&A](http://stackoverflow.com/q/19209650/418556). E.G. [This answer](https://stackoverflow.com/a/10862262/418556) hot links to an image embedded in [this question](https://stackoverflow.com/q/10861852/418556). – Andrew Thompson Sep 10 '20 at 02:23

1 Answers1

0

You should use else if, instead of if on the subsequent checks. What's happening is 12 is going to 10, then it checks for 10, and makes it 6. Using else you can prevent that

if (baby_posY==12) { 
    tiles[baby_posX][baby_posY].setIcon(null); baby_posY=baby_posY-2; // **** right here is what's causing the double move
    tiles[baby_posX][baby_posY].setIcon(icon Baby); 
} else if (baby_posY==10) { // adding 'else' will prevent this second condition from triggering if the first was triggered
    tiles[baby_posX][baby_posY].setIcon(null); baby_posY=baby_posY-4; 
    tiles[baby_posX][baby_posY].setIcon(icon Baby); 
}
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80