C# script to rotate GameObject to mouse cursor.

 

Content not available.
Please allow cookies by clicking Accept on the banner

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;
        difference.Normalize();

        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:

Content not available.
Please allow cookies by clicking Accept on the banner



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

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

  • July 13, 2017 at 6:45 pm
    Permalink

    Any way to slerp to the position?

    Reply
    • July 14, 2017 at 10:29 am
      Permalink

      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 😉

      Reply
      • March 12, 2018 at 2:55 am
        Permalink

        hi thanks for your very good codes.. slerp need Quaternion but rotation_z is a float and Causing an error
        could we Create a variable of type “Quaternion ” and entered numbers… Az rotation_z in it? pls type hire that codes tnx
        my english is bad 🙂 also my programing : ))

        Reply
      • March 12, 2018 at 4:42 am
        Permalink

        this is working 🙂 —enjoy
        public class test3 : MonoBehaviour {

        public Transform from // drag your Obj to this in unity Panel
        public float speed = 1.5F;

        void Start () {}
        void Update () {
        Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        Vector2 direction = mousePos – transform.position;
        float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
        Quaternion myrotation = Quaternion.AngleAxis(angle, Vector3.forward);
        transform.rotation = Quaternion.Lerp(transform.rotation, myrotation, speed*10 * Time.deltaTime);

        if (Vector2.Distance(from.position, mousePos) > 0.9f {
        transform.position = Vector2.MoveTowards(from.position, mousePos, speed * 2 * Time.deltaTime); // for Move Object : ))
        }
        }}

        Reply
  • February 11, 2018 at 8:45 pm
    Permalink

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

    Reply
    • February 12, 2018 at 8:20 pm
      Permalink

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

      Reply
  • February 26, 2018 at 7:32 pm
    Permalink

    How can we rotate the game object to right and left with using keys like “a” and “d”? And then maybe go forward with the key “w”.

    Reply
  • March 12, 2018 at 5:01 am
    Permalink

    this is work 100% – change “yourNameScript” to yourNameScript 🙂

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

    public class yourNameScript : MonoBehaviour {
    public Transform from; // drag your Obj to this in unity Panel
    public float speed = 1.5F;
    void Start() { }
    void Update(){
    Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    Vector2 direction = mousePos – transform.position;
    float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
    Quaternion myrotation = Quaternion.AngleAxis(angle, Vector3.forward);
    transform.rotation = Quaternion.Lerp(transform.rotation, myrotation, speed * 10 * Time.deltaTime);
    if (Vector2.Distance(from.position, mousePos) > 0.9f ){
    transform.position = Vector2.MoveTowards(from.position, mousePos, speed * 2 * Time.deltaTime); // for Move Object : ))
    }}}

    Reply
    • March 12, 2018 at 5:07 am
      Permalink

      subtraction : ” – ” is changed by site : (
      in line 13
      Edit yourself

      Reply
  • March 20, 2018 at 6:52 pm
    Permalink

    I tried this but on a 3d Object, and it never stopped moving anyone know why?

    Reply
  • August 28, 2018 at 5:56 pm
    Permalink

    Is there a way to offset the rotation origin? right now this script rotates from the game object’s origin so it only rotates on top of that, with no distance in between; I am trying to rotate a child object around my character, so i’d like some distance between the two, so my rotating is some distance/radius away from its parent, so both are visible, think enter the gungeon.

    any help is appreciated thanks,

    -e

    Reply
    • August 28, 2018 at 6:16 pm
      Permalink

      It is, create new empty GameObject, add this script to it, and inside it place your object(without script) and move it a bit relative to parent object. Hope it helps 🙂

      Reply
      • August 28, 2018 at 7:38 pm
        Permalink

        guess what, it DID help !! works perfectly now, thanks for the speedy reply, you are awesome !!

        -e

        Reply
        • August 28, 2018 at 7:51 pm
          Permalink

          Glad to hear that, have fun with it 😉

          Reply

Leave a Reply

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

By continuing to use the site, you agree to the use of cookies. You can read more about it the Cookies&Privacy Policy Section Above. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this. You can read more about it the Cookies&Privacy Policy Section.

Close