Transform.Rotate not working around certain axes
I am trying to write a missile guidance script using proportional navigation. However, I encountered a problem with the Transform.Rotate function in Unity. When rotating around every axis except the Z-axis (0,0,1), everything works as expected (see video, https://youtu.be/LlWNCr0PSvY if this link doesn't work try the one below). Only when rotating around the Z-axis nothing happens. So far I have narrowed it down to the -90 degrees X orientation I start the rocket with. When I mirror this situation such that I need to start the rocket with a 90 degrees Y orientation to point at the target the same behaviour is shown. I have no idea what is going wrong here. Can someone please help?
void FixedUpdate()
{
Vector3 LOS = target.transform.position - transform.position; //Line of sight (Black)
Vector3 LOSGain = LOS.normalized - prevLOS.normalized; //Change in LOS (Red)
float LOSAng = Vector3.Angle(transform.forward, LOS);
Debug.DrawRay(transform.position, LOS, Color.black);
Debug.DrawRay(transform.position, LOSGain*10, Color.red);
Vector3 perpVec = Vector3.Cross(LOS.normalized, LOSGain.normalized); //perpVec is perpindicular to both the LOS and the LOS change
float rotationSpeed = Mathf.Clamp(Mathf.Abs(LOSGain.magnitude * N), 0, maxAngCorr); //rotationspeed = Omega * N (Clamped to maximum rotation speed)
transform.Rotate(perpVec, rotationSpeed); //<--Rotate happens here
Debug.Log("SHOULD BE ROTATING");
Debug.Log("perpVec: " + perpVec);
Debug.Log("rotationSpeed: " + rotationSpeed);
Debug.DrawRay(transform.position, perpVec.normalized * 10, Color.blue);
prevLOS = LOS;
}
I have also tried this parallel code and it has the same problem:
Quaternion rot = Quaternion.AngleAxis(rotationSpeed, perpVec.normalized); // rotate with rotationSpeed around perpVec axis.
transform.rotation *= rot;
I forgot to add, more complex axes seem to kind of work, however, I think not perfectly. I think in more complex situations it can rotate around two axes but not the third 'locked' one, but that is a guess.
Answer by VozzeTheCreator · Aug 29, 2020 at 02:05 PM
I have found a solution that avoids the problem by doing the rotation in another way:
Vector3 newLookDirection = Quaternion.AngleAxis(rotationSpeed, perpVec) * transform.forward;
transform.LookAt(transform.position + newLookDirection);
However, it would be nice if someone can shine some light on why the other solutions don't work, but now this one is working flawlessly :)
Your answer
Follow this Question
Related Questions
Unity 2D lookat and shoot issues 0 Answers
GameObject not looking at me.. 1 Answer
How to make the rotation of a child object of object A match the rotation of object B ? 0 Answers
Weird rotation when using Slerp!!? 3 Answers
Is there a transform method equivalent to assigning euler angle offsets? 1 Answer