1.直接修改速度(Rigidbody2D.velocity)
public float speed = 5f;
private Rigidbody2D rb;
void Start() {
rb = GetComponent<Rigidbody2D>();
}
void Update() {
float moveX = Input.GetAxisRaw("Horizontal");
float moveY = Input.GetAxisRaw("Vertical");
rb.velocity = new Vector2(moveX, moveY) * speed;
}
2.使用刚体移动位置(Rigidbody2D.MovePosition)
public float speed = 3f;
private Rigidbody2D rb;
private Vector2 movement;
void Start() {
rb = GetComponent<Rigidbody2D>();
}
void Update() {
movement = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
}
void FixedUpdate() {
// 计算目标位置并移动
Vector2 targetPos = rb.position + movement * speed * Time.fixedDeltaTime;
rb.MovePosition(targetPos);
}
3. 修改Transform位置(Transform.Translate)
public float speed = 5f;
void Update() {
float moveX = Input.GetAxis("Horizontal") * speed * Time.deltaTime;
float moveY = Input.GetAxis("Vertical") * speed * Time.deltaTime;
transform.Translate(moveX, moveY, 0);
}
4. 使用CharacterController组件
public float speed = 6f;
private CharacterController controller;
void Start() {
controller = GetComponent<CharacterController>();
}
void Update() {
Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
controller.Move(move * speed * Time.deltaTime);
}
免责声明:本文系网络转载或改编,未找到原创作者,版权归原作者所有。如涉及版权,请联系删