Restricting gameObject movement to a box

Hi, I’m very new here! I’m trying to make a Tetris-like game and I’ve been able to get all the blocks to move but the player is able to move the blocks out of the intended area. 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 blocks by integers of 20 at a time hence the 20’s in the code. 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 / 10 : 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 < 10 || roundedX >= width - 10 || roundedY < 10 ||roundedY >= height)
                {
                    return false;
                }
            }

            return true;
        }
    }
}

Thank you very much if you’re able to help!

Mathf.Clamp() is probably the most useful way to do this.

This means horribly hairy oneliners like this:

need to be pulled apart into:

  • copy the position from the transform
  • update it
  • clamp it
  • write it back to the transform

Do you have any links to resources you could share with me that explain how I would do this?

You mean beyond the huge wall of sample code on the Mathf.Clamp() documentation page?