首页 > 解决方案 > OnTriggerEnter2D() 似乎无法统一

问题描述

我正在开发一个平台游戏,其中一个球应该能够左右移动和跳跃。我可以使角色成功跳跃或移动,但是当我尝试检查它是否在地面上时,通过创建一个元素作为角色的子元素,使用 2D 触发器对撞机,并使用应该的变量编写代码玩家接触地面时为真,不接触地面时为假,只是没有激活。

这是主要移动脚本的代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Grounded : MonoBehaviour
{
    GameObject Player;

    // Start is called before the first frame update
    void Start()
    {
        Player = gameObject.transform.parent.gameObject;
    }

    // Update is called once per frame
    void Update()
    {

    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (GetComponent<Collider2D>().tag == "Ground")
        {
            Player.GetComponent<Move2D>().isGrounded = true;
        }
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        if (GetComponent<Collider2D>().tag == "Ground")
        {
            Player.GetComponent<Move2D>().isGrounded = true;
        }
    }
}

这是接地脚本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Move2D : MonoBehaviour
{
    public float moveSpeed = 5f;
    public bool isGrounded = false;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        Jump();
        Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f, 0f);
        transform.position += movement * Time.deltaTime * moveSpeed;
    }

    void Jump()
    {
        if (Input.GetButtonDown("Jump") && isGrounded)
        {
            gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector3(0f, 5f), ForceMode2D.Impulse);
        }
    }
}

非常感谢任何帮助或信息。

标签: c#unity3d

解决方案


你能检查一下球和地面都有刚体吗?这是触发触发器所必需的。

*注意:仅当其中一个碰撞器还附加了刚体时才会发送触发事件。*

你也可以改变你的代码

private void OnTriggerEnter2D(Collider2D collision)
{
    if (GetComponent<Collider2D>().tag == "Ground")
    {
        Player.GetComponent<Move2D>().isGrounded = true;
    }
}


private void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.tag == "Ground")
    {
        Player.GetComponent<Move2D>().isGrounded = true;
    }
}

另外我还建议使用“层”而不是使用标签


推荐阅读