unity 控制对象移动、旋转

来源:互联网 发布:淘宝店铺贷款利息多少 编辑:程序博客网 时间:2024/06/10 02:37
  • 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();    }}
0 0
原创粉丝点击