所以我制作了一個帶有剛體和一個子游戲物件“腳”的玩家,我還在我的玩家可以跳下的每個平臺上添加了一個“地板”層,這樣我就可以使用 Physics.CheckSphere() 來查看我的玩家是否真的在地面,可以跳躍。在最后一種情況下,我使用 ForceMode.Impulse 向我的剛體添加一個力。一切正常,只是有時玩家會跳一點,有時跳得更高。這是我的代碼:
[SerializeField] private float speed;
[SerializeField] private float jumpForce;
[SerializeField] private Transform feet = null;
[SerializeField] private LayerMask floorMask;
private Vector3 direction;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
direction = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical")) * speed;
transform.LookAt(transform.position new Vector3(direction.x, 0, direction.z));
}
void FixedUpdate()
{
rb.velocity = new Vector3(direction.x, rb.velocity.y, direction.z);
if (Input.GetKeyDown(KeyCode.Space))
{
if (Physics.CheckSphere(feet.position, 0.1f, floorMask))
{
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
}
}
我用速度替換了 AddForce 方法,它似乎有效,但 AddForce 不是進行跳躍的正確方法?
rb.velocity = new Vector3(rb.velocity.x, 1 * jumpForce, rb.velocity.z);
uj5u.com熱心網友回復:
使用 ForceMode.Impulse 是使用 RigidBody 實作跳躍的理想方式。我相信您需要從 FixedUpdate() 中取出按鈕輸入并將其放入常規 Update() 中。然后使用諸如“canJump”之類的布林值。這是因為您的輸入是在 FixedUpdate() 中讀取的;物理引擎僅每隔一幀呼叫一次。此外,您的 rb.velocity.y 應在接觸地面時設定為 0。
void Update() {
direction = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical")) * speed;
transform.LookAt(transform.position new Vector3(direction.x, 0, direction.z));
bool canJump = Input.GetKeyDown(keyCode.Space) ? true : false;
}
void FixedUpdate() {
if (Physics.CheckSphere(feet.position, 0.1f, floorMask)) {
if (canJump)
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
else
rb.velocity = new Vector3(direction.x, 0, direction.z);
}
else
rb.velocity = new Vector3(direction.x, rb.velocity.y, direction.z);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/336655.html
