Unity實現攝像機以某個物體為中心旋轉


將下方代碼賦給攝像機,並指定需要圍繞的對象,即可實現攝像機隨着該物體為中心以衛星的方式進行旋轉了。

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

//攝像機操作   
//刪減版   在實際的使用中可能會有限制的需求  比如最大遠離多少  最近距離多少   不能旋轉到地面以下等
public class RotateAround : MonoBehaviour
{
    public Transform CenObj;//圍繞的物體
    private Vector3 Rotion_Transform;
    private new Camera camera;
    void Start()
    {
        camera = GetComponent<Camera>();
        Rotion_Transform = CenObj.position;
    }
    void Update()
    {
        Ctrl_Cam_Move();
        Cam_Ctrl_Rotation();
    }
    //鏡頭的遠離和接近
    public void Ctrl_Cam_Move()
    {
        if (Input.GetAxis("Mouse ScrollWheel") > 0)
        {
            transform.Translate(Vector3.forward * 1f);//速度可調  自行調整
        }
        if (Input.GetAxis("Mouse ScrollWheel") < 0)
        {
            transform.Translate(Vector3.forward * -1f);//速度可調  自行調整
        }
    }
    //攝像機的旋轉
    public void Cam_Ctrl_Rotation()
    {
        var mouse_x = Input.GetAxis("Mouse X");//獲取鼠標X軸移動
        var mouse_y = -Input.GetAxis("Mouse Y");//獲取鼠標Y軸移動
        if (Input.GetKey(KeyCode.Mouse1))
        {
            transform.RotateAround(Rotion_Transform, Vector3.up, mouse_x * 5);
            transform.RotateAround(Rotion_Transform, transform.right, mouse_y * 5);
        }
    }

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM