Untitled conversation
- Usercode
- Assistant
using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;
using TMPro;
using UnityEngine.UI;
public class TetrisBlock : MonoBehaviour
{
public static bool isLineClearAnimationInProgress = false;
public float lineClearAnimationDuration = 1f;
public float fallTimeDecrease = 0.2f;
public float minFallTime = 0.01f;
public static int LinesCleared;
public static int height = 21;
public TMP_Text Lines_Cleared;
public int linesPerLevel = 10;
public Vector3 rotationPoint;
public float fallTime = 0.8f;
public static int width = 10;
public bool gameOver = false;
[SerializeField] private Animator myAnimationController;
private static Transform[,] grid = new Transform[width, height];
private float initialFallTime = 0.8f;
private GameManager gameManager;
private int previousLevel = 0;
private GameObject startMenu;
private float previousTime;
private int level = 0;
private SpawnTetromino spawnTetromino;
private static int linesClearingCount = 0;
[SerializeField] private Animator blockAnimator;
[SerializeField] private string lineClearAnimationTrigger = "LineClear";
void ResetGame()
{
if (SceneController.hasRestartedScene)
{
startMenu.SetActive(false);
fallTime = initialFallTime;
level = 0;
LinesCleared = 0;
linesClearingCount = 0;
UpdateUi();
SceneController.hasRestartedScene = false;
Debug.Log($"Scene Has restarted, hasRestartedScene: {SceneController.hasRestartedScene}, fallTime: {fallTime}");
}
}
void Update()
{
if (startMenu != null && !startMenu.activeSelf)
{
LevelUp();
InputHandler();
}
}
void InputHandler()
{
if(Input.GetKeyDown(KeyCode.LeftArrow) || Input.GetKeyDown(KeyCode.A))
{
transform.position += new Vector3(-1, 0, 0);
if(!ValidMove())
transform.position -= new Vector3(-1, 0, 0);
}
else if (Input.GetKeyDown(KeyCode.RightArrow) || Input.GetKeyDown(KeyCode.D))
{
transform.position += new Vector3(1, 0, 0);
if (!ValidMove())
transform.position -= new Vector3(1, 0, 0);
}
else if (Input.GetKeyDown(KeyCode.X))
{
transform.RotateAround(transform.TransformPoint(rotationPoint), new Vector3(0,0,1), 90);
if (!ValidMove())
transform.RotateAround(transform.TransformPoint(rotationPoint), new Vector3(0, 0, 1), -90);
}
if (Time.time - previousTime > (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.S) ? fallTime / 10 : fallTime))
{
transform.position += new Vector3(0, -1, 0);
if (!ValidMove())
{
transform.position -= new Vector3(0, -1, 0);
AddToGrid();
CheckForLines();
this.enabled = false;
FindObjectOfType<SpawnTetromino>().NewTetromino();
}
previousTime = Time.time;
}
}
IEnumerator ClearLines(int i)
{
for (int j = 0; j < width; j++)
{
if (grid[j, i] != null)
{
Animator animator = grid[j, i].GetComponent<Animator>();
if (animator != null)
{
animator.SetTrigger(lineClearAnimationTrigger);
}
yield return new WaitForSeconds(lineClearAnimationDuration);
Destroy(grid[j, i].gameObject);
grid[j, i] = null;
}
}
RowDown(i);
UpdateUi();
linesClearingCount--;
if (linesClearingCount <= 0)
{
isLineClearAnimationInProgress = false;
spawnTetromino.NewTetromino();
}
}
void CheckForLines()
{
for (int i = height - 1; i >= 0; i--)
{
if (HasLine(i))
{
LinesCleared++;
linesClearingCount++;
StartCoroutine(ClearLines(i));
}
}
if (linesClearingCount > 0)
{
isLineClearAnimationInProgress = true;
}
}
bool HasLine(int i)
{
for(int j = 0; j< width; j++)
{
if (grid[j, i] == null)
return false;
}
return true;
}
void DeleteLine(int i)
{
for (int j = 0; j < width; j++)
{
if (grid[j, i] != null)
{
Animator animator = grid[j, i].GetComponent<Animator>();
if (animator != null)
{
animator.SetBool("LineClear", false);
}
Destroy(grid[j, i].gameObject, lineClearAnimationDuration);
grid[j, i] = null;
}
}
}
void RowDown(int i)
{
for (int y = i; y < height; y++)
{
for (int j = 0; j < width; j++)
{
if(grid[j,y] != null)
{
grid[j, y - 1] = grid[j, y];
grid[j, y] = null;
grid[j, y - 1].transform.position -= new Vector3(0, 1, 0);
}
}
}
}
void AddToGrid()
{
bool gameOver = false;
foreach (Transform children in transform)
{
int roundedX = Mathf.RoundToInt(children.transform.position.x);
int roundedY = Mathf.RoundToInt(children.transform.position.y);
grid[roundedX, roundedY] = children;
if (children.transform.position.y >= 19.5f)
{
gameOver = true;
}
if (gameOver)
{
FindObjectOfType<SpawnTetromino>().GameOver();
}
}
}
bool ValidMove()
{
foreach (Transform children in transform)
{
int roundedX = Mathf.RoundToInt(children.transform.position.x);
int roundedY = Mathf.RoundToInt(children.transform.position.y);
if(roundedX < 0 || roundedX >= width || roundedY < 0 ||roundedY >= height)
{
return false;
}
if (grid[roundedX, roundedY] != null)
return false;
}
return true;
}
public static void UpdateUi()
{
TMP_Text linesClearedText = GameObject.Find("Lines_Cleared").GetComponent<TextMeshProUGUI>();
linesClearedText.text = "Lines Cleared: " + LinesCleared.ToString();
Debug.Log(linesClearedText.text);
}
void LevelUp()
{
int newLevel = LinesCleared / linesPerLevel;
if (newLevel > level)
{
int levelDifference = newLevel - level;
level = newLevel;
for (int i = 0; i < levelDifference; i++)
{
fallTime = Mathf.Max(fallTime - fallTimeDecrease, minFallTime);
}
}
}
public static void ResetStaticVariables()
{
grid = new Transform[width, height];
LinesCleared = 0;
}
void Start()
{
gameManager = FindObjectOfType<GameManager>();
if (gameManager != null)
{
startMenu = gameManager.StartMenu;
}
else
{
Debug.LogError("GameManager not found in the scene!");
}
ResetGame();
spawnTetromino = FindObjectOfType<SpawnTetromino>();
blockAnimator = GetComponent<Animator>();
if (blockAnimator == null)
{
Debug.LogError("Animator component not found on the Tetris block!");
}
}
}
make the animation duration be the same as the animation,
To ensure that the animation duration in your Tetris game matches the actual length of the animation clip, you can dynamically retrieve the animation length from the AnimationClip instead of using a hardcoded lineClearAnimationDuration. This approach makes your code more maintainable and reduces the chances of discrepancies between the animation and its handling logic.
Below are the steps and code modifications you can implement to achieve this:
Add a Reference to the AnimationClip:
First, add a reference to the AnimationClip that is used for the line clear animation. This allows you to access its length dynamically.
[SerializeField] private AnimationClip lineClearClip;
Remove or Update the lineClearAnimationDuration:
Since you'll be using the actual animation length, you can remove the lineClearAnimationDuration variable or update its usage to utilize lineClearClip.length.
// Remove this line if no longer needed
// public float lineClearAnimationDuration = 1f;
Update the Coroutine to Use Animation Length:
Modify the ClearLines coroutine to use the length of the lineClearClip instead of the hardcoded duration.
IEnumerator ClearLines(int i)
{
for (int j = 0; j < width; j++)
{
if (grid[j, i] != null)
{
Animator animator = grid[j, i].GetComponent<Animator>();
if (animator != null)
{
animator.SetTrigger(lineClearAnimationTrigger);
}
// Use the actual animation length
float animationLength = lineClearClip != null ? lineClearClip.length : 1f;
yield return new WaitForSeconds(animationLength);
Destroy(grid[j, i].gameObject);
grid[j, i] = null;
}
}
RowDown(i);
UpdateUi();
linesClearingCount--;
if (linesClearingCount <= 0)
{
isLineClearAnimationInProgress = false;
spawnTetromino.NewTetromino();
}
}
Assign the AnimationClip in the Inspector:
After adding the reference, assign the appropriate AnimationClip to the lineClearClip slot in the Unity Inspector. This ensures that the script knows which animation's length to use.
Ensure the AnimationClip is Properly Configured:
Make sure that the AnimationClip assigned to lineClearClip accurately represents the line clear animation. This includes verifying the duration and ensuring it plays as expected within the Animator.
Optional: Handle Missing AnimationClip Gracefully:
To prevent potential null reference issues, you can add error handling in the Start method to ensure that lineClearClip is assigned.
void Start()
{
gameManager = FindObjectOfType<GameManager>();
if (gameManager != null)
{
startMenu = gameManager.StartMenu;
}
else
{
Debug.LogError("GameManager not found in the scene!");
}
ResetGame();
spawnTetromino = FindObjectOfType<SpawnTetromino>();
blockAnimator = GetComponent<Animator>();
if (blockAnimator == null)
{
Debug.LogError("Animator component not found on the Tetris block!");
}
if (lineClearClip == null)
{
Debug.LogError("Line Clear AnimationClip is not assigned!");
}
}
Complete Updated Script:
Here’s the complete updated script with the relevant changes highlighted:
Explanation of Changes:
Added lineClearClip: This serialized field allows you to assign the specific AnimationClip used for the line clear animation via the Unity Inspector.
Updated ClearLines Coroutine: Instead of waiting for a fixed lineClearAnimationDuration, the coroutine now retrieves the length of the assigned AnimationClip (lineClearClip.length) and waits for that duration. If lineClearClip is not assigned for some reason, it defaults to 1 second to prevent potential issues.
Error Handling in Start: Added a check to ensure that lineClearClip is assigned. If not, it logs an error to help with debugging.
Removed lineClearAnimationDuration: Since the animation duration is now dynamically determined, the hardcoded lineClearAnimationDuration variable is no longer necessary. You can remove it or keep it if it's used elsewhere with a default value.
Assigning the AnimationClip:
In the Unity Editor:
TetrisBlock GameObject in your scene.Line Clear Clip field under the TetrisBlock component.AnimationClip to this field by dragging and dropping it from your Project window.Ensure the Animator is Configured Correctly:
Animator component associated with each block has the correct AnimationController and that the LineClear trigger corresponds to the appropriate animation state.By following these steps, your line clear animations will now automatically use the correct duration based on the actual animation clip, ensuring synchronization between the animation and game logic.
Not yet included in a published release.
using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;
using TMPro;
using UnityEngine.UI;
public class TetrisBlock : MonoBehaviour
{
public static bool isLineClearAnimationInProgress = false;
// Removed or comment out the hardcoded duration
// public float lineClearAnimationDuration = 1f;
public float fallTimeDecrease = 0.2f;
public float minFallTime = 0.01f;
public static int LinesCleared;
public static int height = 21;
public TMP_Text Lines_Cleared;
public int linesPerLevel = 10;
public Vector3 rotationPoint;
public float fallTime = 0.8f;
public static int width = 10;
public bool gameOver = false;
[SerializeField] private Animator myAnimationController;
private static Transform[,] grid = new Transform[width, height];
private float initialFallTime = 0.8f;
private GameManager gameManager;
private int previousLevel = 0;
private GameObject startMenu;
private float previousTime;
private int level = 0;
private SpawnTetromino spawnTetromino;
private static int linesClearingCount = 0;
[SerializeField] private Animator blockAnimator;
[SerializeField] private string lineClearAnimationTrigger = "LineClear";
// Add a reference to the AnimationClip
[SerializeField] private AnimationClip lineClearClip;
void ResetGame()
{
if (SceneController.hasRestartedScene)
{
startMenu.SetActive(false);
fallTime = initialFallTime;
level = 0;
LinesCleared = 0;
linesClearingCount = 0;
UpdateUi();
SceneController.hasRestartedScene = false;
Debug.Log($"Scene Has restarted, hasRestartedScene: {SceneController.hasRestartedScene}, fallTime: {fallTime}");
}
}
void Update()
{
if (startMenu != null && !startMenu.activeSelf)
{
LevelUp();
InputHandler();
}
}
void InputHandler()
{
if(Input.GetKeyDown(KeyCode.LeftArrow) || Input.GetKeyDown(KeyCode.A))
{
transform.position += new Vector3(-1, 0, 0);
if(!ValidMove())
transform.position -= new Vector3(-1, 0, 0);
}
else if (Input.GetKeyDown(KeyCode.RightArrow) || Input.GetKeyDown(KeyCode.D))
{
transform.position += new Vector3(1, 0, 0);
if (!ValidMove())
transform.position -= new Vector3(1, 0, 0);
}
else if (Input.GetKeyDown(KeyCode.X))
{
transform.RotateAround(transform.TransformPoint(rotationPoint), new Vector3(0,0,1), 90);
if (!ValidMove())
transform.RotateAround(transform.TransformPoint(rotationPoint), new Vector3(0, 0, 1), -90);
}
if (Time.time - previousTime > (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.S) ? fallTime / 10 : fallTime))
{
transform.position += new Vector3(0, -1, 0);
if (!ValidMove())
{
transform.position -= new Vector3(0, -1, 0);
AddToGrid();
CheckForLines();
this.enabled = false;
FindObjectOfType<SpawnTetromino>().NewTetromino();
}
previousTime = Time.time;
}
}
IEnumerator ClearLines(int i)
{
for (int j = 0; j < width; j++)
{
if (grid[j, i] != null)
{
Animator animator = grid[j, i].GetComponent<Animator>();
if (animator != null)
{
animator.SetTrigger(lineClearAnimationTrigger);
}
// Use the actual animation length
float animationLength = lineClearClip != null ? lineClearClip.length : 1f;
yield return new WaitForSeconds(animationLength);
Destroy(grid[j, i].gameObject);
grid[j, i] = null;
}
}
RowDown(i);
UpdateUi();
linesClearingCount--;
if (linesClearingCount <= 0)
{
isLineClearAnimationInProgress = false;
spawnTetromino.NewTetromino();
}
}
void CheckForLines()
{
for (int i = height - 1; i >= 0; i--)
{
if (HasLine(i))
{
LinesCleared++;
linesClearingCount++;
StartCoroutine(ClearLines(i));
}
}
if (linesClearingCount > 0)
{
isLineClearAnimationInProgress = true;
}
}
bool HasLine(int i)
{
for(int j = 0; j< width; j++)
{
if (grid[j, i] == null)
return false;
}
return true;
}
void DeleteLine(int i)
{
for (int j = 0; j < width; j++)
{
if (grid[j, i] != null)
{
Animator animator = grid[j, i].GetComponent<Animator>();
if (animator != null)
{
animator.SetBool("LineClear", false);
}
Destroy(grid[j, i].gameObject, lineClearAnimationDuration);
grid[j, i] = null;
}
}
}
void RowDown(int i)
{
for (int y = i; y < height; y++)
{
for (int j = 0; j < width; j++)
{
if(grid[j,y] != null)
{
grid[j, y - 1] = grid[j, y];
grid[j, y] = null;
grid[j, y - 1].transform.position -= new Vector3(0, 1, 0);
}
}
}
}
void AddToGrid()
{
bool gameOver = false;
foreach (Transform children in transform)
{
int roundedX = Mathf.RoundToInt(children.transform.position.x);
int roundedY = Mathf.RoundToInt(children.transform.position.y);
grid[roundedX, roundedY] = children;
if (children.transform.position.y >= 19.5f)
{
gameOver = true;
}
if (gameOver)
{
FindObjectOfType<SpawnTetromino>().GameOver();
}
}
}
bool ValidMove()
{
foreach (Transform children in transform)
{
int roundedX = Mathf.RoundToInt(children.transform.position.x);
int roundedY = Mathf.RoundToInt(children.transform.position.y);
if(roundedX < 0 || roundedX >= width || roundedY < 0 ||roundedY >= height)
{
return false;
}
if (grid[roundedX, roundedY] != null)
return false;
}
return true;
}
public static void UpdateUi()
{
TMP_Text linesClearedText = GameObject.Find("Lines_Cleared").GetComponent<TextMeshProUGUI>();
linesClearedText.text = "Lines Cleared: " + LinesCleared.ToString();
Debug.Log(linesClearedText.text);
}
void LevelUp()
{
int newLevel = LinesCleared / linesPerLevel;
if (newLevel > level)
{
int levelDifference = newLevel - level;
level = newLevel;
for (int i = 0; i < levelDifference; i++)
{
fallTime = Mathf.Max(fallTime - fallTimeDecrease, minFallTime);
}
}
}
public static void ResetStaticVariables()
{
grid = new Transform[width, height];
LinesCleared = 0;
}
void Start()
{
gameManager = FindObjectOfType<GameManager>();
if (gameManager != null)
{
startMenu = gameManager.StartMenu;
}
else
{
Debug.LogError("GameManager not found in the scene!");
}
ResetGame();
spawnTetromino = FindObjectOfType<SpawnTetromino>();
blockAnimator = GetComponent<Animator>();
if (blockAnimator == null)
{
Debug.LogError("Animator component not found on the Tetris block!");
}
if (lineClearClip == null)
{
Debug.LogError("Line Clear AnimationClip is not assigned!");
}
}
}