- Home /
need my object to rotate between specific angles on the x axis
so currently I'm trying to make a spotlight for a ship and in the editor, I know that the points that I need are between two vectors ie. vector3(60,-90,-90) and vector3(120,-90,-90)
and I'm wanting to just have a locked rotation between these two points and I've tried everything I can think of using quaternion.Lerp or LerpAngle. or using mathf.lerp, or vector3.lerp. or something as simple as transform.rotate and played with using the lookat function. but it seems no matter how I format this the rotation is straight nonsense.
if you have any example, suggestions or require more information I would be happy to record a short youtube video for you guys.
Thank you for all your time and effort. and keep on keeping on!
Answer by maxoja · Sep 13, 2018 at 08:27 PM
I hope this snippet of code could help. It uses Quaternion.Lerp to interpolate rotation between your 2 angular points.
public float speed = 1;
float ratio = 0;
Quaternion rotationA = Quaternion.Euler(60, -90, -90);
Quaternion rotationB = Quaternion.Euler(120, -90, -90);
public void Update()
{
ratio += Time.deltaTime;
if (ratio >= 2f)
ratio -= 2;
if (ratio <= 1f)
transform.rotation = Quaternion.Lerp(rotationA, rotationB, ratio);
else
transform.rotation = Quaternion.Lerp(rotationA, rotationB, 1-(ratio-1));
}
This worked for me!!! thank you. one question though could you briefly explain this to me else transform.rotation = Quaternion.Lerp(rotationA, rotationB, 1-(ratio-1));
I'm not entirely sure how the 1-(ratio -1) works.
Normally when we Lerp(a, b, ratio) while increasing ratio constantly from 0.0 to 1.0, it basically means "from a to b". In order to reverse the phrase to "from b to a", I can Lerp(a, b, 1-ratio) ins$$anonymous$$d. However, in our case, the ratio in else block is changing from 1.0 to 2.0 which means its value is 1.0 ahead. That is why I need to subtract is by 1, and the final statement becomes Lerp(a, b, 1-(ratio-1))
Answer by Atiyeh123 · Sep 13, 2018 at 08:22 PM
Hi @keilovergames If your problems is just limiting the angle of rotation you can do this.
angle = Mathf.Clamp(angle, min, max); // it clamps the angle between a min and max angle you want
the rest code is like this:
float angle = Mathf.Atan2 (transform.position.y - target.transform.position.y,
transform.position.x - target.transform.position.x) * Mathf.Rad2Deg;
angle = Mathf.Clamp(angle, min, max);
Quaternion rotateTo = Quaternion.AngleAxis (angle , Vector3.forward);
transform.rotation= Quaternion.Slerp (transform.rotation, rotateTo, Time.deltaTime * 10f);