Unity3D、Camera跟隨人物、圍繞物體旋轉(zhuǎn)

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

public class FollowPlayer : MonoBehaviour {
    public float distance = 0;
    public float scrollSpeed = 10;
    public float rotateSpeed = 2;

    private Transform player;
    private Vector3 offSetPostion;//鏡頭位置偏移量
    private bool isRotating = false;//鼠標(biāo)水平滑動(dòng)


    // Use this for initialization
    void Start()
    {
        player = GameObject.FindGameObjectWithTag(Tags.player).transform;
        transform.LookAt(player.position);
        offSetPostion = transform.position - player.position;
    }

    // Update is called once per frame
    void Update()
    {
        transform.position = offSetPostion + player.position;
        //處理視野的旋轉(zhuǎn)
        RotateView();
        //處理視野的拉近拉遠(yuǎn)效果
        ScrollView();

    }

    void ScrollView()
    {
        distance = offSetPostion.magnitude; //返回向量的長(zhǎng)度
        distance += Input.GetAxis("Mouse ScrollWheel") * scrollSpeed;   //返回虛擬軸的值Mouse ScrollWheel:鼠標(biāo)滑輪
        distance = Mathf.Clamp(distance, 8, 18);//限制鏡頭最近和最遠(yuǎn)距離
        offSetPostion = offSetPostion.normalized * distance;
    }

    void RotateView()
    {
        //Input.GetAxis("Mouse X");//得到鼠標(biāo)在水平方向上的滑動(dòng)
        // Input.GetAxis("Mouse Y");//得到鼠標(biāo)在垂直方向上的滑動(dòng)

        if (Input.GetMouseButtonDown(1))
        {
            isRotating = true;
        }

        if (Input.GetMouseButtonUp(1))
        {
            isRotating = false;
        }

        if (isRotating)
        {

            Vector3 originalPos = transform.position;
            Quaternion originalRotation = transform.rotation;

            transform.RotateAround(player.position, player.up, rotateSpeed * Input.GetAxis("Mouse X"));
            transform.RotateAround(player.position, transform.right, -rotateSpeed * Input.GetAxis("Mouse Y"));
            float x = transform.eulerAngles.x;

            if (x > 80 || x < 35)
            {
                transform.position = originalPos;
                transform.rotation = originalRotation;
            }
        }
        offSetPostion = transform.position - player.position;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容