2017-04-18 123 views
0

我想讓玩家雙跳,但玩家可以無限跳躍,任何人都可以幫助我嗎?我使用統一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; 
     } 
    } 

} 
+0

什麼是不工作,是你的角色只跳一次,他從不跳,你得到一個錯誤...並將你的代碼從'Update'移動到'FixedUpdate'。 – CNuts

+0

他只跳一次 – MightyElf

+0

哪段代碼應該移動到fixedupdate? – MightyElf

回答

2

你可以保持無限跳躍的原因是因爲你從來沒有設置groundedfalse所以它總是重置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

FixedUpdate應與剛體打交道時可以用來代替更新。

+0

非常感謝! – MightyElf

+0

@MightyElf我可以幫助我快樂:) – CNuts