Mouse Input to 4 way Direction

I’m trying to figure out a good way to return from a mouse input/touch a 4 way direction e.g up/right/down/left

I can get the world coordinates using this code I’ve built.

if (Input.GetMouseButtonDown(0) == true)
       {
        Plane mPlane = new Plane(Vector3.up, transform.position);

        Ray mRay = Camera.main.ScreenPointToRay(Input.mousePosition);

        float mDistance= 0.0f;
        if (mPlane.Raycast(mRay, out mDistance) == true)
          {
           Vector3 mPosition = mRay.GetPoint(mDistance);
          }
      }

I know I can normalize the mPosition vector but off my head I just cannot think of a way to simplify the direction as mentioned.

Cheers

Try using ScreenToViewportPoint with your mouse position. It will give you the position relative to the screen size (viewport) of the application in 2D grid coordinates.

(0,0) would be the bottom-left of the viewport, (1,1) would be the top-right of the viewport, and (0.5,0.5) would be the center of the viewport. With that in mind, you can assume that:

  • (<0.5, y) = The mouse position is near the left of the screen.

  • (>0.5, y) = The mouse position is near the right of the screen.

  • (x, <0.5) = The mouse position is near the bottom of the screen.

  • (x, >0.5) = The mouse position is near the top of the screen.

1 Like

Hi @Vryken ,

I believe your idea would be no different than normalizing the vector I return in “mPositon”.

I know I could come up with a grid e.g if X < 0 then it must be at least going left or up or down something like that but I’m certain there must be an easier way?

Cheers