using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RotateToTarget : MonoBehaviour
{
// The target marker.
public Transform target;
// Angular speed in radians per sec.
public float speed = 1.0f;
void Update()
{
// Determine which direction to rotate towards
Vector3 targetDirection = target.position - transform.position;
// The step size is equal to speed times frame time.
float singleStep = speed * Time.deltaTime;
// Rotate the forward vector towards the target direction by one step
Vector3 newDirection = Vector3.RotateTowards(transform.forward, targetDirection, singleStep, 0.0f);
newDirection.x = ClampAngle(newDirection.x, 60f, -60f);
// Calculate a rotation a step closer to the target and applies rotation to this object
transform.rotation = Quaternion.LookRotation(newDirection);
}
float ClampAngle(float angle, float from, float to)
{
if (angle < 0f) angle = 360 + angle;
if (angle > 180f) return Mathf.Max(angle, 360 + from);
return Mathf.Min(angle, to);
}
}
By adding the line :
newDirection.x = ClampAngle(newDirection.x, 60f, -60f);
It’s making the object to rotate very very fast nonstop from side to side like crazy.
I want to clamp the rotation on the two axis x and y at this angles : Z is optional :
Rotation : X between 60 and -60
Rotation : Y between 100 and -100
Rotation : Z between 60 and -60 ( Only if needed optional )