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

相机跟随功能:当要跟随的物体开始移动、旋转的时候,主视角跟着变化
在实现功能之前,首先要考虑我们都需要干什么;
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));

        }
    }
}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值