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

Unity子弹碰撞异常排查:击中玩家或触碰物体未按预期表现

游戏子弹碰撞异常问题

我和朋友在开发一款游戏的基础版本,遇到了子弹碰撞的两个异常:

  • 勾选子弹Box Collider的IsTrigger属性时,玩家移动中发射的子弹会击中玩家并直接消失
  • 不勾选IsTrigger时,子弹触碰环境后会停止移动,但不会自动销毁
  • 尝试添加碰撞忽略脚本解决,但问题依然存在

相关代码

Bullet脚本

using UnityEngine;

public class Bullet : MonoBehaviour
{
    public float speed = 20f;
    public Rigidbody2D rb;

    void Start()
    {
        rb.velocity = transform.right * speed;
    }

    void OnTriggerEnter2D(Collider2D hitInfo)
    {
        Debug.Log(hitInfo.name);
        Destroy(gameObject);
    }
}

Ignore脚本

using UnityEngine;
using System.Collections; 

public class ignore : MonoBehaviour
{
    public GameObject playercollision;
    public GameObject bulletcollision;

    void LateUpdate()
    {
        Physics2D.IgnoreCollision(playercollision.GetComponent<Collider2D>(), bulletcollision.GetComponent<Collider2D>());
    }
}

修复方案

1. 解决IsTrigger模式下击中玩家的问题

在OnTriggerEnter2D回调里判断碰撞对象是否为玩家,是则跳过销毁逻辑:

void OnTriggerEnter2D(Collider2D hitInfo)
{
    // 把"Player"改成你实际的玩家对象标签
    if (hitInfo.CompareTag("Player")) return;
    Debug.Log(hitInfo.name);
    Destroy(gameObject);
}

2. 解决非IsTrigger模式下子弹不销毁的问题

添加OnCollisionEnter2D回调处理物理碰撞,同样忽略玩家:

void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.collider.CompareTag("Player")) return;
    Debug.Log(collision.collider.name);
    Destroy(gameObject);
}

3. 废弃无效的Ignore脚本,改用生成时设置碰撞忽略

原Ignore脚本只能处理单个子弹对象,无法覆盖动态生成的所有子弹。建议在玩家的射击生成逻辑里直接设置忽略:

// 示例:玩家射击脚本中的生成代码
public GameObject bulletPrefab;

void Fire()
{
    GameObject bullet = Instantiate(bulletPrefab, transform.position, transform.rotation);
    // 忽略当前玩家和新生成子弹的碰撞
    Physics2D.IgnoreCollision(bullet.GetComponent<Collider2D>(), GetComponent<Collider2D>());
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 17:01:06