Search code examples
javaanimationangledirection

How to detect the direction that looks to player - Java


Hello I am making a game for tests in Java and I want to make something but don't know how. So I have 4 animations for directions up/down/left/right and position of the animal (entity) and player.

I want to make the animal look towards player all time but don't know how to make it. If I use 'if entity.x>player.x' it will look to the correct side but wont be able to look down or up?

Hopefully you understeand what I mean, please answer :D


Solution

  • You're half way there already. What you want to do is determine where in relation to the animal the player lies.

    Let's first make an enum to encapsulate this

    enum Direction { NORTH, EAST, SOUTH, WEST };
    

    As you said, you can check whether the player is on the left or right of the animal.

    if(player.getX() > animal.getX()) {
        animal.setDirection(Direction.EAST);
    } else { 
        animal.setDirection(Direction.WEST);
    }
    

    likewise, you can do the same thing with Y coordinates and the North/South direction.

    if(player.getY() > animal.getY()) {
        animal.setDirection(Direction.NORTH);
    } else { 
        animal.setDirection(Direction.SOUTH);
    }
    

    So now, how do we figure out whether we should use the first check or the second check? Well, think about it for a second. If you live "north" of where you are, you probably aren't straight north, but rather, mostly north - certainly, more north than east, for example. So a good check is then, "what is the dominant direction" - ie. if you live further north than you are east, you say you live north. So how do you check that? Well, you say that the distance you must travel North/South to your place is greater than the distance you must travel East/West. In code:

    if(Math.abs(animal.getX() - player.getX()) > Math.abs(animal.getY() - player.getY())) {
        //More east-west than north-south - do EAST-WEST check
    } else {
        //More north-south than east-west - do NORTH-SOUTH check
    }
    

    So, combining this gives the final result:

    if(Math.abs(animal.getX() - player.getX()) > Math.abs(animal.getY() - player.getY())) {
        //More east-west than north-south - do EAST-WEST check
        if(player.getX() > animal.getX()) {
            animal.setDirection(Direction.EAST);
        } else { 
            animal.setDirection(Direction.WEST);
        }
    } else {
         //More north-south than east-west - do NORTH-SOUTH check
        if(player.getY() > animal.getY()) {
            animal.setDirection(Direction.NORTH);
        } else { 
            animal.setDirection(Direction.SOUTH);
        }
    }
    

    And you are done! Let me know if you have any more questions.