Verify that a player move wouldn't collide before doing it.

TODO: check rotations as well.
This commit is contained in:
Kaj Forney 2021-10-21 11:06:46 -06:00
parent c5228b3a69
commit 671c8d6f7c
Signed by: kforney
GPG key ID: 3AB4E2E04CEF656F

View file

@ -17,20 +17,29 @@ public class tetrominoUserControl : MonoBehaviour
{ {
if (Input.GetButtonDown("tetrisMoveLeft") && activeTetromino != null) if (Input.GetButtonDown("tetrisMoveLeft") && activeTetromino != null)
{ {
activeTetromino.gameObject.transform.position += Vector3.left * 1.0f; if (!checkMoveCollisions(Vector2.left))
GetComponent<AudioSource>().Play(); {
activeTetromino.gameObject.transform.position += Vector3.left * 1.0f;
GetComponent<AudioSource>().Play();
}
} }
if (Input.GetButtonDown("tetrisMoveRight") && activeTetromino != null) if (Input.GetButtonDown("tetrisMoveRight") && activeTetromino != null)
{ {
activeTetromino.gameObject.transform.position += Vector3.right * 1.0f; if (!checkMoveCollisions(Vector2.right))
GetComponent<AudioSource>().Play(); {
activeTetromino.gameObject.transform.position += Vector3.right * 1.0f;
GetComponent<AudioSource>().Play();
}
} }
if (Input.GetButtonDown("tetrisDrop") && activeTetromino != null) if (Input.GetButtonDown("tetrisDrop") && activeTetromino != null)
{ {
activeTetromino.gameObject.transform.position += Vector3.down * 1.0f; if (!checkMoveCollisions(Vector2.down))
GetComponent<AudioSource>().Play(); {
activeTetromino.gameObject.transform.position += Vector3.down * 1.0f;
GetComponent<AudioSource>().Play();
}
} }
if (Input.GetButtonDown("tetrisRotateLeft") && activeTetromino != null) if (Input.GetButtonDown("tetrisRotateLeft") && activeTetromino != null)
@ -55,4 +64,29 @@ public class tetrominoUserControl : MonoBehaviour
{ {
activeTetromino = null; activeTetromino = null;
} }
public bool checkMoveCollisions(Vector2 direction)
{
bool wouldCollide = false;
foreach (Transform child in activeTetromino.transform)
{
RaycastHit2D collision = Physics2D.Raycast(child.position, direction, 1.0f);
// Debug.DrawRay(pieceToCheck.position,Vector3.down,Color.red,1000.0f);
if (collision.collider != null && collision.collider.transform.parent != child.parent)
{
wouldCollide = true;
}
}
if (wouldCollide == true)
{
return true;
}
else
{
return false;
}
}
} }