The first way I’d do this is to grab the viewport of the camera and find the world space coordinates for that viewport at the game plane.
Camera:
ViewportToWorldPoint
Then, once I had the “bounds” of the game as defined by what the camera can see, I would need to find the size of the Player Ship. To do this, I would use Renderer.bounds, as this returns a world space value, whereas Mesh.bounds returns a local space value.
Renderer-bounds
Mesh-bounds
Then I could calculate my x/z Min/Max clamp values.
Specifically:
Create a public reference to the camera being used (or use Camera.Main* instead in the code below):
public Camera myCamera;
*Read the Camera Component docs for more information of “Camera.Main”
Set the x/z Min/Max clamp values to
private float xMin;
private float xMax;
private float zMin;
private float zMax;
Then, in Start(), find the bounds of what the camera can see via ViewPortToWorldPoint, find the HALF of the size of the ship with renderer.bounds.extents, and then set the x/z Min/Max clamp values
void Start () {
// Find the topRight and lowerLeft of the camera Viewport in World Space
Vector3 topRight = myCamera.ViewportToWorldPoint (new Vector3 (1.0f, 0.6f, myCamera.transform.position.y));
Vector3 lowerLeft = myCamera.ViewportToWorldPoint (new Vector3 (0.0f, 0.0f, myCamera.transform.position.y));
// Find the bounds of the ship
float shipWidth = renderer.bounds.extents.x;
float shipLength = renderer.bounds.extents.z;
// Set the bounds for the clamp position by code
xMin = lowerLeft.x + shipWidth;
xMax = topRight.x - shipWidth;
zMin = lowerLeft.z + shipLength;
zMax = topRight.z - shipLength; // ShipLength isn't 100% necessary as this is an aesthetic choice within the play field.
}
NOTE: The “0.6f” value on line 3 in the “Start” function: Vector3 topRight = camera.ViewportToWorldPoint (new Vector3 (1.0f, 0.6f, camera.transform.position.z)); This sets the upper boundary within the game for the player ship. You could make a new public variable, and tweak this in the inspector:
public float playerLimit;
and change the line in “Start” to use this variable:
Vector3 topRight = camera.ViewportToWorldPoint (new Vector3 (1.0f, playerLimit, camera.transform.position.z));