Domanda

So I have been trying to find a way to determine an "overlap" in images for a java game I am writing. Now I know I could create a box to follow the trainer that encompasses it and then use a contains point to see if the trainer's box contains the point of the Car/Pokemon, but I am trying to find an alternate way around this. I tried using nested If statements, but those do not seem to work. If it is something wrong with my coding, or an error in my way of thinking, please let me know. An example of the nested ifs is below.

if (trainer.getPy() == squirtle.getPy() & trainer.getPx() == squirtle.getPx()){
    if  (trainer.getPy() >= squirtle.getPy() - 50)
        if  (trainer.getPy() <= squirtle.getPy() + 50)
            if  (trainer.getPx() >= squirtle.getPx() -50)
                if  (trainer.getPx() <= squirtle.getPx() + 50)
                    trainer.dead();
    Skully skull = new Skully (trainer.getPx(), trainer.getPy());
}
if (trainer.getPy() == pikachu.getPy() & trainer.getPx() == pikachu.getPx()){
    if  (trainer.getPy() >= pikachu.getPy() - 50)
        if  (trainer.getPy() <= pikachu.getPy() + 50)
            if  (trainer.getPx() >= pikachu.getPx() -50)
                if  (trainer.getPx() <= pikachu.getPx() + 50)
                    trainer.dead();
    Skully skull = new Skully (trainer.getPx(), trainer.getPy());
}
È stato utile?

Soluzione

The problem is that your first condition checks whether the two object are at exactly the same position, so all those more relaxed if statements after that are pointless. Instead, you probably just want to check whether the difference between the centres of the two objects are less than 50px apart. You can easily check this using the absolute difference.

if (Math.abs(trainer.getPy() - squirtle.getPy()) < 50 &&
        Math.abs(trainer.getPx() - squirtle.getPx()) < 50) {
    trainer.dead();
    Skully skull = new Skully (trainer.getPx(), trainer.getPy());
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top