Unity Lerp does not work correctly when gameObject rotation changes
Hi, everybody!
I want to automatically rotate my tower (base for gun and gun itself) towards targets (rockets). Problem is that if i place tower on horizontal surface, seems that all work fine, but if i place tower at some angle or upside down (yes, my game include those scenarios), tower can't aim correctly.
My code:
{
public void OnTriggerStay(Collider other)
{
if (other.gameObject.tag == "Rocket")
{
//Base for gun rotation on Y axis (horizontal rotation)
Vector3 direction = other.transform.position - gameObject.transform.GetChild(0).position;
Quaternion targetRotation = Quaternion.LookRotation(direction);
Vector3 rotation = Quaternion.Lerp(gameObject.transform.GetChild(0).transform.localRotation, targetRotation, speed * Time.deltaTime).eulerAngles;
gameObject.transform.GetChild(0).localRotation = Quaternion.Euler(0, rotation.y, 0);
//Gun rotation on X axis (Vertical rotation)
Vector3 direction1 = other.transform.position - gameObject.transform.GetChild(0).GetChild(0).position;
Quaternion targetRotation1 = Quaternion.LookRotation(direction1);
Vector3 rotation1 = Quaternion.Lerp(gameObject.transform.GetChild(0).GetChild(0).transform.localRotation, targetRotation1, speed * Time.deltaTime).eulerAngles;
gameObject.transform.GetChild(0).GetChild(0).localRotation = Quaternion.Euler(rotation1.x, 0, 0);
}
}
}
Tower consists of 2 parts: gameObject.transform.GetChild(0) - GunBase (will rotate only on local Y axis) gameObject.transform.GetChild(0).GetChild(0) - Gun (will rotate only on local X axis)
Tower works normal when placed horizontaly : Incorrect when angle changes:
Does anyone know what the problem is?
снимок.png
(281.8 kB)
снимок1.png
(120.0 kB)
Comment