using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; public class tetromino : MonoBehaviour { public float timeBetweenSteps; public bool active = true; private tetrominoUserControl TetrominoUserControl; private tetrominoSpawnManager TetrominoSpawnManager; private float stepTimer = 0.0f; private bool wouldCollide = false; // Start is called before the first frame update void Start() { TetrominoSpawnManager = FindObjectOfType(); TetrominoUserControl = FindObjectOfType(); TetrominoUserControl.setActiveTetromino(gameObject); } // Update is called once per frame void Update() { stepTimer += Time.deltaTime; if (stepTimer >= timeBetweenSteps && active) { stepTimer = stepTimer - timeBetweenSteps; nextStep(); } } void nextStep() { //I want to run this for each piece of the tetromino. foreach (Transform child in transform) { //Only do this if it's a piece at the bottom, so we don't detect ourself as a collision. if (Math.Abs(child.localPosition.y - (0.5)) < 0.001) //my IDE suggested I do this to fix floating-point comparison issues, and I see the logic at work here. { if (validateFall(child)) { wouldCollide = true; break; } } } if (wouldCollide == false) { Fall(); } else { active = false; TetrominoUserControl.unsetActiveTetromino(); TetrominoSpawnManager.spawnTetromino(); } } private bool validateFall(Transform pieceToCheck) //returns true if the next step collides with something { //Cast a ray to the next position of the tetromino. //NOTE: disabled "Queries Start in Colliders" in Project Settings>Physics 2D (thank you again, Tavi). RaycastHit2D collision = Physics2D.Raycast(pieceToCheck.position, Vector2.down, 1.0f); // Debug.DrawRay(pieceToCheck.position,Vector3.down,Color.red,1000.0f); if (collision.collider != null && collision.collider.name != pieceToCheck.name) { Debug.Log("Collided with object: " + collision.collider.name); //We hit something, but what? if (collision.collider.CompareTag("Ground") || collision.collider.CompareTag("Tetromino")) { ScoreCounter.scoreAmount += 100; return true; } return true; } return false; } void Fall() { transform.position += Vector3.down * 1.0f; } }