How to prevent the mouse from moving when the camera does? (zoom to mouse, 2D environment)

I implemented a zoom-to-mouse function in my 2D environment. So you can zoom in and the camera moves towards where the mouse is. However the mouse also moves each time you zoom in, it stays in the same location on the screen, and since the camera moves, the mouse also moves in comparison to the entire world.

How do I resolve this? I tried looking into manually moving the mouse cursor back the same X/Y distance the camera moved. But it does not look like I can set the mouse location in Unity. I also looked into freezing the mouse in it’s current world point, moving the camera, then unfreezing it. But screen.LockCursor just freezes it to the middle of the screen.

( I have been through several pages worth of links on google using different phrases to try and find an answer. I’d rather avoid buying a plugin, just to resolve one small function…)

Any suggestions?

Code Snipped involved:

float xDiff;
float yDiff;
mousePos = Camera.main.ScreenToWorldPoint( new Vector3(  //Get Mouse world Position
camPos = new Vector3(	//Get Camera Position (Declared at start of class)

// Zoom in and move to mouse
if (Input.GetAxis ("Mouse ScrollWheel") > 0) { // Forward
	if (Camera.main.orthographicSize == ResourceManager.MinCameraHeight){
		;} //Purposeful 
	else {
		xDiff = mousePos.x - camPos.x;
		yDiff = mousePos.y - camPos.y;
                Camera.main.transform.position = new Vector3( (camPos.x + (xDiff)), (camPos.x + (yDiff)), -1f);

The movement is very jagged now, but thats an easy fix. I just need to figure out how to get the mouse to not move with the camera, and instead keep the mouse at the same world point it was at when you started to zoom.


The the idea is to 1) get the world position of the mouse, 2) change the orthographicSize, 3) get the new position of the mouse, 4) translate the camera so that the mouse is again over the original world position. Put the following code on a game object in the scene (the camera is fine, but not required). Put a 2D world image on the screen (Quad or Sprite), run the script and use the mouse wheel to scroll. Note this code assumes an Orthographic camera.

using UnityEngine;
using System.Collections;

public class Example : MonoBehaviour {

	public float minOrthoSize = 2.0f;
	public float maxOrthoSize = 25.0f;
	public float zoomSpeed = 0.5f;

	void Update () {
		float f = Input.GetAxis ("Mouse ScrollWheel");
		if ( Mathf.Abs (f) > 0.01f) { 
			Vector3 v3 = Camera.main.ScreenToWorldPoint (Input.mousePosition);
			Camera.main.orthographicSize += zoomSpeed * f;
			Camera.main.orthographicSize = Mathf.Clamp (Camera.main.orthographicSize, minOrthoSize, maxOrthoSize);
			v3 = v3 - Camera.main.ScreenToWorldPoint (Input.mousePosition);
			Camera.main.transform.position += v3;