为什么我不跳,或跳得好?

时间:2014-10-23 17:57:01

标签: c# unity3d

现在我没有从中得到太多。根据我所做的不同,我最终会遇到无限循环,或者跳跃能力差。我用一个计时器来勾选我跳过的布尔但我得到了一个像跳跃能力的双倍,我的地面检测不够好。你能看出为什么我不能跳,或跳得好吗?

using UnityEngine;
using System.Collections;

public class player : MonoBehaviour 
{
    public float speed = 0.05f;
    public float jumpVelocity = 0.05f;
    public bool onGround = true;
    public bool jumped = false;

    // Use this for initialization
    void Start () { }

    // Update is called once per frame
    void Update () 
    {
        //test if player is on the ground
        if (onGround) { jumped = false; }

        // USER CONTROLS HERE.
        if (Input.GetKeyDown(KeyCode.Space) && onGround == true) 
        {
            jumped = true;

            while(jumped) 
            {
                this.rigidbody2D.AddForce(new Vector2(0, jumpVelocity));

                if (onGround) { jumped = false; }
            }
        }
        else if (Input.GetKey(KeyCode.RightArrow)) 
        {
            this.transform.position += Vector3.right * speed * Time.deltaTime;
        }
        else if (Input.GetKey(KeyCode.LeftArrow)) 
        {
            this.transform.position += Vector3.left * speed * Time.deltaTime;
        }
    }

    void OnCollisionEnter2D(Collision2D col)
    {
        if(col.gameObject.tag == "floor") { onGround = true; }
    }

    void OnCollisionStay2D(Collision2D col)
    {       
        if(col.gameObject.tag == "floor") { onGround = true; }
    }   
}

1 个答案:

答案 0 :(得分:1)

您的问题源于对Update方法和物理如何工作的误解。如果你在更新方法中这样做,它将创建一个无限循环:

while(jumped) 
{
    this.rigidbody2D.AddForce(new Vector2(0, jumpVelocity));

    if(onGround)
    {
        jumped = false;
    }
}

问题是你告诉物理机构添加一个力量。但是你一遍又一遍地这样做。物理模拟仅在返回之后发生,因此无论“onGround”是什么,它都永远不会成为真,因为直到Update方法之后才会施加力。

相反,每次Update方法运行时都必须反复进行此检查,直到onGround为真。