0

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

1 Answers1

1

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);
derHugo
  • 83,094
  • 9
  • 75
  • 115
  • When I move the target object behind the objToRotate the objToRotate is getting back to its original idle position but how can I make that it will return to its original idle position a bit slower smooth? If I move the target object sharp very fast behind the player's head his head returns to the original idle position but too fast. I want that his head will return slower smooth to its original pos when the target object is behind the player. – Oled Neduda Jul 24 '21 at 18:29
  • Nothing in your code is moving smooth at all. If you want smooth rotation then see e.g. [Rotate GameObject over time](https://stackoverflow.com/questions/37586407/rotate-gameobject-over-time) – derHugo Jul 24 '21 at 22:41