Simple Boundaries For Movement

So I’m making a game where you basically move side to side dodging obstacles. It is pretty simple, but what I don’t know how to do is make it so that you can’t move out of the camera’s view. Here’s my code, it is pretty simple, but I just need to know how to get bounds in there:

#pragma strict

function Update () 

if (Input.GetKey (KeyCode.A)) transform.Translate (Vector3(-6,0,0) * Time.deltaTime);

if (Input.GetKey (KeyCode.D)) transform.Translate (Vector3(6,0,0) * Time.deltaTime);

If you couldn’t tell, it is a javascript code. It only has the code for moving, not bounds, so if anybody knows how to do that, please tell me. Thanks.


You can use the WorldToScreenPoint to calculate it easily

    Transform obj;
    Camera CalculationCam;
    public void CheckBoundries()
        Vector2 ObjScreenpoint = CalculationCam.WorldToScreenPoint(obj.transform.position);

        if (ObjScreenpoint.x < 0 )
            // obj is too much left

        } else if (ObjScreenpoint.x > Screen.width)
            // obj is too much right


        if (ObjScreenpoint.y < 0)
            // obj is too much down

        else if (ObjScreenpoint.y > Screen.height)
            // obj is too much Up


Good Luck

  • You could move the camera with the player
  • OR
  • Create a Box Collider at the borders
  • And make the player collide with them

Hope it works