- Home /
Need Help Flipping my character depending on if the mouse is left or right.
Hello, I'm a young developer working on a video game project for school. I'm making a top down 2d shooter game. Currently I've coded in some basic things, like movement and getting the character to face the mouse. However, one problem I ran into was that I can't find out how to flip the character so they're facing right or left depending if the mouse is on the right or left of the screen. Please help? Without this the head just goes a full circle.
This is what I have: public float moveSpeed; public Rigidbody2D rb; private Vector2 moveDirection; private Vector2 mousePos; public Camera cam;
// Update is called once per frame
void Update()
{
ProcessInputs();
mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
}
void FixedUpdate()
{
Move();
Vector2 lookDir = mousePos - rb.position;
float angle = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg - 90f;
rb.rotation = angle;
}
void ProcessInputs()
{
float moveX = Input.GetAxisRaw("Horizontal");
float moveY = Input.GetAxisRaw("Vertical");
moveDirection = new Vector2(moveX, moveY).normalized; //Come Back to this later
}
void Move()
{
rb.velocity = new Vector2(moveDirection.x * moveSpeed, moveDirection.y * moveSpeed);
}
}
Answer by AlgoUnity · Sep 22, 2021 at 11:54 PM
There's more than one way to do this, but the easiest is to set the scale of the transform to negative.
void FixedUpdate()
{
Move();
Vector2 lookDir = mousePos - rb.position;
if (lookDir.x < 0) //if the X component of lookDir is negative, you are looking to the left
{
//Flip the image across the X axis
transform.localScale = new Vector3(1, -1, 1);
}
else
{
transform.localScale = new Vector3(1, 1, 1);
}
float angle = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg - 90f;
rb.rotation = angle;
}
If you want to understand why changing the localScale does this, choose the player's head in the Hierarchy and find localScale in the transform component in the Inspector. Click and drag the x, y, z components of localScale and see what happens when you bring them below 0.
Your answer
Follow this Question
Related Questions
[Please Help!] How Can I Make The Tip Of My Ship Follow My Cursor? 0 Answers
How can I limit the rotation on the Y axis so the player cant spin the camera 360 in an FPS game? 0 Answers
Help!Crash! FatalError"Callback registration failed kMaxCallback" 1 Answer
How to reset character orientation based on direction the camera is facing 1 Answer