- Home /
Constraining a perspective camera in World Y?
I have a top-down camera, pitched 45 degrees about X. I'm trying to constrain the camera from getting too close to the terrain or too far from the terrain. The system that I am trying to implement is just a hard-limit (nothing fancy).
I am at wits end however, as I can't seem to get it to work. On every Update, I have a moveVector, which moves the camera along its local Z axis. I pass the vector into an isInBounds check, which checks if it's in bounds. If it is within an upper and lower constraint in World Y, then it executes the Translate. Else it should set the camera to be at the Y constraint.
My issue is that the camera can go beyond the bounds and get stuck, and the isInBounds check is not correctly setting the camera altitude back to its constraint.
As an example, it's possible to have the camera reach an altitude of 100.5567 (above the maxCameraAltitude of 100) and then no longer be able to move. Why?
The C# snippet for my zoom function and it's boundary check follow:
void moveCameraInZLocalSpaceBasedOnScrollWheel()
{
Vector3 moveVector = Vector3.forward * Input.GetAxis ("Mouse ScrollWheel") * zoomSpeed * Time.deltaTime;
if (isInBounds(moveVector))
{
myCamera.Translate(moveVector);
}
}
bool isInBounds(Vector3 moveVector)
{
bool boundaryCheck = true;
if ((myCamera.position.y + moveVector.y) > maxCameraAltitude)
{
Vector3 vector = myCamera.position;
vector.Set(myCamera.position.x, maxCameraAltitude, myCamera.position.z);
boundaryCheck = false;
}
else if ((myCamera.position.y + moveVector.y) < minCameraAltitude)
{
Vector3 vector = myCamera.position;
vector.Set(myCamera.position.x, minCameraAltitude, myCamera.position.z);
boundaryCheck = false;
}
return boundaryCheck;
}