- Home /
Question by
ahadi71 · Sep 14, 2020 at 07:59 AM ·
lookatlookrotation
How to stop LookRotation() spinning problem?
Hello my friends. Lets Assume I have 2 game objects ( obj 1 and obj 2). I want to local 'Y' axis of obj 2 is in the direction of obj 1. So i write a following code in a update function of my script:
Vector3 dir = obj1.transform.position - obj2.transform.position;
Quaternion holderRotation = Quaternion.LookRotation(obj2.transform.right, dir);
obj2.rotation = holderRotation;
And to be honest its kinda working! but the problem is game object 2 begins to spin around its local 'Y' axis. Does any one can help me how can I stop this spinning? sorry about bad english btw.
Comment
Answer by WarmedxMints · Sep 14, 2020 at 10:36 AM
What I would do if I only wanted to rotate on the Y-axis is reset the Y value of the vectors to zero so only the X and Z positions are taken into account when calculating the rotation.
I would do something like this;
public class FaceObject : MonoBehaviour
{
//Populate in Inspector
public Transform ObjToRotate;
//Populate in Inspector
public Transform ObjToFace;
private void Update()
{
var rot = RotateToFaceObject(ObjToRotate, ObjToFace);
ObjToRotate.rotation = rot;
}
private Quaternion RotateToFaceObject(Transform objToRotate, Transform objToFace)
{
var obj1Pos = objToRotate.position;
//Reset Y Pos so we only rotate on Y Axis
obj1Pos.y = 0f;
var obj2Pos = objToFace.position;
//Reset Y Pos
obj2Pos.y = 0f;
//Get vector direction
var direction = obj2Pos - obj1Pos;
//Calc rotation
var rot = Quaternion.LookRotation(direction);
return rot;
}
}
Your answer