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);}}}