设置物体为刚体,在代码中赋予刚体速度
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement3D : MonoBehaviour
{
// Start is called before the first frame update
public float speed=20;
private Vector3 motion;
private Rigidbody rb;
void Start()
{
rb=GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
motion=new Vector3(Input.GetAxisRaw("Horizontal"),0,Input.GetAxisRaw("Vertical"));
rb.velocity=motion*speed;
}
}
GetAxisRaw(“Horizontal”)会根据你的输入进行赋值.
具体设置可在File-BuildSettings-Player Settings-InputManager里设置
具有刚体组件并不代表物体会碰撞
如果要发生碰撞还需另外添加一个碰撞器Collider组件
物体旋转
//从上下到下依次为对应的参数,代码中只用了前四个参数
//current 当前位置。
//target 尝试达到的目标。
//currentVelocity 当前速度,此值由函数在每次调用时进行修改。
//smoothTime 达到目标所需的近似时间。值越小,达到目标的速度越快。
//maxSpeed 可以选择允许限制最大速度。
//deltaTime 自上次调用此函数以来的时间。默认情况下为 Time.deltaTime
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y,targetAngle,ref turnSmoothVelocity,turnSmoothTime);
transform.rotation = Quaternion.Euler(0f, angle, 0f);
平滑旋转
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y,targetAngle,ref turnSmoothVelocity,turnSmoothTime);
设置旋转角度
transform.rotation = Quaternion.Euler(0f, angle, 0f);