After Rotating a Prefab, Transform.Position of children is inaccurate
I am creating a Tetris clone for practice and each Tetromino is a prefab created of four tile children, each with a sprite and a 2D Collider forming a composite collider.
When rotating a piece, I use the below C# code:
activePiece.transform.rotation = activePiece.transform.rotation * Quaternion.Euler(0, 0, 90);
After a row is filled, I step through each space on the line and find all the child objects whose position is on the line, disabling their hitbox and sprite:
GameObject[] objectsList = GameObject.FindGameObjectsWithTag("Tile"); //All Children of Game Pieces
for (int i = 0; i < lines.Count(); i++)
{
//Remove Line Tiles
for (float x = -5; x < 5; x++)
{
foreach (GameObject tile in objectsList)
{
if (tile.transform.position.Equals(new Vector2(x + 0.5f, lines[i] + 0.5f)))
{
tile.GetComponent<SpriteRenderer>().enabled = false;
tile.GetComponent<BoxCollider2D>().enabled = false;
}
}
}
}
This works for any pieces that have not been rotated, but when taking the tile.transform.position of any piece that has been rotated, the value is relative to their parent's rotated position instead of their own position on the grid. I get results like the below, where the pieces that haven't been disabled are ones that have been rotated:
How can I check the tiles for their accurate position on the line?
Answer by DrBrief · Mar 28 at 07:08 PM
Figured it out with help from friendly people on Discord who pointed out that my float comparison is using Equals. I swapped it out for:
foreach (GameObject tile in objectsList)
{
float fx = tile.transform.position.x;
float fy = tile.transform.position.y;
if (Mathf.Approximately((x + 0.5f), fx) && Mathf.Approximately((lines[i] + 0.5f), fy))
{
tile.GetComponent<SpriteRenderer>().enabled = false;
tile.GetComponent<BoxCollider2D>().enabled = false;
}
}
}