Sunday 2 April 2023

 how to rotate a tank turret and its barrel to point to a target in Unity? here is the code,

using UnityEngine;


public class tank_controller2 : MonoBehaviour

{

    public Transform turret;

    public Transform barrel;

    public Transform target;

    public float turretRotationSpeed = 5f;

    public float barrelRotationSpeed = 5f;

    public float turretRotationRange = 30f;

    public float barrelMinRotationRange = -20f; // Add this line

    public float barrelMaxRotationRange = 30f; // Add this line


    void Update()

    {

        Vector3 targetDirection = target.position - transform.position;

        float yAngle = Mathf.Atan2(targetDirection.x, targetDirection.z) * Mathf.Rad2Deg;

        yAngle = Mathf.Clamp(yAngle, -turretRotationRange, turretRotationRange);

        turret.rotation = Quaternion.RotateTowards(turret.rotation, Quaternion.Euler(0f, yAngle, 0f), turretRotationSpeed * Time.deltaTime);


        Vector3 localTarget = turret.InverseTransformPoint(target.position);

        float xAngle = -Mathf.Atan2(localTarget.y, localTarget.z) * Mathf.Rad2Deg;

        xAngle = Mathf.Clamp(xAngle, barrelMinRotationRange, barrelMaxRotationRange); // Update this line

        barrel.localRotation = Quaternion.RotateTowards(barrel.localRotation, Quaternion.Euler(xAngle, 0f, 0f), barrelRotationSpeed * Time.deltaTime);


        Debug.DrawLine(barrel.position, target.position);

    }

}