I'm making a small game where you play as a turret in the middle of the screen trying to shoot the enemies coming after you. I am having difficulties, however, in trying to figure out how to make the turret change sprites depending on where my mouse cursor is pointing. I don't want to rotate the sprite, mind you, as I already have made different variations of the same sprite for the different directions it will face:

enter image description here

I have an idea of how to accomplish this, but I don't know how to make it happen:

  • The program generates 42 rays, (one for each turret sprite), that originate from the turret

  • If the cursor falls between two of those rays, a specific sprite will be drawn

How would I go about doing this? It doesn't have to be the method described above as long as it produces the same result.

Thanks for your help in advance!

Plug enter image description here


The way I do this is by getting my mouse relative to the player by converting the mouse to screen coordinates.

Vector3 pos = new Vector3(Gdx.input.getX(),Gdx.input.getY(), 0);

    mouseRelativePlayer = new Vector2(pos.getX() - sprite.getX(),
    pos.getY() - sprite.getY());

Next I use the variable mouseRelativePlayer to determine which direction to set my player.

if(player.mouseRelativePlayer.y > 01)
            player.direction = Entity.Direction.UP;
        if(player.mouseRelativePlayer.y < -01)
            player.direction = Entity.Direction.DOWN;
        if(player.mouseRelativePlayer.x < -01)
            player.direction = Entity.Direction.LEFT;
        if(player.mouseRelativePlayer.x > 01)
            player.direction = Entity.Direction.RIGHT;

And for diagonals just do the same but with different values.

| improve this answer | |
  • \$\begingroup\$ I have one question: Why use Vector3 and not Vector2? \$\endgroup\$ – Plug Apr 28 '17 at 17:19
  • \$\begingroup\$ The camera.unproject only takes a vector3 as an argument. I guess for 3d things? \$\endgroup\$ – Joey bobaganoosh Apr 28 '17 at 17:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.