Camera Movement Bounds?

Hello,

I have a simple camera movement script that moves on the X,Z axis (the camera is top down). I want to make the camera move within a bounds.

I first tried adding a physical collider around the border and on the camera, but the effect is kind of awful, meaning the camera just bounces off and rotates… It doesn’t work basically.

I tried scripted a boundary too by doing this:

if(transform.position.z < 20){
	transform.Translate(0, Input.GetAxis ("Vertical") * sensitivity, 0);
}

If the camera moves further than 20, it stops on the Vertical axis like it should, but then I can’t move it back down because its out of the if statement.

Any ideas? I sure would appetite it.

I’m a little confused that you’re checking the z position of the transform but then translating along Y… Is this just a mistake when you re-typed it over here?

Anyway this should be what you’re looking for. I’m assuming C#… Either way this should help you get the idea.

// define max position
float maxZ = 20.0f; // you could even make this serialized so you can change it from the inspector later

// figure out how much we are trying to move by
float wantMoveZ = Input.GetAxis ("Vertical") * sensitivity;
// make sure we're not going too far
float moveZ = Mathf.Min(maxZ - transform.position.z, wantMoveZ);

// finally apply the movement (if there is any)
if (moveZ != 0) {
    transform.Translate(0, 0, moveZ);
}

There’s more easy ways to do this but I was hoping to keep it a little optimized…

This will keep the movement pinned at a max of 20. If there is no movement in Z then it will not translate the transform, etc, if for some reason it manages to go past 20 it will be reset to 20 (thanks to the min) etc etc