I’m trying to have an object rotate towards the mouse pointer on click.
I managed to get that working but the object rotates instantly and i can’t quite figure out how i can make it rotate slowly…
This is my code.
using UnityEngine;
using System.Collections;
public class mouselook : MonoBehaviour {
Vector3 direction;
Vector3 hitpoint;
RaycastHit hit;
float angleDeg;
float angleRad;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0) )
{
Ray ray = (Camera.main.ScreenPointToRay(Input.mousePosition));
Physics.Raycast(ray, out hit);
hitpoint = hit.point;
direction = hitpoint - this.transform.position;
Vector3 relative = transform.InverseTransformDirection(direction);
angleRad = Mathf.Atan2(relative.x,relative.z);
angleDeg = angleRad * Mathf.Rad2Deg;
transform.Rotate(Vector3.up,angleDeg);
}
}
Do not rotate the fill amount of “angleDeg”. Instead rotate a constant (smaller) degree step every frame/update and then check if you have arrived at the desired angle. Once you have arrived or are near enough (difference smaller then the step size) stop rotating.