Your question is a little unclear, but I think I understood the essence of it. Let's look at your requirements.
- You have an upper camera that looks straight down at a two-dimensional plane. We can imagine this as a simple coordinate pair {x, y}, corresponding to a point on the plane on which the camera is looking.
- The camera can track the movement of an object, perhaps a player, but in general, something in the game world.
- The camera must remain within the final boundary of the game world.
It is simple enough to implement. Broadly speaking, somewhere inside your Update() method, you need to follow the steps to fulfill each of these requirements:
if (cameraTarget != null) { camera.Position = cameraTarget.Position; ClampCameraToWorldBounds(); }
In other words: if we have a target, block our position to its position; but make sure that we do not go beyond.
ClampCameraToBounds() also easy to implement. Assuming you have some kind of object, world , which contains the Bounds property, which represents the scale of the world in pixels:
private void ClampCameraToWorldBounds() { var screenWidth = graphicsDevice.PresentationParameters.BackBufferWidth; var screenHeight = graphicsDevice.PresentationParameters.BackBufferHeight; var minimumX = (screenWidth / 2); var minimumY = (screnHeight / 2); var maximumX = world.Bounds.Width - (screenWidth / 2); var maximumY = world.Bounds.Height - (screenHeight / 2); var maximumPos = new Vector2(maximumX, maximumY); camera.Position = Vector2.Clamp(camera.Position, minimumPos, maximumPos); }
This ensures that the camera will never be closer than half the screen to the edge of the world. Why half the screen? Since we defined the camera {x, y} as the point that the camera is looking at, which means that it should always be centered on the screen.
This should give you a camera with the behavior you indicated in your question. Hence, itโs just a matter of implementing your terrain renderer so that your background is drawn relative to the {x, y} coordinate given by the camera object.
Given the position of the object in the coordinates of the game world, we can translate this position into camera space:
var worldPosition = new Vector2(x, y); var cameraSpace = camera.Position - world.Postion;
And then from camera space to screen space:
var screenSpaceX = (screenWidth / 2) - cameraSpace.X; var screenSpaceY = (screenHeight / 2) - cameraSpace.Y;
Then you can use the screen space coordinates of the object to display it.