You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity 2D平台游戏中碰撞触发对象删除功能失效问题

2D平台游戏对象碰撞删除失效问题

我正在开发一款2D平台游戏,设置对象持续移动,当对象触碰到屏幕外带Delete标签的碰撞体时应被销毁,但对象直接穿过该区域未被删除。双方均带有Collider,待删除对象已设置对应标签。

碰撞体设置截图

相关代码

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

public class CollisionButterland : MonoBehaviour
{
    public Talking script;
    public GameObject pan;
    public bool Touching;
    public GameObject clone;
    public bool objectCreated = false;

    void Owie()
    {
        if (Touching == true)
        {
            script.Health -= 10;
            Debug.Log("Health decreased to " + script.Health);
        }
    }

    void Start()
    {
        InvokeRepeating("Owie", 0.5f, 0.5f);
        InvokeRepeating("TrialOne", 0.9f, 0.9f);
    }

    private void OnCollisionStay2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Delete"))
        {
            Destroy(collision.gameObject);
        }

        if (collision.gameObject.CompareTag("Player"))
        {
            Touching = true;
        }
    }

    private void OnCollisionExit2D(Collision2D other)
    {
        Touching = false;
    }

    void TrialOne()
    {
        if (script.trialone == true && !objectCreated)
        {
            clone = Instantiate(pan, new Vector3(10.16f, -2.44f, 0f), transform.rotation);
            clone.GetComponent<Rigidbody2D>().velocity = new Vector2(-5, clone.GetComponent<Rigidbody2D>().velocity.y);
            objectCreated = true;
        }
    }
}

问题排查与解决思路

  • 碰撞体类型匹配检查
    如果Delete标签碰撞体勾选了Is Trigger,OnCollisionStay2D不会触发,要么取消勾选该选项,要么把代码里的OnCollisionStay2D替换为OnTriggerStay2D,同时将参数改为Collider2D collision。
  • 脚本挂载位置修正
    若脚本挂在移动对象(克隆出的pan)上,当前代码会销毁Delete碰撞体而非目标对象,需把Destroy(collision.gameObject);改成Destroy(gameObject);;若脚本挂在Delete碰撞体上,要确保移动对象带有非静态的Rigidbody2D组件。
  • 碰撞矩阵验证
    打开Edit → Project Settings → Physics2D,检查移动对象所在层和Delete碰撞体所在层的碰撞规则,确保两者允许碰撞。
  • 高速穿透处理
    若对象移动速度过快,开启其Rigidbody2D的Continuous Collision Detection,将模式设为Continuous或Continuous Dynamic,避免物理引擎漏检碰撞。

内容的提问来源于stack exchange,提问作者user22411435

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 21:27:16