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
Input.mousePosition.x,
Input.mousePosition.y,
-1f));
camPos = new Vector3( //Get Camera Position (Declared at start of class)
Camera.main.transform.position.x,
Camera.main.transform.position.y,
-1f);
// Zoom in and move to mouse
if (Input.GetAxis ("Mouse ScrollWheel") > 0) { // Forward
if (Camera.main.orthographicSize == ResourceManager.MinCameraHeight){
;} //Purposeful
else {
Camera.main.orthographicSize--;
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.
Thanks!