# Drawing Sprites Depending On Mouse Position (LibGDX)

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:

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.

Plug

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);
cam.unproject(pos);

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.

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