Making a character face the mouse in a 2D game?

The title might be a bit hard to understand. I’m trying to make a 2D fighting game (strange but it might be very cool) and I want the character to face the mouse. Using mouse.Hit isn’t an option since my character should only be able to face either left or right.

I thought that I could maybe compare the mouse.X in some way to see if the mouse was on the left or the right of the character, but the character doesn’t have a variable that tells you where the character is on the screen sadly. Maybe I could attach a GUI object to the character and use GuiObject.Position…

Any thoughts?

  1. Use Camera | Documentation - Roblox Creator Hub to get the 2D position of the player on the screen
  2. Compare it to the mouse 2D position. If mouse.X < player.X then you’re facing left, otherwise right.

Bonus points:

You can use

local diff = mousePosition - player2DPosition
local angle = math.atan2(diff.Y, diff.X)

and now you have the angle that the player → mouse vector makes with the horizon. You could use this for example to aim a gun or something.

Edit:

Another way would be to use physics groups and raycast the mouse with Mouse | Documentation - Roblox Creator Hub towards a plane that covers your entire game and compare the hit position with the player’s 3D position. That’ll probably give you a more “correct” answer.

3 Likes

Thanks alot! I’ll mark this as the solution.

1 Like