# How to rotate 2D object with (gamepad) right stick

I have a 2D character and I want its rotation to turn according to the position of the right stick.

I have already looked for solutions, but I can’t find any. I want to rotate it according to the gamepad so that I can aim.

(I’m using the Input System to get the right stick `Vector2` value)

You can use

``````transform.rotation = Quaternion.LookRotation(Vector3.forward, direction);
``````

to make a sprite point towards a direction vector in 2D This will make the y axis of the sprite point towards the direction vector while keeping its z axis aligned with the world’s z axis (this way it remains in the 2D plane).

using UnityEngine;
using UnityEngine.InputSystem;

public class CharacterRotation : MonoBehaviour
{
public float rotationSpeed = 5f; // Adjust this to control the rotation speed
private Vector2 rightStickInput;

``````// Reference to your character's Rigidbody2D (if it uses one)
private Rigidbody2D rb2d;

private void Awake()
{
// Initialize Input System
InputSystem.onDeviceChange += (device, change) =>
{
{
gamepad.rightStick.canceled += ctx => rightStickInput = Vector2.zero;
}
};
}

private void Start()
{
rb2d = GetComponent<Rigidbody2D>(); // Get the Rigidbody2D component
}

private void Update()
{
RotateCharacter();
}

private void RotateCharacter()
{
if (rightStickInput != Vector2.zero)
{
float angle = Mathf.Atan2(rightStickInput.y, rightStickInput.x) * Mathf.Rad2Deg;
Quaternion targetRotation = Quaternion.AngleAxis(angle, Vector3.forward);

// Apply rotation to the character
if (rb2d != null)
{
// If using Rigidbody2D, use MoveRotation to apply rotation smoothly
rb2d.MoveRotation(Quaternion.Slerp(rb2d.rotation, targetRotation, Time.deltaTime * rotationSpeed));
}
else
{
// If not using Rigidbody2D, use transform.rotation
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * rotationSpeed);
}
}
}
``````

}
In this script:

• We capture the right stick input from the gamepad using the Input System.
• We calculate the desired rotation angle based on the right stick input using `Mathf.Atan2`.
• We apply the rotation to the character using `Rigidbody2D.MoveRotation` for smooth rotation. If you’re not using `Rigidbody2D`, you can use `transform.rotation` instead.

Make sure to adjust the `rotationSpeed` variable to control how fast your character rotates in response to the right stick input.