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();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值