A simple camera question

Hi!

A week ago I started my first Unity project ever and I’m really excited to get into it! However, I already have a simple problem which I can’t find an answer to.

The project is an adaptation of a board game to PC. The main screen is an angled shot of the board where the magic will happen. Right now this is my code for camera movement:

public class MainCameraMove : MonoBehaviour {

    public float verticalSpeed;
    public float horizontalSpeed;

    public float maxZ;
    public float minZ;

    public float maxX;
    public float minX;

    // Use this for initialization
    void Start () {
  
    }

    // Update is called once per frame
    void Update () {
        float v = verticalSpeed * Input.GetAxis("Vertical");
        float h = horizontalSpeed * Input.GetAxis ("Horizontal");
        transform.Translate (h, 0, v, Space.World);
    }
}

I want to insert boundaries so that I am sure that you always see the board. However due to the fact that I use Translate (h,0,v,Space.World) - because the camera is angled - the answer to the question found in tutorials doesn’t work as expected. How can I set boundaries to the camera which is translated according to the world axes? When I went with the simplest

if (h >= maxZ)
  h = maxZ;
if (h <= minZ)
h = minZ

The camera went crazy.

You are close. instead of modifying H or V, try reading directly from the cameras position in world space.

Lets pretend your camera sits a 0,25,0 in world space. 0 units left/right(X), 25 units above the ground(Y), 0 units forward/backward(Z).

If you wanted to limit the movement of the camera as to how far away it can look away from your target point (in this case: 0,0,0) set up a min/max range for left/right and up/down.

public float maxLeft = -5.0f;
public float maxRight = 5.0f;
public float maxForward = 5.0f;
public float maxBackward = -5.0f;

public Camera cam;
void Update(){
if(cam.transform.position.x < maxLeft ){
cam.transform.position = new Vector3(maxLeft , cam.transform.position.y, cam.transform.position.z);
}

if(cam.transform.position.x > maxRight){
cam.transform.position = new Vector3(maxRight, cam.transform.position.y, cam.transform.position.z);
}

//etc, do the same for the Z axis

}

That is one way I could think of. There are probably many others (maybe more efficient) that someone else may help you with. Another way I thought could world is utilizing Unity - Scripting API: Vector3.Distance , but calling that in Update could be not a good idea.

You also may find it easier to parent the camera to a GameObject with no rotation and move the parent instead.

Thanks fot the answers! These solved the problem.