- Home /
Trigger collision with multiple objects suddenly becomes unreliable.
The game I'm working on right now has a cursor that's made out of multiple blocks tied together. The basic idea being that you can switch between different cursor shapes in order to clear out an area.
I'm using collision triggers to detect if any part is over a tile to clear out, and that works perfectly when it's just one piece. But if there's any more than one, sometimes it just doesn't trigger for some of them. It seems very random, sometimes all the pieces hit no problem, and then suddenly one or two of them don't work.
Here's most of the code of the individual pieces (which are instantiated by the main cursor object)
private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "tile")
{
tile = other.gameObject;
}
}
void OnTriggerExit2D(Collider2D other)
{
if (other.tag == "tile")
{
tile = null;
}
}
// Update is called once per frame
void Update()
{
//sets position relative to mouse and follows it
float spriteSize = 0.64f;
float parentPosx = Mathf.RoundToInt(transform.parent.position.x / spriteSize) * spriteSize;
float parentPosy = Mathf.RoundToInt(transform.parent.position.y / spriteSize) * spriteSize;
transform.position = new Vector2(parentPosx + xOffset, parentPosy + yOffset);
//prevents cursor from going too far left
if(transform.position.x < -4.48f + xOffset)
{
transform.position = new Vector2(-4.48f + xOffset, transform.position.y);
}
if (Input.GetMouseButtonDown(0) && tile != null)
{
Destroy(tile);
}
}
Answer by blinkafrootable · Jul 25, 2019 at 05:18 AM
Is it possible that your cursor collides with multiple tiles before the Update function is called causing tiles to override others leading to the deletion of only some of the tiles? I suggest setting tile = other.gameObject
in OnTriggerStay2D as well to make sure that every tile is accounted for. I hope that solves the problem.