Skip to content

Instantly share code, notes, and snippets.

@unitycoder
Last active February 11, 2024 15:42
Show Gist options
  • Save unitycoder/5366a610599b503a40e9 to your computer and use it in GitHub Desktop.
Save unitycoder/5366a610599b503a40e9 to your computer and use it in GitHub Desktop.
Rotate sprite towards mouse
// Rotate sprite/object towards mouse
// Reference: http://johnstejskal.com/wp/rotating-objects-and-sprites-in-unity3d-using-cs-c/
// https://forum.unity3d.com/threads/how-to-detect-angle-from-one-object-to-another-in-2d.477510/
// Usage: Attach this script to sprite, use Orthographic camera!
using UnityEngine;
using System.Collections;
public class RotateSpriteTowardsMouse : MonoBehaviour
{
private Camera cam;
void Start ()
{
cam = Camera.main;
}
void Update ()
{
Vector3 mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
// rotate Y (green axis) towards mouse
//transform.rotation = Quaternion.LookRotation(Vector3.forward, mousePos - transform.position);
// rotate Y (green axis) away from mouse
//transform.rotation = Quaternion.LookRotation(Vector3.forward, transform.position-mousePos);
// rotate X (red axis) towards mouse
Vector3 perpendicular = Vector3.Cross(transform.position-mousePos,Vector3.forward);
transform.rotation = Quaternion.LookRotation(Vector3.forward, perpendicular);
// rotate X (red axis) away from mouse
//Vector3 perpendicular = Vector3.Cross(mousePos-transform.position,Vector3.forward);
//transform.rotation = Quaternion.LookRotation(Vector3.forward, perpendicular);
// using lookat
// transform.LookAt(target.position, new Vector3(0, 0, -1));
// can also set transform.up (green axis)
//mousePos.z = 0;
//transform.up = mousePos - transform.position;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment