- Home /
Rotation of a object depending on where the joystick is facing
I know this had been asked already but I don't get it, but can someone explain this to me? I'm using a 2D project and I want the gun to face towards where the joystick is pointing. Any help is greatly appreciated.
Answer by Namey5 · Mar 20, 2020 at 03:49 AM
This is a very broad question, and as such I can only really give a broad answer. We can figure out the direction the joystick is facing by taking both horizontal and vertical axes and combining them into a 2D vector. From there, we can use the LookRotation function of the Quaternion class to figure out a rotation that points in the direction of that vector and use that to rotate the target object;
//Assuming you have setup the Horizontal and Vertical axes as joystick axes in the input settings.
//Also, must be a Vector3 because Unity is at its heart a 3D engine and all rotations are in 3D, so just leave the z value at 0
Vector3 dir = new Vector3 (Input.GetAxis ("Horizontal"), Input.GetAxis ("Vertical"), 0f);
//Make sure we actually have a direction, and the joystick isn't stationary
if (dir.magnitude > 0.05f)
{
//Find a rotation pointing in the direction of the joystick and apply it to our transform
transform.rotation = Quaternion.LookRotation (dir);
}
Your answer
Follow this Question
Related Questions
joystick connected 1 Answer
Managing input from two players in the same computer using the Xbox 360 controller. 1 Answer
How to use the XBox 360 Controller D-Pad (PC) ? 6 Answers
How do I add input for two different local players? 1 Answer
Find out if any Button on any Gamepad has been pressed and which one 6 Answers