2d game flip game object on x axis to face the other way based on mouse position

Hi Guys, How do I go about flipping a character on the X axis in a 2D game?
I have a shooter named “Player” that follows the mouse and i need this guy to do something like

if mouse X position is less then Player’s X position flip the Player Game Object to face left and VS
so another words as the player looks and aims at the mouse he also looks good when the mouse goes behind the player :wink:

Object.transform.localScale.x = -1;

I can’t get this to work… is there some sort of game example or tutorial that shows how to flip an object based on mouse position? I am sure this is pretty simple but i can’t figure it out :frowning:

You can’t directly change the x value of localscale. You need to create a temporary vector3, assign the localscale, modify it and reassign the updated vector3 back to the localScale.

Vector3 newScale = obj.transform.localScale;
newScale.x *= -1;
obj.transform.localScale = newScale;

EDIT
To check the location of the mouse in world space, use ScreenToWorldPoint to convert the mouse position and compare the x of both the returned value of the mouse position and your object’s position.

thank you for your help guys!
this seems to work for me

transform.Rotate(new Vector3(0,180,0));

5 Likes

Thank you!

Your little line of code helped me now in 2016 :d !

Hi All,

First time posting. The above helped me but I noticed that if I had a more complex object with children it helped me to use

transform.rotation = Quaternion.Euler(0, 180f, 0);

to face right and when I wanted to face left again:

transform.rotation = Quaternion.Euler(0,0,0);

I used this Unity Manual page Unity - Manual: Rotation and orientation in Unity

Hope this helps someone else in the future.

6 Likes

It just did

Sometimes you don`t want to rotate it because this happens: 5371338--543636--Untitled3.png

The way to make this work is just simply scaling it in it`s X axis like this:

transform.localScale = new Vector3(-1f, 1f, 1f);

Hope this helps a bit!

The problem with this is that the childs attached to the player will be scaled, like the UI, weapons, ecc

So what would be the solution in this case?