Determine if cursor is on the left side or right side of a 2D object or sprite regardless of rotation
I am trying to flip my 2D character's upper body based on which side of the character's body the cursor is. Currently, If the cursor is on left side of the body, the character will flip to face left, and vice versa.
The problem is that if I rotate my character, It doesn't adapt to the new rotation, instead it will flip based on the x coordinate alone.
How can I make it so that the body flips based on what side of the body the cursor is on regardless of its rotation? Like in the picture below, if the cursor was in the red the body would flip to face the left, if in the green, to the right.
Here's my current code:
// flip bod and head according to mouse position
if (Input.mousePosition.x - Camera.main.WorldToScreenPoint(playerBod.position).x > 0 && !bodFacingRight) //if positive, turn right
FlipHeadAndBod();
else if (Input.mousePosition.x - Camera.main.WorldToScreenPoint(playerBod.position).x < 0 && bodFacingRight)
FlipHeadAndBod();
Answer by Orrib · Jul 07, 2017 at 06:58 PM
Alright, I figured it out. By converting the mouse position to a local position using Transform.InverseTransformPoint I accounted for the rotation.
The New Code:
// flip bod and head according to mouse position
if (playerBod.InverseTransformPoint(Input.mousePosition).x - playerBod.localPosition.x > 0 && !bodFacingRight) //if positive, turn right
FlipHeadAndBod();
else if (playerBod.InverseTransformPoint(Input.mousePosition).x - playerBod.localPosition.x < 0 && bodFacingRight)
FlipHeadAndBod();
Sorry, it should be playerBod.InverseTransformPoint(Camera.main.ScreenToWorldPoint(Input.mousePosition)).x
Your answer
Follow this Question
Related Questions
How could I do pixel art with no blurring rotation like in Tiny Survivor? 0 Answers
Top-Down 2D Movement with Rotation? 0 Answers
Sprites pixel colliding with 2d collider 0 Answers
Sprite Orbiting Sprite with Mouse 0 Answers
How to make a 2d object, when thrown stick to another object orientated the side its touching 0 Answers