通过修改位置来实现移动
利用修改Transform组件的position的两种常用方法。
1.使用Translate()函数。
2.直接指定新的位置
void Update()
{
transform.Translate(1.5f,0,0);
//或
transform.position += new Vector3(1.5f,0,0);
}
通过物理系统实现位移
1。利用AddForce()对物体施加力改变位置
2.直接修改物体的速度
public Rigidbody rb;
void FixedUpdate()
{
rb.AddForce(10*Time.fixedDeltaTime,0,0);
//或
rb.velocity = new Vector3(10*Time.fixedDeltaTime,rb.velocity .y,rb.velocity.z);
}
通过输入控制物体移动
以键盘的W、A、S、D为例文章来源:https://uudwc.com/A/nP3RV
参考unity的输入管理器的横轴输入与纵轴输入文章来源地址https://uudwc.com/A/nP3RV
public Rigidbody rb;
public float speed;
void FixedUpdate()
{
float horizontal = Input.GetAxis("Horizontal");
float vetical = Input.GetAxis("Vetical");
rb.AddForce(horizontal*speed*Time.fixedDeltaTime,vetical*speed*Time .fixedDeltaTime,0);
//或
rb.velocity = new Vector3(horizontal*speed*Time.fixedDeltaTime,vetical*speed*Time.fixedDeltaTime,rb.velocity.z);
}