using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class tetrominoUserControl : MonoBehaviour { public GameObject activeTetromino; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { if (Input.GetButtonDown("tetrisMoveLeft") && activeTetromino != null) { if (!checkMoveCollisions(Vector2.left)) { activeTetromino.gameObject.transform.position += Vector3.left * 1.0f; GetComponent().Play(); } } if (Input.GetButtonDown("tetrisMoveRight") && activeTetromino != null) { if (!checkMoveCollisions(Vector2.right)) { activeTetromino.gameObject.transform.position += Vector3.right * 1.0f; GetComponent().Play(); } } if (Input.GetButtonDown("tetrisDrop") && activeTetromino != null) { if (!checkMoveCollisions(Vector2.down)) { activeTetromino.gameObject.transform.position += Vector3.down * 1.0f; GetComponent().Play(); } } if (Input.GetButtonDown("tetrisRotateLeft") && activeTetromino != null) { rotateWithChecks(90); // activeTetromino.gameObject.transform.Rotate(0,0,90,Space.World); GetComponent().Play(); } if (Input.GetButtonDown("tetrisRotateRight") && activeTetromino != null) { rotateWithChecks(90); // activeTetromino.gameObject.transform.Rotate(0,0,-90,Space.World); GetComponent().Play(); } if (Input.GetButtonDown("Quit")) { SceneManager.LoadScene("titleScreen"); } } public void setActiveTetromino(GameObject tetromino) { activeTetromino = tetromino; } public void unsetActiveTetromino() { 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); if (collision.collider != null && collision.collider.transform.parent != child.parent) { wouldCollide = true; } } if (wouldCollide == true) { return true; } else { 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().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); } } }