2014-10-30 107 views
1

您好,感謝您閱讀本文。停止在我的Unity遊戲中跳轉的玩家/用戶

我是Unity的新手,但不管如何,我設法制作了一個小型2D遊戲。但是我遇到了跳轉功能的一個小問題。

玩家/用戶不應該能夠在遊戲中多跳。

這是控制播放器的C#腳本。

using UnityEngine; 
using System.Collections; 

public class RobotController : MonoBehaviour { 
//This will be our maximum speed as we will always be multiplying by 1 
public float maxSpeed = 2f; 
public GameObject player; 
//a boolean value to represent whether we are facing left or not 
bool facingLeft = true; 
//a value to represent our Animator 
Animator anim; 
//to check ground and to have a jumpforce we can change in the editor 
bool grounded = true; 
public Transform groundCheck; 
float groundRadius = 0.2f; 
public LayerMask whatIsGround; 
public float jumpForce = 700f; 

// Use this for initialization 
void Start() { 
    //set anim to our animator 
    anim = GetComponent <Animator>(); 

} 


void FixedUpdate() { 
    //set our vSpeed 
    anim.SetFloat ("vSpeed", rigidbody2D.velocity.y); 
    //set our grounded bool 
    grounded = Physics2D.OverlapCircle (groundCheck.position, groundRadius, whatIsGround); 
    //set ground in our Animator to match grounded 
    anim.SetBool ("Ground", grounded); 


    float move = Input.GetAxis ("Horizontal");//Gives us of one if we are moving via the arrow keys 
    //move our Players rigidbody 
    rigidbody2D.velocity = new Vector3 (move * maxSpeed, rigidbody2D.velocity.y); 
    //set our speed 
    anim.SetFloat ("Speed",Mathf.Abs (move)); 
    //if we are moving left but not facing left flip, and vice versa 
    if (move > 0 && !facingLeft) { 

     Flip(); 
    } else if (move < 0 && facingLeft) { 
     Flip(); 
    } 
} 

void Update(){ 
    //if we are on the ground and the space bar was pressed, change our ground state and add an upward force 
    if(grounded && Input.GetKeyDown (KeyCode.UpArrow)){ 
     anim.SetBool("Ground",false); 
     rigidbody2D.AddForce (new Vector2(0,jumpForce)); 
    } 


} 

//flip if needed 
void Flip(){ 
    facingLeft = !facingLeft; 
    Vector3 theScale = transform.localScale; 
    theScale.x *= -1; 
    transform.localScale = theScale; 
} 
} 

這裏是Player對象和GroundCheck對象。

enter image description here enter image description here

如何從能夠multijump停止播放。所以如果他按上箭鍵,他會跳起來,在他着陸之前不能再跳。 感謝您的時間和幫助

更新

如果它很難看到圖像這裏有上Imgur圖片: http://imgur.com/GKf4bgi,2i7A0AU#0

+0

您是否試過將跳轉代碼移動到'FixedUpdate'而不是'Update'?這可能會產生一些影響,因爲這是您檢查球員是否接地的地方。 – Catwood 2014-10-30 10:57:05

回答

2

您可以添加其他撞機您的播放器遊戲物體,並使其與Is Trigger選項的觸發器。使用此代碼來更改標誌變量說服力的,如果玩家在地面上:

private bool isOnGround = false; 
void OnCollisionEnter2D(Collision2D collision) { 
    isOnGround = true;  
} 

void OnCollisionExit2D(Collision2D collision) { 
    isOnGround = false; 
} 

然後,你可以只允許跳躍時isOnGround是真實的。

2

您可以創建一個名爲groundController小遊戲對象,將其下播放器。 你正在設置布爾值接地和代碼檢查你的控制器是否與地面重疊。

看它這裏獲取更多信息:http://youtu.be/Xnyb2f6Qqzg?t=45m22s