- Home /
Rotate an object using joystick
I'm looking for a way to map the angle the player moves the joystick from its rest point to an object - for example, if the player were to move the stick to a upper right position, the object would spin to face that direction - could anyone give me some pointers?
I'm reading the stick input into a Vector3, which I assume needs to somehow converted into a float, and then to an angle?
input = Vector3(Input.GetAxis("Left Joystick X"), Input.GetAxis("Left Joystick Y"), 0);
Answer by aldonaletto · Oct 10, 2011 at 11:57 PM
Input.GetAxis (for joysticks) returns a value between -1 and +1, proportional to the angle of the joystick lever. All you have to do is multiply this value by the maximum angle you want the player to turn to:
var maxX: float = 60; var maxY: float = 60;
function Update(){ var angleX = maxX*Input.GetAxis("Left Joystick X"); var angleY = maxY*Input.GetAxis("Left Joystick Y"); transform.localEulerAngles = Vector3(angleY, angleX, 0); } If this code is attached to the camera, for instance, you can aim it up and down with joystick Y, and left and right with joystick X - both proportionally to the joystick movement.
It may seem that angleY and angleX are swapped in localEulerAngles: that's because the first parameter sets the rotation angle around the X axis, thus going up and down; the second does the same around the Y axis, thus swinging left or right.
localEulerAngles is used instead of eulerAngles because it will work even if the camera is a child of other object (if it's not, localEulerAngles and eulerAngles do the same).
Case any axis go to the wrong direction, just invert the signal of angleX or angleY.
Your answer
Follow this Question
Related Questions
Joystick Rotation with Transform.RotateAround 0 Answers
from Quaternion to RotateAround 1 Answer
Rotate vector around vector? 2 Answers
Rotate One Object Around Another 1 Answer