Implement rotation collision check.

This commit is contained in:
Kaj Forney 2021-10-28 17:08:26 -06:00
parent 3046a9f72e
commit 106fb35f46
No known key found for this signature in database
GPG key ID: 32E055243F4B293B

View file

@ -45,13 +45,15 @@ public class tetrominoUserControl : MonoBehaviour
if (Input.GetButtonDown("tetrisRotateLeft") && activeTetromino != null)
{
activeTetromino.gameObject.transform.Rotate(0,0,90,Space.World);
rotateWithChecks(90);
// activeTetromino.gameObject.transform.Rotate(0,0,90,Space.World);
GetComponent<AudioSource>().Play();
}
if (Input.GetButtonDown("tetrisRotateRight") && activeTetromino != null)
{
activeTetromino.gameObject.transform.Rotate(0,0,-90,Space.World);
rotateWithChecks(90);
// activeTetromino.gameObject.transform.Rotate(0,0,-90,Space.World);
GetComponent<AudioSource>().Play();
}
@ -94,4 +96,41 @@ public class tetrominoUserControl : MonoBehaviour
return false;
}
}
public void rotateWithChecks(int degrees)
{
bool wouldCollide = false;
Collider2D[] results = new Collider2D[10];
//Perform the rotation (will undo later if there's a collision).
activeTetromino.gameObject.transform.Rotate(0,0,degrees,Space.World);
foreach (Transform child in activeTetromino.transform)
{
//Store any overlapping colliders in the results array.
child.GetComponent<BoxCollider2D>().OverlapCollider(new ContactFilter2D().NoFilter(), results);
//If there are collisions...
if (results.Length != 0)
{
foreach (Collider2D a in results)
{
//and IF they aren't an extra null item in the array...
if (a != null)
{
//Only act if the overlap is not with another part of this tetromino.
if (a.gameObject.transform.parent != child.parent)
{
Debug.Log("Collision detected with " + a.gameObject.name);
wouldCollide = true;
}
}
}
}
}
//If we collided, undo the rotation.
if (wouldCollide == true)
{
activeTetromino.gameObject.transform.Rotate(0,0,degrees * -1,Space.World);
}
}
}