C# script to rotate GameObject to mouse cursor.

 

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

// © 2017 TheFlyingKeyboard
// 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:

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

2 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

Leave a Reply

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