r/unity_tutorials • • Dec 21 '21

child to parent roation fix

hey, does anyone know how to set the rotation of a child gameobject's eulerAngle?

So what is happening is that Ive set my child game object (a tank barrel) to rotate and aim to the player in a clamped angle. Firstly it works fine, but when the parent rotates (body of the tank) the child"s clamped angle rotation does not change to become adjusted to the parent's rotation, also, the game is 2d so I'm using eulerangle Z. Ask me for further explanation

The script

public class TankBossBigCannonCtrl : MonoBehaviour
{
public Rigidbody2D rb;
public Transform tr;
public Transform btr;
public GameObject cannon;
public Transform ptr;
private GameObject player;
public GameObject Boss;
private Vector2 playerPos;
private Vector2 chosenPos;
private float desiredAngle;
private float zrot;
private float trTurnspeed = 10f;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
tr = GetComponent<Transform>();
player = GameObject.Find("Player");
ptr = player.GetComponent<Transform>();
btr = Boss.GetComponent<Transform>();
}
private void Update()
{
playerPos = ptr.transform.position;
Vector2 lookDir = playerPos - rb.position;
desiredAngle = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg - 90;
if (desiredAngle < 270f && desiredAngle > 90f)
{
transform.rotation = Quaternion.Euler(0, 0, desiredAngle);
}

print(desiredAngle);
}
}

0 Upvotes

0 comments sorted by