- Home /
Character facing the position of mouse cursor (2d platformer),Sprite changing based on mouse position
Hello, I am making a 2d platformer game and I want the player to face left or right according to the position of mouse cursor.
I found some scripts for the sprite to face the mouse direction but those scripts make the sprite turn 360 degrees facing the mouse (suitable for a top down game) but what I want to make is;
Let's say the screen is divided from top to down in two parts, left and right. When the mouse is located on the left side, the sprite for the character looking at the left side will be activated. When I run right, the character will run backwards since he is facing left side.
I don't want the player to rotate 360 degrees, just left and right.
Please help me with this, I hope I explained the situation clearly.,Hello, I am making a 2d platformer game and I want my character to face the position where the mouse is. I can make the sprites rotate according to mouse 360 degrees but what I want is that, if the mouse is on left side, character-looking-left (just making up the name to be clear) will be activated. When the mouse is on the right side character-looking-right will be activated.
If mouse is on left and I press move right button, I want my character to face left and walk backwards to right side.
1- I found some tutorials about 360 degree rotation ( like for a top-down game) but since I have only 2 directions (left and right)
Please help me find a way to make this happen. I hope I made the situation clear enough.
Answer by Ymrasu · Feb 21, 2019 at 01:27 PM
You can find which side of the player the mouse is by subjecting the player's position from the mouse position, then checking if it is positive or negative. Something like this:
bool facingRight = true;
void Update()
{
// using mousePosition and player's transform (on orthographic camera view)
var delta = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
if (delta.x >= 0 && !facingRight) { // mouse is on right side of player
transform.localScale = new Vector3(1,1,1); // or activate look right some other way
facingRight = true;
} else if (delta.x < 0 && facingRight) { // mouse is on left side
transform.localScale = new Vector3(-1,1,1); // activate looking left
facingRight = false;
}
}
Your answer
Follow this Question
Related Questions
Character rotation help needed. 1 Answer
Rotate to facing direction 6 Answers
Character Controller - unknown rotation, flying 1 Answer
Grid-based movement: How to face forward 2 Answers
How can I straighten my character's movement and actions? 0 Answers