Code Analysis of Unity3D Tank Battle Turret Angle Moving with Main Camera

After the completion of the main functions of the camera to follow the
need to set the rotation of the fort
basic principle is placed in a turretMesh fort at (not visible)
named the turret
and the assembly placed in turret Fort file

Insert picture description hereThen create an instance object turret

    public Transform turret;
        public Transform turret;


    public Transform gun;

    private float turretRotSpeed = 0.3f;

    private float turretRotTarget = 0;
    private float turretRollTarget = 0;



    private float maxRoll = 10f;
    private float minRoll = -4f;

Insert picture description hereFind turret (instantiated)

    void Start ()
    {


        turret = transform.Find("turret");
        if (turret == null)
        {
            Debug.Log("turret is null");
        }
        }
    void Update() {
        //欧拉角 要左右转的话 绕世界线的y轴 主相机位置 
        turretRotTarget = Camera.main.transform.eulerAngles.y;
        
//方法
        TurretRotation();
}

Insert picture description here



  //炮塔旋转
    public void TurretRotation()
    {


        if (Camera.main == null)
            return;
        if (turret == null)
            return;

        //归一化角度

        //var 角 = 当前炮塔的欧拉角 减去 主机欧拉夹角
        float angle = turret.eulerAngles.y - turretRotTarget;
		//鼠标左右摇晃 则turretRotTarget必然会变化   通过angle的变换推断  turret.Rotate的左右摆动位置
        if (angle < 0) angle += 360;

        if (angle > turretRotSpeed && angle < 180)
            turret.Rotate(0f, -turretRotSpeed, 0f);
        else if (angle > 180 && angle < 360 - turretRotSpeed)
            turret.Rotate(0f, turretRotSpeed, 0f);



        turretRotTarget = turret.eulerAngles.y - turretRollTarget;


    }`

Published 271 original articles · Like 44 · Visits 50,000+

Guess you like

Origin blog.csdn.net/qq_38992403/article/details/105239216