2D camera zoom at mouse point

Hello,

I made a search for this topic but couldn’t find a working script.

I would like the camera to zoom in/out with the mouse wheel but use the mouse position as the center of zooming. This is for a Unity 2D project.

The code I tried is (in a C# class called CameraDrag):

public float zoom = 1f;
public float zoomFactor = 1.1f;

(Update code)

        float mw = Input.GetAxis("Mouse ScrollWheel");
        if (Mathf.Abs(mw)>0) {
            Vector3 curPos = Camera.main.transform.position;
            Vector3 offset = (Camera.main.ScreenToWorldPoint(Input.mousePosition) - curPos) / zoom;
            if (mw < 0) zoom *= zoomFactor;
            if (mw > 0) zoom /= zoomFactor;
            Camera.main.orthographicSize += Mathf.Sign(mw)*zoom;
            Camera.main.transform.position = Camera.main.ScreenToWorldPoint(Input.mousePosition) - offset;
        }

I would appreciate any help!

What happened when you tried this code?

The camera does zoom in/out, but sadly not at the mouse point. The code I posted is mine, I tried slightly changing a few calculations but couldn’t achieve the desired result.

I’ve tried fiddling with the code some more and also tried out other snippets from around the internet to no avail. Would appreciate some insight on this!

I have not used any of this before, but assuming that setting the orthographic size already handles zooming all that’s left is to move the camera parallel to the screen. I can think of two solutions:

  1. Determine the cameras current position relative to the middle of the screen and add that vector to the mouse position.

  2. Determine the vector from the middle of the screen to the mouse position and add that to the current camera position.

For the latter, the code would be:

Camera cam = Camera.main;
Vector3 moveVector = cam.ScreenToWorldPoint(Input.mousePosition) - cam.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0));
cam.transform.position = cam.transform.position + moveVector;