控制摄像机一直看物体的正方,并且相距一定距离

来源:互联网 发布:橡树岛宝藏 知乎 编辑:程序博客网 时间:2024/04/30 17:04


    private bool blStart;
    private GameObject camer;
    private GameObject target;

   // private float height = 10;
    private float rotationDamping = 3;
    private float curDis = 100;
   // private float heightDamping = 3;

    private Vector3 tartPos;


 void Update()
    {
        UpdateCamerLogic();
    }


public void ControlCamerLogic(GameObject camer, GameObject target)
    {
        blStart = true;
        this.camer = camer;
        this.target = target;
        tartPos = target.transform.position - target.transform.forward * curDis;
    }


 private void UpdateCamerLogic()
    {
       
        if (blStart)
        {

 // Calculate the current rotation angles
       
        var wantedRotationAngleY = target.transform.eulerAngles.y;
        var wantedRotationAngleX = target.transform.eulerAngles.x;


        var currentRotationAngleY = camer.transform.eulerAngles.y;
        var currentRotationAngleX = camer.transform.eulerAngles.x;



        // Damp the rotation around the y-axis
        currentRotationAngleY = Mathf.LerpAngle(currentRotationAngleY, wantedRotationAngleY, rotationDamping * Time.deltaTime);
        currentRotationAngleX = Mathf.LerpAngle(currentRotationAngleX, wantedRotationAngleX, rotationDamping * Time.deltaTime);

      
        // Convert the angle into a rotation
        var currentRotation = Quaternion.Euler(currentRotationAngleX, currentRotationAngleY, 0);

        //var testRotation = Quaternion.LookRotation(target.transform.forward); //这个方法和上面的方法等价,是unity封装的
        //Debug.Log("========>currentRotation:" + currentRotation + "=========>testRotation:" + testRotation);


        // Set the position of the camera on the x-z plane to:
        // distance meters behind the target
        var curPos = camer.transform.position;

        float posX = Mathf.Lerp(curPos.x, tartPos.x, rotationDamping * Time.deltaTime);
        float posY = Mathf.Lerp(curPos.y, tartPos.y, rotationDamping * Time.deltaTime);
        float posZ = Mathf.Lerp(curPos.z, tartPos.z, rotationDamping * Time.deltaTime);
        camer.transform.position = new Vector3(posX, posY, posZ);
        camer.transform.rotation = currentRotation;

     }

   }




0 0