Convert Mouse Position to relative Vector2

I’m building a grid based game, and I need to detect where the mouse position is and convert that to a Vector2 direction. I basically just need to know where the mouse resides within these colored coordinates and access the tile to the left, right, up, or down position.

5098565--502553--MousePos.png

I expected this to work, but the value never changes and always returns:

Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 dir = (mousePos - transform.position).normalized;
Debug.Log("pos: " + dir + "worldp: " + mousePos);

pos: (0.1, 0.1, -1.0)worldp: (4.9, 0.3, -1.0)

When you convert from a screen to a world point and you want to compare the direction you would need to zero out your Z value or it will skew your direction vector (because the world point has a different Z value from your transform).

e.g.

Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 dir = (mousePos - transform.position);
dir.z = 0.0f;
Vector3 dirNormalized = dir.normalized;
Debug.Log("pos: " + dirNormalized + "worldp: " + mousePos);

So the pos value doesn’t change unless I go into the scene and actually move the camera around the player. When I do this, I’m getting values that I would expect such as 1,0,0, 0,1,0.

Here’s a log of values that aren’t changing when I move the player and mouse cursor around it.

5098943--502586--Log.png

It’s difficult to tell from the code without seeing what’s happening. If you want to set up a small test project and post it here I can have a look at it.

From your screenshot, it looks like “worldp” is changing, but “pos” is not.

My best guess is that pos actually is changing, it’s just that you can’t see the changes because Unity is rounding to one decimal point when displaying the coordinates, and the differences in the mouse movement are so small relative to the overall distance that they get drowned out when you normalize.

Try changing your output to also include the value of “transform.position”, and consider removing the “.normalized” part when you calculate dir (at least temporarily, for testing).