unity 一个物体随键盘上下左右旋转和前进的脚本

注意:脚本挂在gamaobject 上面 ,操作对象的目标  this.gameObject 为操作对象

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class changePosition : MonoBehaviour
{

    //操作对象的目标  this.gameObject 为操作对象

    public int moveSpeed = 5;
    public float RotationSpeed = 60;
    private void Update()
    {
        //w0s1a0 d1 /上下左右
        float hor = Input.GetAxis("Horizontai");
        float ver = Input.GetAxis("Vertical");
        if (hor != 0 || ver != 0)
        {
            MovementRotation(hor, ver);
        }
    }


    //直线旋转操作
    public void MovementRotation(float hor, float ver)
    {
        // LookRotation 获取旋转方向 
        //                  (0,0,1)    
        //
        //     (-1,0,0)      物体        (1,0,0)
        //
        //                  (0,0,-1) 
        //  LookRotation 参数 例子 (1, 0, 0)表示正X轴方向 (-1, 0, 0)表示负X轴方向
        Quaternion dir = Quaternion.LookRotation(new Vector3(hor, 0, ver));
        //旋转,赋值速转,没有过渡
        // this.transform.rotation = dir;
        //渐渐旋转
        this.transform.rotation = Quaternion.Lerp(this.gameObject.transform.rotation, dir, Time.deltaTime * RotationSpeed);
        //前进 ,自身z 方向前进
        if (Mathf.Abs(ver) > 0.1)
        {
            this.transform.Translate(0, 0, Time.deltaTime * moveSpeed);
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值