【问题标题】:UNITY - Infinite JumpUNITY - 无限跳跃
【发布时间】:2014-12-30 08:08:48
【问题描述】:

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


}

感谢您的帮助,

弗洛。

【问题讨论】:

  • 我不确定它是否会永远飞下去?您是否启用了rigidbody.useGravity(或rigidbody2d 重力比例不为零)?
  • 请注意目前“jump”和“z”键的行为有所不同。当“jump”被按下时,即使“jump”被按下,Jump() 也会执行一次。按住 z 键时,每帧都会执行 Jump(),直到键被释放。如果您希望两者都有类似的行为,您可以使用 Input.GetKeyDown("z")。

标签: unity3d unityscript


【解决方案1】:

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

【讨论】:

  • 可能是因为本例中“void FixedUpdate()”中用到了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-23
  • 1970-01-01
相关资源
最近更新 更多