团结 - 无限跳跃



我在Unity 2D中的脚本有问题,因为我的角色无限跳跃,你能帮帮我吗(我是Unity的菜鸟)。我用布尔值尝试过一件事,但没有结果......我在 C# 中的代码是:

using UnityEngine;
using System.Collections;
public class Movements2D : MonoBehaviour {
    public float movementSpeed = 5.0f;
    private float jumpHeight = 500f;
    // Use this for initialization
    void Start () {
    }
    // Update is called once per frame
    void Update () {
        if(Input.GetKey("left") || Input.GetKey("q"))
        {
            transform.position += Vector3.left * movementSpeed * Time.deltaTime;
        }
        if(Input.GetKey("right") || Input.GetKey("d"))
        {
            transform.position += Vector3.right * movementSpeed * Time.deltaTime;
        }
        if(Input.GetButtonDown("Jump") || Input.GetKey("z"))
        {
            Jump();
        }
    }
    void Jump()
    {
        rigidbody.AddForce (new Vector3 (0, jumpHeight, 0), ForceMode.Force);
    }

}

感谢您的帮助,

弗洛。

在添加导致他们向上移动的力之前,您没有检查您的角色是否在地板上。此检查通常使用 Raycast 完成。所以也许像这样:

void Jump()
{
    RaycastHit2D hit = Physics2D.Raycast(transform.position, -Vector2.up, 0.1f);
    if (hit.collider != null)
    {
        rigidbody.AddForce (new Vector3 (0, jumpHeight, 0), ForceMode.Force);
    }
}

这将从角色的当前位置向下投射一条光线,最大距离为 0.1(您可能希望更改)。如果光线击中任何东西,那么角色必须在(或非常靠近)地板上,因此可能会跳跃。

最新更新