Hello there! I’m currently trying to make a Tetris-like game and I’ve been able to get all the tetrominoes to move but I don’t know how to restrict that movement so they don’t go off the screen. I’m trying to get them to stay in a box that is 160x280 (width x height) and the bottom left corner is in (0,0). I’m moving the tetrominos by integers of 20 at a time hence the 20’s in the code. Right now this is the code:
private float previousTime;
public float fallTime = 0.8f;
public static int height = 280;
public static int width = 160;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
transform.position += new Vector3(-20, 0, 0);
if (!ValidMove())
transform.position -= new Vector3(-20, 0, 0);
}
else if (Input.GetKeyDown(KeyCode.RightArrow))
{
transform.position += new Vector3(20, 0, 0);
if (!ValidMove())
transform.position -= new Vector3(20, 0, 0);
}
if(Time.time - previousTime > (Input.GetKey(KeyCode.DownArrow) ? fallTime / 20 : fallTime))
{
transform.position += new Vector3(0, -20, 0);
previousTime = Time.time;
}
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;
}
}
return true;
}
}
}
Thank you very much if you can help!