简体   繁体   English

Unity 让一个 object 通过另一个 object 但仍然触发碰撞

[英]Unity getting an object to pass through another object but still trigger collision

basicaly i need an object to be able to pass through an object just like as if it was a trigger, but still detect it as a colision becouse of the way i made hitting enemies work (or a way to get physics2d.overlapboxall to detect triggers), here is the code for my weapon attack and the enemy i need to pass through the player but also do damage to the player.基本上我需要一个 object 能够像它是一个触发器一样通过一个 object ,但由于我让击中敌人工作的方式(或一种让physics2d.overlapboxall 检测触发器的方式)仍然将它检测为colision ),这是我的武器攻击代码和我需要穿过玩家但也会对玩家造成伤害的敌人。

 if (AttackDelay <= 0)
            { //attacking
                Collider2D[] EnemiesToDmg = Physics2D.OverlapBoxAll(AttackPos.position,new Vector2(AttackRangeX,AttackRangeY),0, WhatIsEnemy);
                for (int i = 0; i < EnemiesToDmg.Length; i++)
                {EnemiesToDmg[i].GetComponent<Health>().takeDamage(AttackDamage);}

and for the enemy并为敌人



    void FixedUpdate()
    {


        RotateAndMove(target2);
        if (AttackRecharge<=AttackRechargeMax)
        {
            AttackRecharge += Time.deltaTime;
        }


    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if(collision.gameObject.layer==10)
        {
            player.gameObject.GetComponent<Health>().takeDamage(20);
        }
        if(collision.gameObject.transform==target2)
        {


           if (!IsVisible)
            {
                 target2.position = player.position + (player.position - transform.position) / 5;
            }
           else
            {
                TeleportToCamera(target2);
            }

        }


    }

As mentioned in the comments this is exactly what isTrigger is for.正如评论中提到的,这正是isTrigger的用途。
You can change this in code like this:您可以像这样在代码中更改它:

Collider.isTrigger = true;

Or in the editor with this tickbox:或在带有此复选框的编辑器中:
在此处输入图像描述

This will allow you to use code such as OnTriggerEnter and will make your game object be able to be passed through这将允许您使用诸如OnTriggerEnter类的代码,并使您的游戏 object 能够通过

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM