让玩家双跳

时间:2017-04-18 20:07:36

标签: c# unity3d

我想允许玩家双跳,但玩家可以无限跳跃,任何人都可以帮助我吗?我使用Unity 5

using System.Collections.Generic;
using UnityEngine;

public class PlayerControl : MonoBehaviour {

    public float moveSpeed;
    public float jumpHeight;
    private bool grounded;
    private Rigidbody2D rb;
    private int jumpCount = 0;
    private int maxJumps = 2;

    // Use this for initialization
    void Start () {

    }
    // Update is called once per frame
    void Update () {
        if (Input.GetKeyDown (KeyCode.Space) && jumpCount < maxJumps) {
            rb = GetComponent<Rigidbody2D> ();
            rb.velocity = new Vector2 (rb.velocity.x, jumpHeight);
            jumpCount = jumpCount + 1;
        }

        if (grounded == true) {
            jumpCount = 0;
        } 

        if (Input.GetKey (KeyCode.D)) {
            rb.velocity = new Vector2 (moveSpeed,rb.velocity.y);
        }

        if (Input.GetKey (KeyCode.A)) {
            rb.velocity = new Vector2 (-moveSpeed,rb.velocity.y);
        }
    }
    void OnCollisionEnter2D (Collision2D collider){
        if (collider.gameObject.tag == "Ground") {
            grounded = true;
        }
    }

}

1 个答案:

答案 0 :(得分:2)

您可以无限跳跃的原因是因为您从未将grounded设置为false,因此它会始终将jumpCount的值重置为0

if (grounded == true) {
    jumpCount = 0;
} 

所以当你跳过设置grounded = false因为你不再在地面时。

if (Input.GetKeyDown (KeyCode.Space) && jumpCount < maxJumps) {
    rb = GetComponent<Rigidbody2D> ();
    rb.velocity = new Vector2 (rb.velocity.x, jumpHeight);
    jumpCount = jumpCount + 1;

    grounded = false;
}

使用RigidBody和物理时,最好使用FixedUpdate

  

在处理Rigidbody时,应该使用FixedUpdate而不是Update。

相关问题