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.

1 Answer

1

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 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: Mathf.Lerp(player.transform.rotation.eulerAngles.x , angle, Time.time); http://docs.unity3d.com/Documentation/ScriptReference/Mathf.Lerp.html Just saw this too: http://docs.unity3d.com/Documentation//ScriptReference/Mathf.LerpAngle.html

–

Thank you! I have been searching all over for this solution, and finally stumbled across this post.

–