我在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用于跳墙)

最佳答案

这是你的问题!

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

This Tutorial非常适合学习2D角色。

还有一个建议!尝试将对象/组件的引用存储在某些变量中以方便地访问它们。在GetComponent<>中使用GameObject.Find() / Update()/FixedUpdate()效率不高,因此不是一个好习惯。

07-25 20:56