Unity 5.1.1跳过" Input.GetKeyDown"有时候

时间:2015-07-12 01:30:51

标签: c# unity3d 2d

我在Win 64位计算机上使用Unity 5.1.1,能够运行我创建的游戏。在制作2D侧面滚轮时,我发现我的角色有时在提示时不会跳跃。这是代码:

public float speed;
public float MomentAcc;
private float moveVertical;

private float score;
private float scoreP;

public GameObject wallRight;
public GUIText scoreText;
public bool touching;

void Start() {
    MomentAcc = 10;
    score = 0;

}

    //Jump limiter 
    void OnCollisionStay2D() {

    touching = true;            
}

    void OnCollisionExit2D() {

    touching = false;
}


    void Update() {

    if (Input.GetKeyDown(KeyCode.W) && touching == true || Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Began && touching == true) {

        moveVertical = 29;

    } else {

        moveVertical = 0;

    }

}

    void FixedUpdate () {


        scoreP = GameObject.Find ("Ball").GetComponent<Rigidbody2D> ().position.x + 11;

        if(scoreP > score) {

        score = score + 10;

        }   

            UpdateScore ();

                if(GetComponent<Death>().startGame == true) {



            float moveHorizontal = 5;


            Vector2 forward = new Vector2 (moveHorizontal, 0);
            Vector2 jump    = new Vector2 (0, moveVertical);


            //Maxspeed limit

            GetComponent<Rigidbody2D> ().AddForce (moveVertical * jump);


            speed = moveHorizontal * MomentAcc * Time.deltaTime * 5;



                if (GetComponent<Rigidbody2D> ().velocity.x < 7.000000) {


                GetComponent<Rigidbody2D> ().AddForce (Vector2.right * speed);




                    if(GameObject.Find ("wallRight").GetComponent<wallRightScript>().wallJumpRight == true) {

                    GetComponent<Rigidbody2D> ().AddForce (new Vector2 (-420, 300));


                    } 

                    if(GameObject.Find ("wallLeft").GetComponent<wallLeftScript>().wallJumpLeft == true) {

                        GetComponent<Rigidbody2D> ().AddForce (new Vector2(420, 150));

                    } 

                }   




        }
    }



    void UpdateScore() {

        scoreText.text = "Score: " + (score );

    }

}

(旁注:wallLeft / wallRight用于跳墙)

1 个答案:

答案 0 :(得分:1)

这是你的问题!

您正在使用Input.GetKeyDown(KeyCode.W) && touching == true,在这种情况下,您的跳转取决于touching变量,当您按“W”键时,该变量可能为false。您正在使用rigidbody,在水平拖动时,您不能指望它始终与地面发生碰撞。因此,您可能需要更改实施以进行地面检查。

This Tutorial有助于学习2D角色。

还有一个建议!尝试在一些变量中存储对象/组件的引用以轻松访问它们。在GetComponent<>中使用GameObject.Find() / Update()/FixedUpdate()效率不高,不是一种好的做法。