【问题标题】:Player Script cant move right and jump at the same time玩家脚本不能同时向右移动和跳跃
【发布时间】:2018-02-19 00:24:54
【问题描述】:

我正在学习 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;
}

【问题讨论】:

    标签: c# unity5


    【解决方案1】:

    我找到了一个解决方案,但我不确定它为什么解决了这个问题。如果您知道原因,请在下方评论!

    private bool IsGrounded() 方法中,我删除了检查rb2d.velocity.y &lt;= 0 是否为if 的语句。我认为这将有助于检查玩家是向下移动还是静止不动。出于某种原因,向右移动玩家会使 if 语句失败。这似乎是一个错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多