Unity中我会的两种移动方式
- Transform.Translate移动,也是最基本的移动方式
public float speed = 5;
void Update()
{
Move();
}
void Move()
{
if (Input.GetKey(KeyCode.W)|Input.GetKey(KeyCode.UpArrow))
{
this.transform.Translate(Vector3.forward * speed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.S) | Input.GetKey(KeyCode.DownArrow))
{
this.transform.Translate(Vector3.back * speed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.A) | Input.GetKey(KeyCode.LeftArrow))
{
this.transform.Translate(Vector3.left * speed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.D) | Input.GetKey(KeyCode.RightArrow))
{
this.transform.Translate(Vector3.right * speed * Time.deltaTime);
}
}
- Rigidbody(刚体)
public Rigidbody rigid;
public float speed;
void FixedUpdate()
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
if (Input.GetKey(KeyCode.W)|Input.GetKey(KeyCode.S))
{
rigid.velocity = Vector3.forward * vertical * speed;
}
if (Input.GetKey(KeyCode.A) | Input.GetKey(KeyCode.D))
{
rigid.velocity = Vector3.right * horizontal * speed;
}
}
- 总结
以上的forward,back , left,right可以在unity的官方文档中查找到分别对应前后左右。
其中update函数是每一帧执行一遍(start只是开始执行一遍),而fixedupdate则是每0.02秒执行一次,Time.deltaTime则是根据机型、电脑的配置自适应帧数,所以,如果是Update中就需要用Time.deltaTime来优化,但FixedUpdate中用Time.deltaTime的话就会显得速度很慢。