Wednesday, February 20, 2013

PlayerOutOfBounds

Most likely, you're going to have a player object in your game that you'll want to keep within the boundaries of the screen. When we say "boundaries of the screen", we really mean within the viewport of the camera.

Typically, during your update cycle, you perform a check on the player object current position, and if it's outside of those boundaries, you reset the player's position back within the bounds. The following code snippet is one way of achieving this in Unity, using some arbitrary boundary numbers that represent world coordinates of the bounds of the camera view, that perhaps you happen to figure out while playing and logging your player's position .


This isn't a very robust solution, however. It ignores variances in screen resolution. The world coordinate of 8.0f may happen be the right most bounds of the X-axis at, for arguments sake, 960x600, but not at a higher, or lower resolution. We should also note that the world coordinates will vary based on where you placed your prefabs within the world as well. 

To keep things as resolution independent as possible, and thus as platform independent as possible, do the following instead. Note, I call obtainScreenBounds in my player object's Start method. You don't need to call it every Update cycle. 


obtainScreenBounds makes use of a key method, ScreenToWorldPoint, "which transforms position from screen space into world space". When you pass in a Vector3 of (0, 0, cameraToPlayerDistance) to this method, a Vector3 that represents the bottom left of the screen, you'll get back a Vector3 representing the same location in world coordinates. When you pass in a Vector3 of (Screen.width, Screen.height, cameraToPlayerDistance), you obtain a Vector3, in world coordinates, that's located at the upper right location of the current screen view. Thus, regardless of what the resolution is, you'll always have the correct screen boundaries to Clamp the player's position with. 

No comments:

Post a Comment