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.
1 Answer
1This 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);
}