gnxrly
gnxrly

Reputation: 1

How can I check if there is a collision between two Collider2D types in a specified area?

I'm experimenting with dungeon generation in Unity2D, I'm generating the rooms all on top of each other (with a slight offset), then moving them later with this code:

        foreach (GameObject room in rooms)
        {
            moveDirection = Vector3.zero;
            InCollision = Physics2D.OverlapBoxAll(room.transform.position, room.transform.localScale, roomlayer);
            if (InCollision.Length > 1)
            {
                foreach (Collider2D neighbor in InCollision)    
                    moveDirection += new Vector2(room.transform.position.x - neighbor.GetComponent<Transform>().position.x, room.transform.position.y - neighbor.GetComponent<Transform>().position.y).normalized;
            }
            room.transform.Translate(moveDirection.normalized * 100 * Time.deltaTime);
        }

This works as intended when I put it in the FixedUpdate() function, but I need to be able to do it in Start(). I can't figure it out however, because the Start() function only iterates once, which will definitely leave some rooms in collision. I've looked at several posts about this, but they're all talking about the OnTriggerEnter() function, which I don't think will work for me, since to my knowledge, the function only detects if something triggers the collider, not if it is currently in collision. So... I need a workaround to keep repeating the script above until there are no objects in collision with each other, I don't know if this is a dumb question and the answer is really obvious, my workflow has come to a halt due to this issue. Thank you in advance!

I figured I could use a while loop that keeps repeating the foreach loop above so long as there is a collision, but it kept crashing the Unity client, I later found out the Physics2D function i was using, OverlapBoxAll() doesn't actually detect for collisions within the area, but checks for any colliders inside said area, so it always returns a non-null array and the loop never ends, causing Unity to freeze. I've also tried using flags. I've used a boolean (set to false by default) as a condition for the while loop as long as it is false, and if a collision is detected, set it to true and the loop doesn't repeat after that. But this broke the whole thing and I am too lazy to try and find out why.

Upvotes: 0

Views: 54

Answers (1)

Soul
Soul

Reputation: 21

I can't figure it out however, because the Start() function only iterates once, which will definitely leave some rooms in collision.

I figured I could use a while loop that keeps repeating the foreach loop above so long as there is a collision, but it kept crashing the Unity client

Did you try corutines? https://docs.unity3d.com/Manual/Coroutines.html

Upvotes: 1

Related Questions