- Home /
player mouse rotation, 2D twin shooter. player won't rotate.
Hey guys, I'm trying to get my player ship to rotate with my mouse. I've checked and re-checked and still can't get it to work. The player is a 2D sprite currently in a 'still' position and haha, just won't move. My background and player are in reset positions. Here's the coding below, I hope someone has an idea or sees something that can be fixed, it has been pretty frustrating. Thanks in advance.
void Update ()
{
Rotation ();
}
//rotate player to face mouse
void Rotation ()
{
//finding where the mouse is relative to the player
Vector3 worldPos = Input.mousePosition;
worldPos = Camera.main.ScreenToWorldPoint(worldPos);
//get the difference from each axis (delta x and y)
float dx = this.transform.position.x - worldPos.x;
float dy = this.transform.position.y - worldPos.y;
//get the angle between the two objects
float angle = Mathf.Atan2(dy, dx) * Mathf.Rad2Deg;
Quaternion rotation = Quaternion.Euler(new Vector3(0, 0, angle));
// Assign the ship's rotation
this.transform.rotation = rotation;
}
Answer by DanSuperGP · Jan 07, 2015 at 12:50 AM
The Z element of the vector passed to Camera.ScreenToWorldPoint represents the distance from Camera. Since you want the touch to be in the same plane as the ship you are rotating, you need to set the Z value to the distance from the camera to the plane your sprite is in. If you haven't changed the camera from it's default position, that would be 10.
So, if you add
worldPos.z = 10.0f;
After line 10 before line 11 it will work.
The way you have it now, no matter where you move the mouse, it is returning the camera's location because the distance from the camera is zero.
Thanks for the advice, tried it out and she spins like a ballerina. I'll remember that for the next time.
Your answer
Follow this Question
Related Questions
Attempting to Calculate and Change Scale of Platforms Sets Scale to 0 1 Answer
Mathf.Atan changes instantly even with a slow lerped value 1 Answer
What is the correct way to move an object to a target location? 2 Answers
Postive and Negative Button Binding 3 Answers
SmoothDamp from 360 to 1 1 Answer