- Home /
Rotating object around Z axis with lerp/slerp
Im trying to rotate my player to face where I last clicked. I've acutally manged to do this, but now I want to see the player rotate at a set speed instead of the sprite just changing rotation instantly. Ive tried several methods I've found online, but none of them work for me. Here's what I have
 void Update()
 {
    if (Input.GetMouseButtonDown (0)) 
    {
 
             Vector3 diff = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
             diff.Normalize();
             float rot_z = Mathf.Atan2(diff.y, diff.x) * Mathf.Rad2Deg;
             transform.rotation= Quaternion.Euler(0f, 0f, rot_z - 90);
 
 
             Instantiate(ProjectilePrefab, transform.position, transform.rotation);
         }
 }
The code above works fine, but it shows no movement. I have tried to do this but the position is wrong and the rotation is instant as well:
 Vector3 diff = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
 var newRotation = Quaternion.LookRotation(diff);
 newRotation.y = 0.0f;
 newRotation.x = 0.0f;
 transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, Time.deltaTime * 30);
Any ideas?
               Comment
              
 
               
              Answer by prof3ta · Jun 19, 2014 at 12:48 AM
So, finally found the answer. I still dont understand but I made it work
  if (Input.GetMouseButtonDown (0)) {
                     target = Camera.main.ScreenToWorldPoint (Input.mousePosition);
                     rotateToTarget = true;
                     print ("NEW TARGET: " + target);
             }
 
             if (rotateToTarget == true && target != null) {                             
                     print ("Rotating towards target");
 
 
                     targetRotation = Quaternion.LookRotation (transform.position - target.normalized, Vector3.forward);
                     targetRotation.x = 0.0f;//Set to zero because we only care about z axis
                     targetRotation.y = 0.0f;
 
                     player.transform.rotation = Quaternion.Slerp (transform.rotation, targetRotation, Time.deltaTime * rotationSpeed);  
 
 
 
                     if (Mathf.Abs (player.transform.rotation.eulerAngles.z - targetRotation.eulerAngles.z) < 1) {
 
                             rotateToTarget = false;
                             travelToTarget = true;
                             player.transform.rotation = targetRotation;
                             print ("ROTATION IS DONE!");
                     }
             }
 
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                