【问题标题】:Detect collision between player and ground Unity3D检测玩家和地面 Unity3D 之间的碰撞
【发布时间】:2016-03-28 15:40:42
【问题描述】:

我还在学习 Unity,现在我正在努力让我的玩家能够跳跃。当然,我不希望我的玩家能够永远跳下去,所以我的想法是只在玩家与地板物体接触时才启用跳跃。这是我到目前为止的代码:

public class PlayerController : NetworkBehaviour
{

    public float speed;             // Player movement speed
    private bool grounded = true;   // Contact with floor

    private Rigidbody rb;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    // Show a different color for local player to recognise its character
    public override void OnStartLocalPlayer()
    {
        GetComponent<MeshRenderer>().material.color = Color.red;
    }

    // Detect collision with floor
    void OnCollisionEnter(Collision hit)
    {
        if (hit.gameObject.tag == "Ground")
        {
            grounded = true;
        }
    }

    // Detect collision exit with floor
    void OnCollisionExit(Collision hit)
    {
        if (hit.gameObject.tag == "Ground")
        {
            grounded = false;
        }
    }

    void FixedUpdate()
    {
        // Make sure only local player can control the character
        if (!isLocalPlayer)
            return;

        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");

        Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);

        rb.AddForce(movement * speed);

        // Detect space key press and allow jump if collision with ground is true
        if (Input.GetKey("space") && grounded == true)
        {
            rb.AddForce(new Vector3(0, 1.0f, 0), ForceMode.Impulse);
        }
    }
}

但似乎OnCollisionEnterOnCollisionExit 永远不会触发。所以玩家仍然可以随时跳跃。我做错了吗?

编辑:似乎OnCollisionEnterOnCollisionExit 触发得非常好。只是 if 语句返回 false。我不知道为什么。

if (GameObject.Find("Ground") != null) 返回 true。

编辑 2:奇怪的是,这两个都返回 Untagged

Debug.Log(hit.gameObject.tag);
Debug.Log(hit.collider.tag);

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    请提供更多信息

    1. 请告诉我您使用的是哪个版本的 unity?
    2. 您是否已将项目更新为其他最新版本的 unity?
    3. 同时提供您的“标签”数组的屏幕截图。

    【讨论】:

    • 原来我把对象名称和对象标签搞混了。地面对象真的根本没有标签。我已经添加了那个标签,一切都很完美!我正要自己回答,但我会接受你的:)
    • 谢谢。祝您的项目一切顺利
    猜你喜欢
    • 2022-01-28
    • 2016-02-17
    • 1970-01-01
    • 1970-01-01
    • 2019-04-20
    • 2013-05-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-07
    相关资源
    最近更新 更多