Ways to detect 2D collision other than OnCollisionEnter2D

后端 未结 2 1605
执念已碎
执念已碎 2020-12-07 06:31

This might come off as a stupid question, but in an if statement, is it possible to check if the object is currently colliding with another object?

Here is what I ha

相关标签:
2条回答
  • 2020-12-07 07:03

    Maybe what you are looking for is the OnCollisionStay method, this one will fire as long as they are touching each other.

    There is some more info in the link here: https://docs.unity3d.com/ScriptReference/Collider2D.OnCollisionStay2D.html

    0 讨论(0)
  • 2020-12-07 07:17

    Are there different solutions than OnCollisionEnter2D

    Yes. Many of them!

    CircleCollider2D, other 2D colliders and its base class Collision2D, have built in functions to do this.

    public bool IsTouching(Collider2D collider); //Check collision by the provided collider
    public bool IsTouchingLayers(); //Check collision by any collision
    public bool IsTouchingLayers(int layerMask); //Check collision by layer
    public bool OverlapPoint(Vector2 point); //Check collision by position
    

    The first function is more appropriate for this.

    Simple Example:

    Collision2D collider1;
    Collision2D collider2;
    
    void Update()
    {
        //Checks if collider1 is touching with collider2
        if (collider1.collider.IsTouching(collider2.collider))
        {
    
        }
    }
    

    Example with the OnCollisionEnter2D function:

    public CircleCollider2D myCircleCollider;
    
    void OnCollisionEnter2D(Collision2D c)
    {
        if (c.collider.IsTouching(myCircleCollider))
        {
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题