- Home /
Rotate with joystick - LookAt axis flipping
I want to control rotation in only one axis (X) via joystick. I mean, if joystick is at top, function returns Vector2(0.0,1.0) and box is also "looking" at this point, when left returns (-1.0,0.0). I wrote function like this:
function On_JoystickMove(MovingJoystick : MovingJoystick) { Debug.Log(MovingJoystick.joystickAxis); player.transform.LookAt(Vector3(MovingJoystick.joystickAxis.x,MovingJoystick.joystickAxis.y,player.transform.position.z)); }
But in some cases ex.(1.0,0.0) gameobject 'player' flips in Y axis by 180 degrees. I tried many solutions posted here but actually none of them worked correctly.
Answer by LyanApps · Apr 02, 2013 at 06:40 PM
I assume you are making just a 2D platform game or something similar? Have you tried just setting the angle based on the input?
//You may have to play around with/switch the y and x
var angle = Mathf.Atan2(input.y,input.x) * Mathf.Rad2Deg;
player.transform.rotation = Quaternion.Euler(angle, 0, 0);
Thank you! Works good and actually solved my problem but when im passing values like (1.0,0.0) i have something like 'smooth spikes' or disturbances.
for smooth transition what i used is Quaternion.Lerp and it works like charm.
Here's my code make changes as per your need.
atan2 = $$anonymous$$athf.Atan2(myJoystick.InputDirection.y, myJoystick.InputDirection.x) * $$anonymous$$athf.Rad2Deg;
transform.rotation = Quaternion.Lerp (transform.rotation, Quaternion.Euler (0, 0, (atan2-90)), trackingSpeed * Time.deltaTime);
For smooth transitions you'll have to look into Lerp or Slerp functions. I would include it but I don't have much experience using those. Because you're only messing with one angle you can try something like:
$$anonymous$$athf.Lerp(player.transform.rotation.eulerAngles.x , angle, Time.time);
http://docs.unity3d.com/Documentation/ScriptReference/$$anonymous$$athf.Lerp.html
Just saw this too:
http://docs.unity3d.com/Documentation//ScriptReference/$$anonymous$$athf.LerpAngle.html
Thank you! I have been searching all over for this solution, and finally stumbled across this post.