我正在統一制作一些東西,我可以走到前面、左邊和右邊,但是每當我試圖向后退時,我的播放器會走得更快,盡管它們的編碼方式相同。我很新,所以我不知道為什么這不起作用。有人有類似的問題嗎?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Walk : MonoBehaviour
{
public Rigidbody rb;
private bool moving;
public float Speed;
void Update()
{
if (Input.GetKey("right"))
{
rb.AddForce(Speed*Vector3.right);
moving = true;
}
else{moving = false;}
if (Input.GetKey("left"))
{
rb.AddForce(Speed*Vector3.left);
moving = true;
}
else{moving = false;}
if (Input.GetKey("up"))
{
rb.AddForce(Speed*Vector3.forward);
moving = true;
}
else{moving = false;}
if (Input.GetKey("down"))
{
rb.AddForce(Speed*Vector3.back);
moving = true;
}
else{moving = false;}
if (moving)
{
moving = true;
}
else{rb.velocity = Vector3.zero;}
}
}
uj5u.com熱心網友回復:
試試這個:
private Rigidbody _rigidbody;
private float _movementForce = 10f;
private double _maximumVelocity = 10f;
private void Awake() => _rigidbody = GetComponent<Rigidbody>();
private void Update(){
if(_rigidbody.velocity.magnitude >= _maximumVelocity)
return;
if(Input.GetKey("up"))
_rigidbody.AddForce(_movementForce * transform.forward);
if(Input.GetKey("down"))
_rigidbody.AddForce(_movementForce * -transform.forward); // -forward gives u back
if(Input.GetKey("left"))
_rigidbody.AddForce(_movementForce * -transform.right);
if(Input.GetKey("right"))
_rigidbody.AddForce(_movementForce * transform.right);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/408553.html
標籤:
下一篇:不能統一移動相機
