1. 程式人生 > >unity 控制物件移動、旋轉

unity 控制物件移動、旋轉

  • W/S :: 前進/後退
  • A/D :: 下降/上升
  • 滑鼠滾輪 :: 物件移動的速度
  • 游標水平移動 :: 物件左右方向旋轉
  • 游標上下移動 :: 物件上下方向旋轉
using UnityEngine;
using System.Collections;

public class ObjectController : MonoBehaviour
{
    // x方向移動的速度
    public float xSpeed = 1f;

    // y方向移動的速度
    public float ySpeed = 1f;

    // z方向移動的速度
    public float
zSpeed = 1f; public Vector3 velocity = Vector3.zero; // 是否按下A鍵 private bool isAdown = false; // 是否按下D鍵 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(); } }