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

Unity开发问题:玩家与Point碰撞时如何销毁而非触发反弹?

问题:玩家碰撞Point时反弹,无法销毁目标

我正在开发一款空中射击游戏,玩家可通过碰撞收集Point,但目前碰撞后玩家会直接反弹,无法实现销毁Point的效果。相关脚本如下:

PointCollection脚本

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

public class PointColliection : MonoBehaviour
{
     
    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.CompareTag("Point"))
        {
            Destroy(other.gameObject);
        }
    } 
}

Player脚本

using UnityEngine;

public class Player : MonoBehaviour
{
    [HideInInspector] 
        public Rigidbody2D rb;
    [HideInInspector]
        public CircleCollider2D col;

    [HideInInspector] public Vector3 pos { get { return transform.position; } }

    void Awake ()
    {
        rb = GetComponent<Rigidbody2D> ();
        col = GetComponent<CircleCollider2D> ();
    }

    public void Push (Vector2 force)
    {
        rb.AddForce (force, ForceMode2D.Impulse);
    }

    public void ActivateRb ()
    {
        rb.isKinematic = false;
    }

    public void DesactivateRb ()
    {
        rb.velocity = Vector3.zero;
        rb.angularVelocity = 0f;
        rb.isKinematic = true;
    }
}

解决方案

核心原因

反弹是因为Player和Point的Collider2D都处于物理碰撞模式(未勾选Is Trigger),导致Rigidbody2D触发物理反弹;而你的PointCollection脚本依赖OnTriggerEnter2D事件,该事件仅在至少一个Collider2D设置为触发器时才会触发。

具体修复步骤

  1. 设置Point的Collider为触发器
    选中场景中的Point对象,在Inspector面板找到它的Collider2D组件,勾选Is Trigger选项。这样物理引擎不会处理两者的碰撞反弹,只会触发触发器事件。

  2. 检查Point的Rigidbody2D(如果有)
    如果Point对象挂载了Rigidbody2D,将其设置为Kinematic(勾选Is Kinematic),避免物理引擎对Point产生额外力影响;如果不需要物理效果,直接移除Rigidbody2D组件即可。

  3. 验证标签与脚本挂载

    • 确认Point对象的标签设置为Point
    • 确保PointCollection脚本正确挂载在Player对象上(因为脚本监听的是Player的触发器事件)

可选优化:碰撞事件替代触发器

如果需要保留Player的物理碰撞(比如和敌人碰撞),也可以改用OnCollisionEnter2D事件替代OnTriggerEnter2D,同时在碰撞时关闭Point的碰撞体避免反弹:

修改后的PointCollection脚本:

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

public class PointColliection : MonoBehaviour
{
    private void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.CompareTag("Point"))
        {
            // 先关闭Point的碰撞体,避免反弹
            other.gameObject.GetComponent<Collider2D>().enabled = false;
            Destroy(other.gameObject);
        }
    } 
}

这种方式不需要将任何Collider设为触发器,但需要确保Point的Collider2D在销毁前被禁用,防止物理反弹产生。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 09:13:10