Keep gameobject within game screen bounds

Hey, all. I’m larning to code by making a personal schmup project and right now I’m partially able to lock my ships movement within the screen. I say partially because the game object is able to move out of bounds to the left and also beneath it. It seems my code gave me a bounding box four times the size I need, but I don’t know if it’s the cameras settings, the actual code or what. I"ve included a print of the camera settings, any help would be appreciated:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BoundaryCheck : MonoBehaviour
{
private Vector3 screenBounds;
// Start is called before the first frame update
void Start()
{
screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));// Converts the center of the screen to World Units

}

// Update is called once per frame
void LateUpdate()
{
//Clamps ship movement within screen bounds
Vector2 shipPos = transform.position;
shipPos.x = Mathf.Clamp(shipPos.x, screenBounds.x *-1, screenBounds.x);
shipPos.y = Mathf.Clamp(shipPos.y, screenBounds.y *-1, screenBounds.y);
transform.position = shipPos;
}
}

you may need to check the center/pivot point of your ship. That is what the code uses to determine its position. Also take in account the ships size.

I found my old stay in bounds snippet:

public static void StayInBounds(Transform transform)
{
    float bounds = (Global.gridWidth * 5) - 5;
    if (transform.position.x < -bounds - 10) { transform.position = new Vector3(-bounds - 10, transform.position.y, transform.position.z); }
    if (transform.position.x > bounds) { transform.position = new Vector3(bounds, transform.position.y, transform.position.z); }
    if (transform.position.z < -bounds - 10) { transform.position = new Vector3(transform.position.x, transform.position.y, -bounds - 10); }
    if (transform.position.z > bounds) { transform.position = new Vector3(transform.position.x, transform.position.y, bounds); }
}

And boy did that not age well, lol… Have to re-do that eventually.

But if you have an odd shaped object, you kind of have to control x,z with offsets. Another way would be to make BoxColliders as boundaries, and if any object collides with that it knows it’s out of bounds.

I would suggest looking into caching variables/components, as Camera.main and transform.position can chew up a bit of performance, if you start to scale up your project. But in small games it’s really not a noticeable difference. :slight_smile:

Thanks for the info! I’m actually trying to use my cameras viewport as the bounds for my spaceship object. I’m close to finishing it, the only problem now is that half the sprite can escape camera view in the edges, but at least the ship itself stays on screen!

Finding the edges and corners of the 2D screen, width, height, etc. (ScreenMetrics2D):