unity rotate towards mouse 3d code example
Example 1: how to make an object point towards the mouse in unity
//Inside your update loop, add the following code:
//First, get the mouse position
Vector2 mousePosition = new Vector2 (
Input.GetAxis("MouseX"),
Input.GetAxis("MouseY")
);
//Then, use unity's built-in lookAt function to do all the math for you:
transform.LookAt(mousePosition);
Example 2: unity rotate towards
Quaternion.RotateTowards(Quaternion from, Quaternion to, float maxDegreesDelta);
Example 3: 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); // Turns Right transform.rotation = Quaternion.AngleAxis(angle, Vector3.up); //Turns Left } }
Example 4: unity make 3d object spin towards mouse
public class LookTowardMouse : MonoBehaviour { // Update is called once per frame void Update () { //Get the Screen positions of the object Vector2 positionOnScreen = Camera.main.WorldToViewportPoint (transform.position); //Get the Screen position of the mouse Vector2 mouseOnScreen = (Vector2)Camera.main.ScreenToViewportPoint(Input.mousePosition); //Get the angle between the points float angle = AngleBetweenTwoPoints(positionOnScreen, mouseOnScreen); //Ta Daaa transform.rotation = Quaternion.Euler (new Vector3(0f,0f,angle)); } float AngleBetweenTwoPoints(Vector3 a, Vector3 b) { return Mathf.Atan2(a.y - b.y, a.x - b.x) * Mathf.Rad2Deg; } }