方法一:改变物体的transform
public class ExampleClass : MonoBehaviour { public float speed = 5; // 跟随摄像机的移动要写在LateUpdate中 void LateUpdate() { transform.Translate(0, 0, Time.deltaTime * speed); } }
方法二:使用刚体的位移函数MovePosition()
public class ExampleClass : MonoBehaviour { public float speed = 6.0f; Vector3 movement; void Start() { playerRigidbody = rigidbody; } void FixedUpdate() { // 角色控制 float h = Input.GetAxisRaw("Horizontal"); // 获取横轴值 float v = Input.GetAxisRaw("Vertical"); // 获取纵轴值 Move(h, v); } void Move(float h, float v) { movement.Set(h, 0, v); movement = movement.normalized * speed * Time.deltaTime; playerRigidbody.MovePosition(transform.position + movement); } }
方式三:改变刚体的速度rigidbody.velocity。速度是矢量,具有方向性。
public class ExampleClass : MonoBehaviour { // 获取摇杆值 float moveHorizontal = Input.GetAxis("Horizontal"); float moveVertical = Input.GetAxis("Vertical"); // 改变速度 rigidbody.velocity = new Vector3(moveHorizontal, 0.0f, moveVertical) * speed; }
原文:http://www.cnblogs.com/guxin/p/unitiy-how-to-move-player.html