C# make object rotate to mouse code example
Example 1: Point to mouse 2D Unity
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);
Example 2: unity rotate towards mouse
using UnityEngine; using System.Collections; public class SCR_mouseRotation : MonoBehaviour { void Update () { Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.z, 10); Vector3 lookPos = Camera.main.ScreenToWorldPoint(mousePos); lookPos = lookPos - transform.position; float angle = Mathf.Atan2(lookPos.z, lookPos.x) * Mathf.Rad2Deg; transform.rotation = Quaternion.AngleAxis(angle, Vector3.down);