杂谈(相机跟随功能详解)(7)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/lfanyize/article/details/102769129

相机跟随功能:当要跟随的物体开始移动、旋转的时候,主视角跟着变化
在实现功能之前,首先要考虑我们都需要干什么;
1.获取相机与要跟随的物体。’
2.确定相机与物体之间的距离与高度。
3.需要知道要跟随的对象的位置、高度、旋转角度等。
4.需要知道当前的相机位置、高度、旋转角度等。

代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class OwnMake : MonoBehaviour
{
    public Transform Target;//用来获取要跟随的对象
    public Transform selfTransform;//获取相机
    public float distance = 50.0f;//要跟随的距离
    public float Height = 10.0f;//跟随时的高度
    public float HeightDamping = 2.0f;//设定高度阻尼
    public float RotateDamping = 3.0f;//设定旋转阻尼
    // Start is called before the first frame update
    void Start()
    {
        Target = this.gameObject.GetComponent<Transform>();//获取到要跟随物体的Transform组件

    }

    // Update is called once per frame
    void Update()
    {
        if (!Target)
        {
            return;
        }
        else
        {


            float wantedHeight = Target.position.y + Height;//跟随物体的位置加上设定的两者之间的高度
            float wantedRotation = Target.eulerAngles.y;//跟随物体绕y轴旋转的角度

            float currentHeight = selfTransform.position.y;//当前相机的高度为
            float currentRotation = selfTransform.rotation.y;//相机当前的旋转角度

            currentHeight = Mathf.Lerp(currentHeight, wantedHeight, HeightDamping * Time.deltaTime);
            currentRotation = Mathf.LerpAngle(currentRotation, wantedRotation, RotateDamping * Time.deltaTime);

            //开始设定相机旋转的功能
            Quaternion currentRotate = Quaternion.Euler(0, currentRotation, 0);

            selfTransform.position = Target.position;
            selfTransform.position -= currentRotate * Vector3.forward * distance;

            //开始设定相机移动的功能

            Vector3 CurrHeight = Target.position;
            CurrHeight.y = currentHeight;

            selfTransform.position = CurrHeight + new Vector3(0, 0, 20);
            selfTransform.LookAt(Target.position + new Vector3(0, 10, 0));

        }
    }
}

实现效果如下:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/lfanyize/article/details/102769129