在我的Unity游戏中停止播放器/用户多跳

时间:2014-10-30 10:35:34

标签: unity3d

您好,感谢您阅读本文。

我是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

如何阻止播放器进行多重播放。因此,如果他按下upArrow键,他会跳起来,在他降落之前不能再跳。 感谢您的时间和帮助

更新

如果很难看到这里的图像是Imgur上的图像: http://imgur.com/GKf4bgi,2i7A0AU#0

2 个答案:

答案 0 :(得分:2)

您可以制作一个名为groundController的小游戏对象,将其置于播放器下。 您正在设置接地的bool值,并在代码中检查您的控制器是否与地面重叠。

在此处观看以获取更多信息:http://youtu.be/Xnyb2f6Qqzg?t=45m22s

答案 1 :(得分:2)

您可以将另一个Collider添加到您的玩家GameObject,并使其成为Is Trigger选项的触发器。使用此代码更改标志变量,告知玩家是否在地上:

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

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

然后,只有在isOnGround为真时才允许跳转。