How to Ignore Collision between Objects

ぐ巨炮叔叔 提交于 2019-11-27 19:40:37

问题


1.I have written an script that uses ontriggerenter to find when a cannon ball hits another ship in a 2D game.

private void OnTriggerEnter(Collider other)
{


    if (other.tag != "cannonBallWASD" )
    {
        return;
    }

    Destroy(other.gameObject);
    Destroy(gameObject);
    Debug.Log(other);
}

2.The Ship that is controlled using WASD(ShipWASD) fires a cannonball(cannonballWASD) at a 2nd ship controlled using the arrow keys(ShipArrows). This code is on a script attached to ShipArrows.

3.I have a seperate bit of code in place which uses a cube without a mesh renderer(The Boundary) which destroys any cannonballs that leave the boundary so it looks like they are falling into the sea. This is a 2-PLAYER GAME.

4.Here in lies the problem- So that the Boundary moves around with the ship it is a CHILD of the ShipArrows. When I fire the cannon the cannonball hits the boundary instead of the ships collider. When i remove the boundary it hits the ship as it should but the boundary is something i want.

5.The boundary and the ship both have and need Is Trigger Colliders on them. Is there any way to ignore the boundary in this script but not ignore it in the following script.

private void OnTriggerExit(Collider other)
{
    if(other.tag != "cannonBallWASD" && other.tag != "cannonBallArrows")
    {
        return;
    }
    Destroy(other.gameObject);
}

This script makes ShipArrows cannonBalls look like they are falling in the sea by destroying them when they leave ShipArrows Boundary. (Both ships do this.)


回答1:


To ignore collision, use Physics.IgnoreCollision.

There is also Physics.IgnoreLayerCollision which is used to ignore collisions on layers.

Just put all the Objects you want to ignore in a layer then invoke the function to ignore layers on them.

Ignore Collison 3D:

Physics.IgnoreCollision(yourFirstCollider, yourSecondCollider, true)

or

Physics.IgnoreLayerCollision(yourFirstLayer, yourOtherLayer, true);

Reset/Recognize Collison 2D:

Physics2D.IgnoreCollision(yourFirstCollider, yourSecondCollider, false);

or

Physics2D.IgnoreLayerCollision(yourFirstLayer, yourOtherLayer, false)

Both layers do not have to be the-same. You can ignore collision on Objects from different layers. This can also be accomplished through the Editor without code by assigning each GameObject layer and going to Edit --> Project Settings --> Physics --> or Edit --> Project Settings --> Physics 2D then configure which layers should collide with one another from there.



来源:https://stackoverflow.com/questions/43396091/how-to-ignore-collision-between-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!