How can I clamp a GameObject to screen borders?

I am making a 2D top down game, and I'd like to make it when the player hits the edge of the screen, he cant move any more. I don't wanna use colliders for this, due to screen changing with aspect ratio, I'm sort of a semi begginer with code and I would like to find out the easiest way around this.

What I was thinking like `ScreenToWorldPoint`

probably an easier way plz help thanks =D

  • You could have 4 colliders and update them to be located about the points of the screen corners, stretching to the next, having a layer mask that only blocks the player.

  • You could build a mesh that span the frustum of the camera every time the screen resolution is changed, and use a mesh collider (or multiple convex colliders if you would get tunneling). Then you could just parent this to the camera so it follow the camera.

  • Another variant would be to sample each corner to create 4 planes (or lines if it's strictly 2D) and test movement against those planes.

  • A fourth variant would be similar to the previous one; Get the line from the current position to its desired position and clamp it where it meets the screen edge. If you sample the screen locations for "current" and "next" position of your object, you can find out how far in screen space it moves before it's clamped and apply the same scale in world space, to derive the clamped position that way.

Statement pretty much covered it; I would personally use the frustrum planes option (his second bullet point), you could probably make use of this function.