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)
{
activeTetromino.gameObject.transform.position += Vector3.left * 1.0f;
GetComponent<AudioSource>().Play();
if (!checkMoveCollisions(Vector2.left))
{
activeTetromino.gameObject.transform.position += Vector3.left * 1.0f;
GetComponent<AudioSource>().Play();
}
}
if (Input.GetButtonDown("tetrisMoveRight") && activeTetromino != null)
{
activeTetromino.gameObject.transform.position += Vector3.right * 1.0f;
GetComponent<AudioSource>().Play();
if (!checkMoveCollisions(Vector2.right))
{
activeTetromino.gameObject.transform.position += Vector3.right * 1.0f;
GetComponent<AudioSource>().Play();
}
}
if (Input.GetButtonDown("tetrisDrop") && activeTetromino != null)
{
activeTetromino.gameObject.transform.position += Vector3.down * 1.0f;
GetComponent<AudioSource>().Play();
if (!checkMoveCollisions(Vector2.down))
{
activeTetromino.gameObject.transform.position += Vector3.down * 1.0f;
GetComponent<AudioSource>().Play();
}
}
if (Input.GetButtonDown("tetrisRotateLeft") && activeTetromino != null)
@ -55,4 +64,29 @@ public class tetrominoUserControl : MonoBehaviour
{
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;
}
}
}