This is actually fairly simple to implement on a basic level as well. Say you know your level is 4000 pixels wide, your camera is 800px wide and your char is 50 px wide.
To stop your camera going off the off-level, you can't have the left hand position of your screen below 0 (ie: off to the left) or above 3200 (ie: your level with minus the size of your screen).
Similiarly, to stop your char going off-level you can't have the left hand position of your cahr sprite below 0 (ie: off to the left) or above 3950 (ie: your level with minus the size of your char sprite).
Now you know the logic behind it, the code is fairly easy. Say you have a 'MoveChar' and a 'MoveCamera' function. They would look something like this:
| public void MoveChar() |
| { |
| if (CharShouldMoveLeft()) |
| charPosition.X -= 5; |
| |
| if (CharShouldMoveRight()) |
| charPosition.X += 5; |
| |
| MathHelper.Clamp(charPosition.X, 0, 3950); |
| } |
| |
| public void MoveCamera() |
| { |
| if (CameraShouldMoveLeft()) |
| cameraPosition.X -= 5; |
| |
| if (CameraShouldMoveRight()) |
| cameraPosition.X += 5; |
| |
| MathHelper.Clamp(cameraPosition.X, 0, 3200); |
| } |
the 'MathHelper.Clamp' function basically takes the first value and clamps it between the first and second value.
This is obviously a pretty basic method., if you are looking to expand it, look at the platformer sample in the education catalog