- Home /
Question by
Maroni100 · Jan 30, 2019 at 07:30 AM ·
2djoysticktopdowntop down shooter
Joystick character rotation wrong movement
Hi guys, i'm trying to make my character look at joystick direction, but i'm having some problems, if i look to left and right it works correctly, but if i look to top and down it inverts the sides. if it in left or right and i drag it to top or down it inverts the sides too, how can i correct this? My Code
float horizontalAxis2 = CrossPlatformInputManager.GetAxis("Horizontal_2");
float verticalAxis2 = CrossPlatformInputManager.GetAxis("Vertical_2");
Vector2 lookVec = new Vector2(horizontalAxis2, verticalAxis2);
if (lookVec.sqrMagnitude > 0.1) {
float angle = Mathf.Atan2(lookVec.x, lookVec.y) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(new Vector3(0, 0, angle)), Time.deltaTime * moveForce);
}
Comment
Best Answer
Answer by sean244 · Jan 29, 2019 at 04:26 AM
Re-write your code to the following
float horizontalAxis2 = CrossPlatformInputManager.GetAxis("Horizontal_2");
float verticalAxis2 = CrossPlatformInputManager.GetAxis("Vertical_2");
Vector2 lookVec = new Vector2(horizontalAxis2, verticalAxis2);
if (lookVec.sqrMagnitude > 0.1)
{
float angle = Mathf.Atan2(lookVec.y, lookVec.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(Vector3.forward * (angle + 90f)), Time.deltaTime * moveForce);
}
I made three changes:
First, I re-wrote
float angle = Mathf.Atan2(lookVec.x, lookVec.y) * Mathf.Rad2Deg;
to
float angle = Mathf.Atan2(lookVec.y, lookVec.x) * Mathf.Rad2Deg;
Atan2 is y over x, not x over y.
Second, I added a 90 degree offset to the angle
Vector3.forward * (angle + 90f)
Finally, I used Slerp instead of Lerp because it looks nicer :)
playerrotation.gif
(179.3 kB)
You’re welcome :) Be sure to subscribe to my YouTube channel https://www.youtube.com/channel/UCo_3O$$anonymous$$EZQiRLQihycbkYd_Q