Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question 2D camera zoom at mouse point

Discussion in 'Scripting' started by vdweller, May 29, 2020.

  1. vdweller

    vdweller

    Joined:
    May 24, 2020
    Posts:
    7
    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):

    Code (CSharp):
    1. public float zoom = 1f;
    2. public float zoomFactor = 1.1f;
    (Update code)

    Code (CSharp):
    1.         float mw = Input.GetAxis("Mouse ScrollWheel");
    2.         if (Mathf.Abs(mw)>0) {
    3.             Vector3 curPos = Camera.main.transform.position;
    4.             Vector3 offset = (Camera.main.ScreenToWorldPoint(Input.mousePosition) - curPos) / zoom;
    5.             if (mw < 0) zoom *= zoomFactor;
    6.             if (mw > 0) zoom /= zoomFactor;
    7.             Camera.main.orthographicSize += Mathf.Sign(mw)*zoom;
    8.             Camera.main.transform.position = Camera.main.ScreenToWorldPoint(Input.mousePosition) - offset;
    9.         }
    I would appreciate any help!
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,735
    What happened when you tried this code?
     
  3. vdweller

    vdweller

    Joined:
    May 24, 2020
    Posts:
    7
    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.
     
  4. vdweller

    vdweller

    Joined:
    May 24, 2020
    Posts:
    7
    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!
     
  5. Cannist

    Cannist

    Joined:
    Mar 31, 2020
    Posts:
    64
    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:

    Code (CSharp):
    1. Camera cam = Camera.main;
    2. Vector3 moveVector = cam.ScreenToWorldPoint(Input.mousePosition) - cam.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0));
    3. cam.transform.position = cam.transform.position + moveVector;