Keep a 2D Object Inside the Screen
If you want a GameObject in Unity 2D to move left and right but never leave the visible game screen, the cleanest approach is to calculate the screen boundaries in world space and clamp the object’s position.
Here’s a polished, production‑ready script that does exactly that.
🎯 Keep a 2D Object Inside the Screen (Unity C#)
using UnityEngine;
public class ScreenBoundedMovement2D : MonoBehaviour
{
[Header("Movement Settings")]
public float speed = 3f;
private float leftBound;
private float rightBound;
void Start()
{
// Convert screen edges to world space
Camera cam = Camera.main;
Vector3 left = cam.ScreenToWorldPoint(new Vector3(0, 0, cam.nearClipPlane));
Vector3 right = cam.ScreenToWorldPoint(new Vector3(Screen.width, 0, cam.nearClipPlane));
leftBound = left.x;
rightBound = right.x;
}
void Update()
{
// Move left/right using input (A/D or arrows)
float move = Input.GetAxisRaw("Horizontal") * speed * Time.deltaTime;
transform.Translate(move, 0, 0);
// Clamp position inside screen
Vector3 pos = transform.position;
pos.x = Mathf.Clamp(pos.x, leftBound, rightBound);
transform.position = pos;
}
}
🧠What this script does
- Converts the screen edges into world coordinates
- Moves the object left/right using player input
- Clamps the X‑position so the object never leaves the camera view
Perfect for:
- Players
- Enemies
- Platforms
- Collectibles
Comments