玩家脚本无法向右移动并同时跳跃

时间:2018-02-17 05:50:24

标签: c# unity5

我正在学习Unity,我正在编写一个播放器脚本。根据我写的剧本,我希望看到我的玩家能够在站立时跳起,同时向左移动,同时向右移动。 如果玩家同时向右移动,则玩家无法跳跃。我做了一堆重构和重组。我认为这可能与Input.GetButton("Jump")有关。

此外,我将rb2d.AddForce(new Vector2(0.0f, jumpHeight))更改为rb2d.velocity = new Vector2(0.0f, jumpHeight),但播放器刚刚消失。

到目前为止,这是我的脚本:

private Rigidbody2D rb2d;
[SerializeField]
private LayerMask whatIsGround;
private bool isTouchingGround;
private bool facingRight = true;

[SerializeField]
private float speed;

[SerializeField]
private float jumpHeight;

[SerializeField]
private Transform[] groundPoints;

[SerializeField]
private float groundRadius;

// Use this for initialization
void Start () {
    rb2d = GetComponent<Rigidbody2D>(); 
}
private void FixedUpdate() {
    float moveHorizontal = Input.GetAxis("Horizontal");
    Flip(moveHorizontal);
    if (Input.GetButton("Jump") && IsGrounded()) {
        rb2d.AddForce(new Vector2(0.0f, jumpHeight));
    }

    rb2d.velocity = new Vector2(moveHorizontal * speed, rb2d.velocity.y);
}

private void Flip(float horizontal) {
    if ((horizontal > 0 && !facingRight) || (horizontal < 0 && facingRight)) {
        facingRight = !facingRight;
        Vector3 theScale = transform.localScale;
        theScale.x *= -1;
        transform.localScale = theScale;
    }
}

private bool IsGrounded() {
    if (rb2d.velocity.y <= 0) {
        foreach (Transform point in groundPoints) {
            Collider2D[] colliders = Physics2D.OverlapCircleAll(point.position, groundRadius, whatIsGround);
            foreach (Collider2D collider in colliders) {
                if (collider.gameObject != gameObject)
                    return true;
            }
        }
    }
    return false;
}

1 个答案:

答案 0 :(得分:0)

我找到了一个解决方案,但我不确定为什么它解决了这个问题。如果你有一个想法,请在下面评论!

private bool IsGrounded()方法中,我删除了if语句检查rb2d.velocity.y <= 0。我认为这将是一个有用的检查,看看球员是向下移动还是静止。出于某种原因,正确地移动玩家是因为if语句失败了。这似乎是一个错误。

相关问题