How to pan in unity 3d space?

1.7k Views Asked by At

I have two c # scripts that are attached to my main camera object. These scripts rotate around my gameobject and also allows me to zoom in and out. But I am trying to pan. How can I do that?

I have a few classes that are attached to my main camera object. It is to rotate and to zoom in and out. But it is very limiting. I want to pan through the game. How do I do that?

Here is my code for rotating:

    [SerializeField] private Camera cam;
    private Vector3 previousPosition;

    void Update()
    {
        Vector3 eulerAngles = transform.rotation.eulerAngles;
        eulerAngles = new Vector3(0, eulerAngles.y, 0);
        transform.rotation = Quaternion.Euler(eulerAngles);
        if (Input.GetMouseButtonDown(2))
        {
            previousPosition = cam.ScreenToViewportPoint(Input.mousePosition);
        }

        if (Input.GetKey(KeyCode.LeftShift) && Input.GetMouseButton(2))
        {
            Vector3 direction = previousPosition - cam.ScreenToViewportPoint(Input.mousePosition);
            cam.transform.RotateAround(new Vector3(), new Vector3(1, 0, 0), direction.y * 45);
            cam.transform.RotateAround(new Vector3(), new Vector3(0, 1, 0), -direction.x * 360);
            // cam.transform.RotateAround(new Vector3(), new Vector3(1, 0, 0), -direction.y * 360);

            previousPosition = cam.ScreenToViewportPoint(Input.mousePosition);
        }
    }

Here is my code for zooming:

    [SerializeField] private Camera cam;

    void Update()
    {
        if (Input.GetAxis("Mouse ScrollWheel") > 0)
        {
            cam.GetComponent<Camera>().fieldOfView--;
        }
        if (Input.GetAxis("Mouse ScrollWheel") < 0)
        {
            cam.GetComponent<Camera>().fieldOfView++;
        }
    }

As, I mentioned, they are both attached to my main camera. The problem with these script is that I want to pan and these scripts don't do that. How do I pan my camera around my gameobject?

1

There are 1 best solutions below

0
SpicyCatGames On

Just do this

transform.Translate(direction * Time.deltaTime);

where direction is a Vector3, the direction you want to pan.

The problem is, your rotation script is rotation around position 0,0,0. So rotation won't work correctly once you move the camera from there. You'll have to change the rotation script to use the correct position.

Instead of actually panning the camera, you'd find it easier to have an empty gameobject and have the camera follow that gameobject. Pan that object when you want to move the camera, and use the position of the object and rotate the camera around it, assuming you don't want the camera to be following the player.