- Home /
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
Answer by Statement · Mar 04, 2011 at 12:28 PM
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.
i think I'm going to stick with the frustum method, thanks for your reply.
Note that if the camera is moving, then you might get tunneling effects (the player escaping the bounds), when using a simple mesh collider. You might want to construct convex mesh colliders (extrude the colliders out a bit, reaching outside the field of view
Hi, Statement, I want to set 4 colliders and locate them at the border, but I did not solve how to archieve it. Do you know how to write in the codes?
Answer by PrimeDerektive · Mar 04, 2011 at 04:55 PM
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.
Just what i needed thank u very much, now to get my head around using it properly...
Your answer
Follow this Question
Related Questions
Camera Zoom script stops ability to pan 1 Answer
2D Orthographic camera movement clamp in any orthographic size 1 Answer
RTS Camera Rotation and Movement 0 Answers
Camera movement question 1 Answer
Clamping Issue 1 Answer