C# script to rotate GameObject to mouse cursor.


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

// © 2017 TheFlyingKeyboard and released under MIT License
// theflyingkeyboard.net

public class RotateToMouse : MonoBehaviour {
  public float offset = 0.0f;

  // Use this for initialization
  void Start () {
  // Update is called once per frame
  void Update () {
        Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;

        float rotation_z = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.Euler(0f, 0f, rotation_z + offset);

Offset instructions for below sprite:

with settings:

Object behaves as shown in video:

Unity 2D C# Rotate GameObject To Mouse Cursor
Tagged on:         

4 thoughts on “Unity 2D C# Rotate GameObject To Mouse Cursor

  • July 13, 2017 at 6:45 pm

    Any way to slerp to the position?

    • July 14, 2017 at 10:29 am

      Change this: transform.rotation = Quaternion.Euler(0f, 0f, rotation_z + offset);
      to this: transform.rotation = Quaternion.Slerp(from.rotation, rotation_z + offset, Time.time * speed);
      and add public float speed at top of the script
      I have not tested it, but I think it should work 😉

  • February 11, 2018 at 8:45 pm

    my rotation is delayed by 90 degrees, do you have any idea why?

    • February 12, 2018 at 8:20 pm

      Your sprite is probably rotated, change offset, as shown in the second video 🙂


Leave a Reply

Your email address will not be published. Required fields are marked *