[英]rigidbody.AddForce() don't make my player jump at the same height everytime in unity
所以我制作了一個帶有剛體和一個子游戲對象“腳”的玩家,我還在我的玩家可以跳下的每個平台上添加了一個“地板”層,這樣我就可以使用 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);
使用 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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.