# Need help for an algorithm that use Physics2D.OverlapAreaAll

Hello good people. I encounter a problem using OverlapArea and i don’t know how can I fix it. The next image explains what i’m trying to do, and below is my code. THE PROBLEM is that sometimes for one or more “photons” the code part for OUT is not executed, is very rarely
but it happens. Maybe someone can give me a hand of help or how can i make this work fine.

``````        private Cell parentRef;
private int photonMask = (1 << 9);
private List<GameObject> arrPhotons;
private float maxDistance;
public void Init()
{
parentRef = transform.GetComponent<Cell>();
arrPhotons = new List<GameObject>();
maxDistance = parentRef.Size/DataStorage.PPU/2;
}

private void Update()
{
if(parentRef.Rank == Cell.EnumRank.Mother)
return;

//*** get the photons that are in the overlap area
Vector2 pA = new Vector2(transform.position.x - parentRef.Size/DataStorage.PPU/3, transform.position.y - parentRef.Size/DataStorage.PPU/3);
Vector2 pB = new Vector2(transform.position.x + parentRef.Size/DataStorage.PPU/3, transform.position.y + parentRef.Size/DataStorage.PPU/3);
Collider2D[] photons = Physics2D.OverlapAreaAll(pA, pB, photonMask);
if(photons.Length > 0)
{
Photon photon = photons[0].GetComponent<Photon>();
}

//*** OUT
for(int i=0; i < arrPhotons.Count; i++)
{
if((arrPhotons[i].transform.position - transform.position).magnitude >= maxDistance  arrPhotons[i].layer == 8)
{
//Debug.Log("out: " + arrPhotons[i].name);
arrPhotons[i].layer = 9;
arrPhotons.Remove(arrPhotons[i]);
}
}

//*** IN
if(photons.Length > 0)
{
Photon photon = photons[0].GetComponent<Photon>();
if((photon.transform.position - transform.position).magnitude < 0.02f)
{
photon.gameObject.layer = 8;
//Debug.Log("in: " + photon.name);
}
}
``````

First question I may ask is are you sure your Photons are not traveling at a rate of speed which could bypass the collider in question?

Basically as far as I can see, you are trying to capture a photon that has entered a field. Usually, you want to do a raycast or spherecast or whatever to see if the photon is going to hit an object before moving it, if it does, then you can do something there.

Is it in Unity 4.5? as a slew of Physics bugs were fixed in that version.

Yes, is unity 4.5 version.

Thanks, I will try this two methods, but one question before, this methods needs rigidbody?