Unity点击物体摄像机推进跟随

/***********************
* Title:        
* FileName:         
* Date:         2020
* Author:       玄策
* Version:      1.0
* UnityVersion: 2019.2.4f1
* Description:  
* Func:           
* -    使用方法:在需要跟随的物体的脚本OnMouseDown中上添加下两行代码
*                   CamFollow.Instance.Obj = gameObject;
                    CamFollow.Instance.followObj();
***********************/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
public class CamFollow : SingletonMono
{
    GameObject gameObj; //要跟随的物体

    GameObject Cam;

    //public Vector3 StartCamPos;  //摄像机跟随物体前的位置信息
    //public Vector3 StartCamRo;

    bool isPosTrue; //是否跟随点击物体

    Vector3 v; ////物体与摄像机的向量

    void Awake()
    {
        Cam = Camera.main.gameObject;

        //StartCamPos = Cam.transform.position;  //记录初始位置
        //StartCamRo = Cam.transform.eulerAngles;

    }

    void Update()
    {
        //摄像机一直跟随
        if (isPosTrue)
        {
            if (gameObj != null)
            {
                Cam.transform.position = gameObj.transform.position - v.normalized * 5;
                Cam.transform.LookAt(gameObj.transform);

            }

            if (Input.GetMouseButtonDown(1) || Input.GetMouseButtonDown(2))
            {
                breakObj();
            }
        }
        
    }
    /// 
    /// 跃进观看并跟随动
    /// 
    public void FollowObj(GameObject Obj)
    {
        gameObj = Obj;
        
        //关闭相机控制
        Camera.main.GetComponent().enabled = false;

        //记录初始位置
        //StartCamPos = Cam.transform.position;  
        //StartCamRo = Cam.transform.eulerAngles;

        //跟随物体
        StartCoroutine(followToObj(Obj));
    }
    IEnumerator followToObj(GameObject Obj)
    {
        Cam.transform.LookAt(Obj.transform); //摄像机朝向物体

        v = Obj.transform.position - Cam.transform.position;
        //移动动画
        Cam.transform.DOLocalMove(Obj.transform.position - v.normalized * 5, 1).SetEase(Ease.Linear);;

        yield return new WaitForSeconds(1);
        isPosTrue = true;

    }

    /// 
    /// 恢复正常视角
    /// 
    public void breakObj()
    {
        //关闭跟随
        isPosTrue = false;
        Camera.main.GetComponent().enabled = true;
    }

    //2.-------------------------
    //后写的通用方法,只跃进查看
    //public void FollowObj(GameObject Obj)
    //{
    //    StartCoroutine(FollowToObj(Obj));
    //}
    //IEnumerator FollowToObj(GameObject Obj)
    //{
    //    yield return new WaitForSeconds(0);
    //    v = Obj.transform.position - Camera.main.transform.position;
    //    //移动动画
    //    Camera.main.transform.DOLocalMove(Obj.transform.position - v.normalized * 5, 1).SetEase(Ease.Linear);
    //    Camera.main.transform.LookAt(Obj.transform); //摄像机朝向物体
    //}
}

你可能感兴趣的:(Unity点击物体摄像机推进跟随)