兩個代碼都附在MainCamera上面,可以實現鍵盤加鼠標漫遊
1、KeyMove.cs 鍵盤漫遊
using UnityEngine;
using System.Collections;
public class KeyMove : MonoBehaviour {
void Start () {
}
void Update () {
//前後左右
if (Input.GetKey (KeyCode.A)) {
transform.Translate (-25 * Time.deltaTime,0, 0 , Space.Self);
}
if (Input.GetKey (KeyCode.D)) {
transform.Translate ( 25 * Time.deltaTime,0, 0 , Space.Self);
}
if (Input.GetKey (KeyCode.W)) {
transform.Translate (0, 0, 25 * Time.deltaTime, Space.Self);
}
if (Input.GetKey (KeyCode.S)) {
transform.Translate (0, 0 , -25 * Time.deltaTime,Space.Self);
}
//旋轉
if (Input.GetKey (KeyCode.Q)) {
transform.Rotate (0, -25 * Time.deltaTime, 0, Space.Self);
}
if (Input.GetKey (KeyCode.E)) {
transform.Rotate (0, 25 * Time.deltaTime, 0, Space.Self);
}
if (Input.GetKey (KeyCode.Z)) {
transform.Rotate (-25 * Time.deltaTime,0, 0 , Space.Self);
}
if (Input.GetKey (KeyCode.C)) {
transform.Rotate ( 25 * Time.deltaTime,0, 0 , Space.Self);
}
//升高降低鏡頭
if (Input.GetKey (KeyCode.H)) {
transform.Translate (0, 5 * Time.deltaTime, 0);
}
if (Input.GetKey (KeyCode.N)) {
transform.Translate (0, -5 * Time.deltaTime, 0);
}
}
}
2、【轉發】鼠標漫遊
using UnityEngine;
using System.Collections;
public class FlyMove : MonoBehaviour {
private float sensitivityX = 1F; //X轉動增量速度
private float sensitivityY = 1F; //y轉動增量速度
private float minimumY = -90F; //Y軸轉動限制
private float maximumY = 90F;
float rotationY = 0F; //y起始值
private float MovingSpeed = 1f; //移動屏幕的速度
float delta_x,delta_y,delta_z; //計算移動量
float distance = 5;
float ZoomSpeed = 20f; //拉近拉遠速度
Quaternion rotation;
void Start () {
}
void Update () {
if(Input.GetMouseButton(0)){//左鍵旋轉屏幕
{
float rotationX = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * sensitivityX;
rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
rotationY = Mathf.Clamp (rotationY, minimumY, maximumY);
transform.localEulerAngles = new Vector3(-rotationY, rotationX, 0);
}
}
if (Input.GetMouseButton(2)){
}
if(Input.GetAxis("Mouse ScrollWheel")!= 0){//滾軸拉近拉遠
delta_z = -Input.GetAxis("Mouse ScrollWheel") * ZoomSpeed;
transform.Translate(0,0,-delta_z);
distance += delta_z;
}
if (Input.GetMouseButton (2)) {//滾軸中間移動屏幕
delta_x = Input.GetAxis("Mouse X") * MovingSpeed;
delta_y = Input.GetAxis("Mouse Y") * MovingSpeed;
rotation = Quaternion.Euler(0, transform.rotation.eulerAngles.y,0 );
transform.position =rotation * new Vector3(-delta_x,-delta_y,0)+transform.position;
}
}
}