- W/S :: 前进/后退
- A/D :: 下降/上升
- 鼠标滚轮 :: 对象移动的速度
- 光标水平移动 :: 对象左右方向旋转
- 光标上下移动 :: 对象上下方向旋转
using UnityEngine;
using System.Collections;
public class ObjectController : MonoBehaviour
{
public float xSpeed = 1f;
public float ySpeed = 1f;
public float zSpeed = 1f;
public Vector3 velocity = Vector3.zero;
private bool isAdown = false;
private bool isDdown = false;
private float x = 0.0f;
private float y = 0.0f;
void Update()
{
float theZ = Input.GetAxis("Vertical") * this.zSpeed;
float theX = Input.GetAxis("Horizontal") * this.xSpeed;
Vector3 v1 = new Vector3(0, 0, theZ);
v1 = this.transform.TransformDirection(v1);
v1 = v1 - Vector3.Dot(v1, Vector3.up) * Vector3.up;
v1 = this.transform.InverseTransformDirection(v1);
this.transform.Translate(v1);
Vector3 v2 = new Vector3(0, theX, 0);
this.transform.Rotate(v2);
if (Input.GetKeyDown(KeyCode.A))
this.isAdown = true;
else if (Input.GetKeyUp(KeyCode.A))
this.isAdown = false;
else if (Input.GetKeyUp(KeyCode.D))
this.isDdown = false;
else if (Input.GetKeyDown(KeyCode.D))
this.isDdown = true;
if (this.isAdown)
this.transform.position = Vector3.SmoothDamp(this.transform.position
, this.transform.position - new Vector3(0, this.ySpeed, 0)
, ref velocity, 0.1f);
if (this.isDdown)
this.transform.position = Vector3.SmoothDamp(this.transform.position
, this.transform.position + new Vector3(0, this.ySpeed, 0)
, ref velocity, 0.1f);
float zoom = Input.GetAxis("Mouse ScrollWheel");
if (this.zSpeed + zoom < 10 && this.zSpeed + zoom > 0.1)
this.zSpeed += zoom;
}
private void Rotate()
{
this.x += Input.GetAxis("Mouse X") * this.xSpeed;
this.y -= Input.GetAxis("Mouse Y") * this.ySpeed;
if (this.y < -360f)
this.y += 360f;
if (this.y > 360f)
this.y -= 360f;
y = Mathf.Clamp(y, -20f, 80f);
Quaternion rotation = Quaternion.Euler(y * 0.5f, x, 0);
this.transform.rotation = rotation;
}
private void LateUpdate()
{
Rotate();
}
}