To address the boundary issues when rotating tetrominoes in your Tetris-like game, it's essential to ensure that the entire tetromino remains within the grid boundaries after any rotation. The current implementation only checks the x position of the tetromino's transform, which isn't sufficient because tetrominoes consist of multiple blocks that can individually exceed boundaries after rotation.
Here's a comprehensive approach to fix the boundary system:
-
Check All Child Blocks After Rotation:
- After rotating the tetromino, verify that each individual block (child) remains within the grid boundaries.
- If any block exceeds the boundaries, revert the rotation to maintain the tetromino within the playable area.
-
Implement an IsValidPosition Method:
- This method will iterate through all child blocks of the current tetromino and ensure they are within the defined grid limits.
-
Adjust Rotation Logic:
- Modify the
RotateTetra method to incorporate boundary checks using the IsValidPosition method.
Step-by-Step Implementation
-
Define the Grid Boundaries:
Ensure you have clear definitions for your grid limits. Based on your existing variables:
private float k_minus = -4.5f; // Left boundary
private float k = 4.5f; // Right boundary
private float j = -6.5f; // Bottom boundary (adjust as needed)
-
Implement the IsValidPosition Method:
This method checks whether each block of the tetromino is within the grid boundaries.
bool IsValidPosition()
{
foreach (Transform block in currentTetra.transform)
{
Vector2 blockPos = block.position;
// Check horizontal boundaries
if (blockPos.x < k_minus || blockPos.x > k)
{
return false;
}
// Check vertical boundaries (assuming `j` is the bottom limit)
if (blockPos.y < j)
{
return false;
}
}
return true;
}
-
Modify the RotateTetra Method:
Update the rotation logic to use the IsValidPosition method. If the rotation causes any block to go out of bounds, revert the rotation.
void RotateTetra()
{
// Rotate the tetromino
currentTetra.transform.Rotate(0, 0, rotationAngle);
// Check if the new rotation is valid
if (!IsValidPosition())
{
// Revert rotation if invalid
currentTetra.transform.Rotate(0, 0, -rotationAngle);
}
}
-
Optional: Implement Wall Kicks for Better Rotation Handling:
Wall kicks allow the tetromino to adjust its position slightly when a rotation would otherwise cause it to go out of bounds. This makes the rotation feel smoother and more natural.
Here's a basic implementation:
void RotateTetra()
{
// Define possible wall kick offsets
Vector2[] wallKicks = new Vector2[]
{
new Vector2(1, 0),
new Vector2(-1, 0),
new Vector2(0, 1),
new Vector2(0, -1)
};
// Rotate the tetromino
currentTetra.transform.Rotate(0, 0, rotationAngle);
// If invalid, try wall kicks
if (!IsValidPosition())
{
foreach (Vector2 kick in wallKicks)
{
currentTetra.transform.position += (Vector3)kick;
if (IsValidPosition())
{
return; // Successful wall kick
}
// Revert the kick if it doesn't work
currentTetra.transform.position -= (Vector3)kick;
}
// Revert rotation if all wall kicks fail
currentTetra.transform.Rotate(0, 0, -rotationAngle);
}
}
Note: The wall kick offsets can be adjusted based on your grid size and game mechanics. This is a simplistic implementation to get you started.
-
Ensure Children Blocks Are Properly Positioned:
Make sure each tetromino prefab consists of child blocks positioned relative to the parent. This ensures that when the parent tetromino rotates, all child blocks rotate accordingly and their positions accurately reflect their placement on the grid.
-
Adjust Spawning Logic if Necessary:
Ensure that when new tetrominoes spawn, they do so within the grid boundaries. Adjust the spawn x and y positions if tetrominoes are appearing outside the playable area.
Final Revised Script
Here's the updated script incorporating the above changes:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TetraManagerScript : MonoBehaviour
{
public GameObject[] Tetras;
private GameObject currentTetra;
private float x;
private float y = 9.5f;
private float j;
private float k;
private float k_minus;
public static int grid_x = 1;
public static int grid_y = 1;
private int grid_width = 10;
private int grid_height = 20;
private int TetraToSpawn;
private float fallSpeed = 1f;
[SerializeField] private float fallTime;
private float rotationAngle = 90f;
// Define grid boundaries
private float leftBoundary = -4.5f;
private float rightBoundary = 4.5f;
private float bottomBoundary = -6.5f; // Adjust based on your grid
void Start()
{
SpawnTetras();
fallTime = Time.time + fallSpeed;
}
void Update()
{
TetraMove();
AutoFall();
}
void SpawnTetras()
{
if (Tetras != null && Tetras.Length > 0)
{
TetraToSpawn = Random.Range(0, Tetras.Length);
switch (TetraToSpawn)
{
case 0:
x = 0.5f;
j = -6.5f;
k_minus = -4.5f;
k = 4.5f;
break;
case 1:
case 2:
case 4:
x = 0.5f;
j = -7.5f;
k_minus = -4.5f;
k = 3.5f;
break;
default:
x = -0.5f;
j = -8.5f;
k_minus = -4.5f;
k = 3.5f;
break;
}
currentTetra = Instantiate(Tetras[TetraToSpawn], new Vector3(x, y, 0), Quaternion.identity);
}
}
void TetraMove()
{
if (currentTetra == null) return;
float xPos = currentTetra.transform.position.x;
float yPos = currentTetra.transform.position.y;
if (Input.GetKeyDown(KeyCode.A) && xPos > leftBoundary)
{
currentTetra.transform.position += Vector3.left * grid_x;
if (!IsValidPosition())
{
currentTetra.transform.position -= Vector3.left * grid_x; // Revert if invalid
}
}
if (Input.GetKeyDown(KeyCode.D) && xPos < rightBoundary)
{
currentTetra.transform.position += Vector3.right * grid_x;
if (!IsValidPosition())
{
currentTetra.transform.position -= Vector3.right * grid_x; // Revert if invalid
}
}
if (Input.GetKeyDown(KeyCode.S) && yPos > j)
{
currentTetra.transform.position += Vector3.down * grid_y;
if (!IsValidPosition())
{
currentTetra.transform.position -= Vector3.down * grid_y; // Revert if invalid
}
}
if (Input.GetKeyDown(KeyCode.X))
{
RotateTetra();
}
}
void AutoFall()
{
if (currentTetra == null) return;
float yPos = currentTetra.transform.position.y;
if (Time.time >= fallTime && yPos > j)
{
currentTetra.transform.position += Vector3.down * grid_y;
if (!IsValidPosition())
{
currentTetra.transform.position -= Vector3.down * grid_y;
// Here you might want to lock the tetromino and spawn a new one
// Lock tetromino logic goes here
// SpawnTetras();
}
fallTime = Time.time + fallSpeed;
}
}
void RotateTetra()
{
if (currentTetra == null) return;
// Rotate the tetromino
currentTetra.transform.Rotate(0, 0, rotationAngle);
// Check if the new rotation is valid
if (!IsValidPosition())
{
// Define possible wall kick offsets
Vector2[] wallKicks = new Vector2[]
{
new Vector2(1, 0),
new Vector2(-1, 0),
new Vector2(0, 1),
new Vector2(0, -1)
};
bool kicked = false;
foreach (Vector2 kick in wallKicks)
{
currentTetra.transform.position += (Vector3)kick;
if (IsValidPosition())
{
kicked = true;
break;
}
// Revert the kick if it doesn't work
currentTetra.transform.position -= (Vector3)kick;
}
if (!kicked)
{
// Revert rotation if all wall kicks fail
currentTetra.transform.Rotate(0, 0, -rotationAngle);
}
}
}
bool IsValidPosition()
{
foreach (Transform block in currentTetra.transform)
{
Vector2 pos = block.position;
// Check horizontal boundaries
if (pos.x < leftBoundary || pos.x > rightBoundary)
{
return false;
}
// Check vertical boundaries
if (pos.y < bottomBoundary)
{
return false;
}
// Optionally, check for collisions with other locked blocks here
// Example:
// if (IsOccupied(pos))
// {
// return false;
// }
}
return true;
}
// Optional: Implement collision detection with locked blocks
// bool IsOccupied(Vector2 position)
// {
// // Implement your collision logic here
// }
}
Additional Recommendations
-
Implement a Grid System:
- For more robust collision and boundary handling, consider implementing a grid-based system where each grid cell tracks whether it's occupied.
- This will help in managing locked tetrominoes and preventing overlapping.
-
Handle Locked Tetrominoes:
- When a tetromino can no longer move down, lock it into place and check for any complete lines to clear.
-
Improve Movement Smoothness:
- Instead of moving tetrominoes by fixed grid steps instantly, consider using smooth transitions for better visual appeal.
-
Enhance Rotation Mechanics:
- Explore more advanced rotation systems like the Super Rotation System (SRS) used in modern Tetris games for better rotation handling and wall kicks.
-
Debugging:
- Use
Debug.Log statements or Unity's Gizmos to visualize tetromino positions and boundaries during development.
By implementing these changes, your tetrominoes should remain within the grid boundaries during rotations and movements, providing a smoother and more reliable gameplay experience.