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!
What's the point of keeping the mouse position on the same world point while zooming? Can the camera move laterally while zooming? If so, you could move the camera to be centered above the point that you are clicking on and then zoom in. That way, your mouse position is 0,0,0 (relatively), so zooming shouldn't be a problem.
– smneratI see two choices. First, you could write your zoom so that it preserves the mouse position. If this is route you want to go, I can post some sample code when I get a bit of time. But there is another route. You can simulate the mouse cursor. Typically this is done by hiding the hardware cursor and using a GUITexture. You can use MouseX and MouseY to move the GUITexture. This gives you the ability to position the 'cursor' wherever you want.
– robertbu