繁体   English   中英

刚体.AddForce()不要让我的玩家每次都以相同的高度跳跃

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM