UNITY - 无限跳跃

时间:2014-12-29 21:15:47

标签: unity3d unityscript

我在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);
    }


}

感谢您的帮助,

弗洛。

1 个答案:

答案 0 :(得分:0)

在添加导致他们向上移动的力之前,您没有检查角色是否在场上。此检查通常使用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(您可能希望更改)。如果射线击中任何东西,那么角色必须在地板上(或非常接近),因此可能会跳跃。

相关问题