Search code examples
c#unity-game-enginespriteunityscriptunity3d-2dtools

Detect complete overlap of GameObject of Sprite


So I've got a prefab which I am instantiating from the resources folder randomly in random places as follows, and is just an image with a Sprite Renderer attached to it at the moment:

go = (GameObject)Instantiate(Resources.Load("alienPink")); 

These are instantiated at different locations after every 3 seconds.

I also have a ball with a Sprite Renderer, Circle Collider 2d and a Rigid Body 2D attached to it and i get access to the RigidBody 2D as follows:

//ray cast from camera to mouse point to detect hit

RaycastHit2D hit = Physics2D.Raycast(mousePos2D , dir);

. . .

RigidBody2D grabbedObject = hit.collider.rigidbody2D;

//do stuff with grabbedObject including change position

I want to detect when the prefab is COMPLETELY overlapped by the ball which is transparent so I can start doing stuff to the prefab. COMPLETE is the keyword over here and I've tried numerous methods including trying to detect an overlap between the Renderer of prefab and the ball's rigidBody2D to no avail. I've even tried grabbing all the prefabs in scene, getting them into an array and detecting overlaps by going through all of the array in every single update but it just doesn't work:

GameObject[] prefab =GameObject.FindGameObjectsWithTag("enemies");  //returns GameObject[]

SOMEBODY HALP! Seriously I've been trying to do this for days now.

Thank you.


Solution

  • Try using Physics2D.OverlapCircle to detect overlaps. Another option worth checking out is: Physics2D.OverlapArea. If these two options only provides a partial solution, try using Physics2D.OverlapPoint by checking multiple points so that each point is required to be overlapped; for example, if the ball is to be completely inside a square check for the overlapping of four points within that square.