How to check if gameObject is interact with multiple colliders
I am making a 2D game, where player can put down buildings in a map. Obviously I do not want those buildings to be built on another one, so I added a blocked parameter to the builder gameobject. OnTriggerEnter/Exit not work correctly if there are multiple buildings on the board, and the blocker parameter becomes true if it exits one collider even if it's inside another one. For this I put an OnTriggerStay method on the blocker script, so if it the builder leaves one Collider, the OnTriggerStay overwrites the others Exit, but sometimes the color is flashing when it's leaving one collider and stays in another. When it leaves the first black box, but it's still blocked by the second one: Any better idea how to handle this?
public void OnTriggerEnter2D(Collider2D collision)
{
Color tmp = collision.gameObject.GetComponentInChildren<SpriteRenderer>().color;
tmp = Color.red;
collision.blocked = true;
collision.gameObject.GetComponentInChildren<SpriteRenderer>().color = tmp;
}
}
public void OnTriggerStay2D(Collider2D collision)
{
Color tmp = collision.gameObject.GetComponentInChildren<SpriteRenderer>().color;
tmp = Color.red;
collision.blocked = true;
collision.gameObject.GetComponentInChildren<SpriteRenderer>().color = tmp;
}
}
private void OnTriggerExit2D(Collider2D collision)
{
Color tmp = collision.gameObject.GetComponentInChildren<SpriteRenderer>().color;
tmp = Color.green;
collision.blocked = false;
collision.gameObject.GetComponentInChildren<SpriteRenderer>().color = tmp;
}
}
Thank you!
Answer by tormentoarmagedoom · Jan 15, 2019 at 09:02 AM
Good day. First, i supose its a copy/paste, but there is a " } " that does nothing
I normally combine the OnTriggerStay with the VEctor3.Distance function, (so no need OnTrigger Eneter/Exit ... The only posiblitity to allow building is something like this:
public void OnTriggerStay2D(Collider2D collision)
{
if (Collider2D.tag =="Building" || INSERT ALL TAGS OF ALL OBJECTS THAT BLOCK BUILDING)
{
if (Vector3.Distance(collision.gameObject.transform.position, transform.position) > 10)
{
You can build.
}
{
}
Bye!