Unity中攝像機的重要性毋庸置疑,關於攝像機的操作也有很多,比如第一人稱跟隨,第二人稱跟隨,攝像機的拉近拉遠等等,下面就暫時實現攝像機的拉近拉遠和旋轉:
創建新的場景,場景中添加一個cube,然后給cube添加新的腳本,腳本內容如下:
using UnityEngine;
using System.Collections;
public class TestCube : MonoBehaviour {
private GameObject rotateObj;
private GameObject camera;
public float speed = 3f;
private bool rotate = false;
public float maxView = 90;
public float minView = 10;
void Start()
{
rotateObj = GameObject.Find("Rotate");
camera = GameObject.Find("Main Camera");
}
void Update () {
//滑動鼠標滑輪控制視角的大小
float offsetView = Input.GetAxis("Mouse ScrollWheel") * speed;
float tmpView = offsetView + Camera.main.fieldOfView;
tmpView = Mathf.Clamp(tmpView, minView, maxView);
Camera.main.fieldOfView = tmpView;
//繞主角旋轉攝像機
if(rotate)
{
camera.transform.RotateAround(transform.position, Vector3.up, speed * Input.GetAxis("Mouse X"));
}
if(Input.GetMouseButtonDown(0))
{
rotate = true;
}
if(Input.GetMouseButtonUp(0))
{
rotate = false;
}
}
}
