From 671c8d6f7c9a5e1e0c43ab600e0cf6fac7ee44b7 Mon Sep 17 00:00:00 2001 From: Kaj Forney Date: Thu, 21 Oct 2021 11:06:46 -0600 Subject: [PATCH] Verify that a player move wouldn't collide before doing it. TODO: check rotations as well. --- Assets/Scripts/tetrominoUserControl.cs | 46 ++++++++++++++++++++++---- 1 file changed, 40 insertions(+), 6 deletions(-) diff --git a/Assets/Scripts/tetrominoUserControl.cs b/Assets/Scripts/tetrominoUserControl.cs index bb9dcd1..edc5549 100644 --- a/Assets/Scripts/tetrominoUserControl.cs +++ b/Assets/Scripts/tetrominoUserControl.cs @@ -17,20 +17,29 @@ public class tetrominoUserControl : MonoBehaviour { if (Input.GetButtonDown("tetrisMoveLeft") && activeTetromino != null) { - activeTetromino.gameObject.transform.position += Vector3.left * 1.0f; - GetComponent().Play(); + if (!checkMoveCollisions(Vector2.left)) + { + activeTetromino.gameObject.transform.position += Vector3.left * 1.0f; + GetComponent().Play(); + } } if (Input.GetButtonDown("tetrisMoveRight") && activeTetromino != null) { - activeTetromino.gameObject.transform.position += Vector3.right * 1.0f; - GetComponent().Play(); + if (!checkMoveCollisions(Vector2.right)) + { + activeTetromino.gameObject.transform.position += Vector3.right * 1.0f; + GetComponent().Play(); + } } if (Input.GetButtonDown("tetrisDrop") && activeTetromino != null) { - activeTetromino.gameObject.transform.position += Vector3.down * 1.0f; - GetComponent().Play(); + if (!checkMoveCollisions(Vector2.down)) + { + activeTetromino.gameObject.transform.position += Vector3.down * 1.0f; + GetComponent().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; + } + } }