- Home /
I'm new to Unity and C# and I need help with a character control problem.
I would like the character to slowly turn its head towards the camera but clamping the y axis so the head doesn't turn all the way around. I left in the code some of the ways I've tried to achieve the desired outcome
using UnityEngine; using System.Collections;
public class LookAtSlow : MonoBehaviour { // the target too look at public Transform target; // rotationSpeed is the usual slerp speed factor // maxAnglePerSecond is the maximum angle travelled per second (in degrees) public float rotationSpeed = 4f, maxAnglePerSecond = 10f; void Update() { // first calculate the look vector as normal Vector3 targetDirection = (target.position - transform.position).normalized; Vector3 currentForward = transform.forward; Vector3 newForward = Vector3.Slerp(currentForward, targetDirection, Time.deltaTime * rotationSpeed);
     // now check if the new vector is rotating more than allowed
     float angle = Vector3.Angle(currentForward, newForward);
     float maxAngle = maxAnglePerSecond * Time.deltaTime;
     
     if (angle > maxAngle)
     {
         // it's rotating too fast, clamp the vector
         newForward = Vector3.Slerp(currentForward, newForward, maxAngle / angle);
     }
     // This code changes the character's x axis but it doesnt clamp the y axis
     //newForward.y = Mathf.Clamp(transform.rotation.y, -20.0f, 20.0f);
     
     // The if statements make the character's head change direction in the x axis when active but doesnt clamp the y
     //if (transform.eulerAngles.y > 40)
     //{
     //transform.eulerAngles = new Vector3 (newForward.x, 40, newForward.z);
     //transform.rotation = Quaternion.Euler(newForward.x, 0.41f, newForward.z);
     //newForward.y = transform.eulerAngles.y;
     // }
     // assign the new forward to the transform
     transform.forward = newForward;
 }
}
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                