Reputation: 11321
Later also to the sides but for now on Y.
using UnityEngine;
using System;
using System.Collections;
public class RotationTest : MonoBehaviour
{
public Transform target;
public Transform objToRotate;
void LateUpdate()
{
Vector3 relativePos = target.position - objToRotate.position;
Quaternion rotation = Quaternion.LookRotation(relativePos, Vector3.up);
rotation.y = Mathf.Clamp(rotation.y, -1f, 1f);
objToRotate.rotation = rotation;
}
}
I tried with the line :
rotation.y = Mathf.Clamp(rotation.y, -1f, 1f);
but it's not working I tried also the values -50f and 50f
Upvotes: 0
Views: 859
Reputation: 90580
Quaternion
has four components, x, y, z, w
and they all move in the range -1, 1
.. so your clamping is absolutely useless ;)
=> Never touch a the components of a Quaternion
directly unless you really know exactly what you are doing!
In your case you seem to want to limit the angle it rotates around the given axis (in your case Vector3.up) so what you can use would be Quaternion.ToAngleAxis
, limit that angle and convert it back to a rotation using Quaternion.AngleAxis
like e.g.
Quaternion rotation = Quaternion.LookRotation(relativePos, Vector3.up);
// Extract the axis and angle
rotation.ToAngleAxis (out var angle, out var axis);
// Since ToAngleAxis returns only unsigned angle
// this checks if we actually have a negative rotation
if(angle > 180)
{
angle -= 360;
}
// Clamp the angle to the desired limits
angle = Mathf.Clamp(angle, -50, 50);
// Finally convert both back to a rotation
transform.rotation = Quaternion.AngleAxis(angle, axis);
Upvotes: 1