Instantiating Prefab at MousePosition & GUI.Matrix

Hello,

I was able to get an object to instantiate at the mouse position correctly before I added a GUI Matrix to keep the GUI scale. This is the code I was using.

            Screen.showCursor = false;
			Rect pos = new Rect(mousePos.x, Screen.height - mousePos.y ,turretCanPlace.width, turretCanPlace.height);
			GUI.Label(pos, mineCanPlace);	
			
			// If the player pressed LMB, instatiate the turret
			if(Input.GetMouseButton(0))
			{
				Vector3 worldPos = Camera.main.ScreenToWorldPoint(mousePos);
				worldPos.y -= 65.8f;
				Debug.Log("TurretSceneScript.OnGui(Placing turret) World Pos: " + worldPos);
				Instantiate(turretPrefab, worldPos, Quaternion.identity); //AngleAxis(90, Vector3.up));
				
				// Set the cursor back to visible
				Screen.showCursor = true;
			}

When I added the GUI Matrix, the prefab no longer instantiated at the correct position. Here is the code for the GUI.Matrix. It’s resizing from 1920 * 1080.

public static void AutoResize(int screenWidth, int screenHeight)
	{
	    Vector2 resizeRatio = new Vector2((float)Screen.width / screenWidth, (float)Screen.height / screenHeight);
	    GUI.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(resizeRatio.x, resizeRatio.y, 1.0f));
	}

I messed around with the code, and got a partial fix, but as I move the cursor to the right, or down, the distance between the icon and instantiated prefab increases. Here’s what I’m currently using:

Rect pos = new Rect(mousePos.x * (1920/Screen.width), (1080/Screen.height) * (Screen.height - mousePos.y) ,turretCanPlace.width, turretCanPlace.height);

Can anyone help me figure out how to get the prefab to instantiate on the correct location? Thanks for your help!

After another hour of head scratching I figured it out. Started outputing the position of the label for the turret, and the mouse position. Eventually realised that the inaccuracy resulted from dividing an int by a float.

Rect pos = new Rect(mousePos.x * (1920/Screen.width), (1080/Screen.height) * (Screen.height - mousePos.y) ,turretCanPlace.width, turretCanPlace.height);

I just changed the 1920 and 1080 to floats and everything is working ok again.

Rect pos = new Rect(mousePos.x * (1920f/Screen.width), (1080f/Screen.height) * (Screen.height - mousePos.y) ,turretCanPlace.width, turretCanPlace.height);

Hopefully will be of some help to the next guy!