I am trying to get transform.rotation.z to chase the mouse pointer at a rotation speed. But I get a very weird results and can't figure out what I am doing wrong.

var mp = Input.mousePosition;
var camZ = Camera.main.transform.position.z;
// Grab the current mouse position on the screen.
// Subtract the cams Z from the mouse Z to get ground plane. 
var mousePos = Camera.main.ScreenToWorldPoint (
                           new Vector3 (mp.x, mp.y, mp.z - camZ));
//Rotates toward the mouse                      
var targetEuler = new Vector3 (0, 0, 
      Mathf.Atan2 ((mousePos.y - transform.position.y), 
                   (mousePos.x - transform.position.x)) * Mathf.Rad2Deg - 90);
transform.eulerAngles = new Vector3 (0, 0,
      Mathf.Lerp (transform.eulerAngles.z, targetEuler.z,
                  Time.deltaTime * rotationSpeed));

OKi was way off. This is how i got it to work.

                        rotationTarget = Camera.main.ScreenToWorldPoint (Input.mousePosition);                      

                    var _lookRotation = Quaternion.LookRotation (transform.position - rotationTarget, Vector3.forward);

                    _lookRotation.x = 0.0f;

                    _lookRotation.y = 0.0f;

                    transform.rotation = Quaternion.Slerp (transform.rotation, _lookRotation, Time.deltaTime * rotationSpeed);  

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.