UICamrea和其他Camera的区别,Camera跟随人物移动的脚本,人物移动结合遥感

UICamera单独拿来渲染UI层的东西,Camera 用作主Camera,且UICamera要渲染
的Depth only要比主Camera要大,这样UICamera层的东西就能展现在Main Camera前边
下边附上Camera跟随人物移动的脚本

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

public class CameraFollowPlayer : MonoBehaviour
{
    
    



    private Vector3 offset;
    public Transform role;
    public float moveSpeed = 3;
    public float rotateSpeed = 3;

    // Start is called before the first frame update
    void Start()
    {
    
    
        offset = transform.position - role.position;
        offset = new Vector3(0, offset.y, offset.z);
    }

    // Update is called once per frame
    void Update()
    {
    
    
        Vector3 beginPos = role.position + offset;//摄像机正常偏移位置,起点
        Vector3 endPos = role.position + offset.magnitude * Vector3.up;//offset.magnitude向量的长度
        ///从起点到终点分别取3个点,通过射线判断摄像机是否有遮挡
        Vector3[] posArr = new Vector3[] {
    
    
            beginPos,
            Vector3.Lerp(beginPos,endPos,0.25f),
            Vector3.Lerp(beginPos,endPos,0.5f),
            Vector3.Lerp(beginPos,endPos,0.75f),
            endPos
        };
        Vector3 targetPos = posArr[0];
        foreach (var pos in posArr)
        {
    
    
            RaycastHit hitInfo;
            ///第一个参数射线的起点,第二个参数射线的方向
            if (Physics.Raycast(pos, role.position - pos, out hitInfo))
            {
    
    
                if (hitInfo.collider.tag == "Player")
                {
    
    
                    targetPos = pos;
                    break;
                }
                else
                {
    
    
                    continue;
                }
            }
            else
            {
    
    
                targetPos = pos;
                break;
            }
        }
        this.transform.position = Vector3.Lerp(transform.position, targetPos, Time.deltaTime * moveSpeed);//通过插值平滑移动
        Quaternion nowRotation = transform.rotation;
        this.transform.LookAt(role.position);//摄像机转向目标
        this.transform.rotation = Quaternion.Lerp(nowRotation, transform.rotation, Time.deltaTime * rotateSpeed);//通过插曲平滑旋转
    }
}

并且结合遥控控制人物的主要核心代码

 if (myplayState==PlayerState.NoneIdle)
        {
    
    
            ani.SetBool("Canwalk", true);

            this.transform.rotation = Quaternion.LookRotation(this.dir);

            this.transform.Translate(dir * Time.deltaTime * distanceSpeed, Space.World);

        }

猜你喜欢

转载自blog.csdn.net/charlsdm/article/details/126209890
今日推荐