Rotate towards object in the same direction of gamepad tick or mouse position in screen

Hello everyone! I’m having a simple issue with my development, and that is that I want to rotate this turret based on the direction that my gamepad’s right stick is facing, also in the direction of the current mouse position in screen.

I’m using the new input system and both values are set to Vector 2, mouse is set to delta (could be a bad idea for this, but still not sure if use Delta or Position).

The idea is to have it look like the image attached, meaning that the turret’s cannon should be facing in the same direction I’m moving my gamepad’s stick or looking at the mouse on screen position.

I’ve tried many things, but non worked and I ran out of ideas.

If anyone could help me or give me a small hint, anything really, I would appreciate it.

PS: Title → Rotate object towards*

I recommend first making sure the local forward of your gameobject being aligned with the turret’s barrel.
How I approach this is by using Quaternion.LookRotation : Unity - Scripting API: Quaternion.LookRotation
You give that function a forward direction (your input vector3 normalized) and it will output the rotation you want your turret to have

1 Like

Mathf.Atan2() and Mathf.Rad2Deg will get you from X/Y cartesian coordinates to degrees around the compass.

See attached example.

8240049–1077429–MissileTurnTowards.unitypackage (12.1 KB)

1 Like

@ferlinnoise @Kurt-Dekker Apologies, when I got the thing to work I completely forgot I posted this here.

I got it running with the following code

private void HandleGamepadInput()
{
   float angleRadians = Mathf.Atan2(gamepadValue.y, gamepadValue.x);
   float angleDegrees = -angleRadians * Mathf.Rad2Deg;
   objectToRotate.rotation = Quaternion.AngleAxis(angleDegrees + 90, Vector3.up);
}

Where gamepadValue is the value I get when reading the Vector2 values from the Input System event.
The minus in angleRadians I quite don’t remember why is there, but it works that way. The same for the + 90 on the Quaternion.AngleAxis

Thank you both for the help you gave me!

1 Like