Mouse Position Y/Transform Y Detection

I have an empty gameobject as a child object on my player in my 2d game. In my code, I set it as a transform. I was hoping to be able to detect when the mouse goes above it, but the numbers I am showing in my debug log for the mouse y position are way off. Here is my code.

    public Transform mouseUP;
    public Transform mouseDOWN;
    public Vector2 mousePos;




 
    void Update()
    {
        mousePos = Camera.main.WorldToScreenPoint(Input.mousePosition);
        float xpos = mouseUP.transform.localPosition.x;
        float ypos = mouseUP.transform.localPosition.y;



        if (mousePos.y > ypos)
        {
            MovementStates = Movement.ShootUpRight;
        }

        Debug.Log(mousePos.y);
        //Debug.Log(ypos);

I have also tried just using Input.mousePosition for the y coordinates, the numbers I am getting have nothing to do with the y position of the mouseUP transform.

First identify what you EXPECT them to be.

Then print out what they ACTUALLY are.

Hard wire inputs with actual pre-made code values if it’s too tricky to get right with the mouse.

Beyond that, to help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run?
  • what are the values of the variables involved? Are they initialized?

Knowing this information will help you reason about the behavior you are seeing.

This is what I am running now. I still do not understand what is going on. I want my game to detect if the mouse position y is above a certain height.

        Vector2 mousePos = Cam.WorldToScreenPoint(Input.mousePosition);

        float ypos = mousePos.y;
        float xpos = mousePos.x;

        Debug.Log(aa);


        if (ypos > 38000 && xpos > 34000)
        {
            MovementStates = Movement.ShootUpRight;
        }

        if (ypos < 38000 && xpos > 34000)
        {
            MovementStates = Movement.ShootRight;
        }


        // Debug.Log(mousePos);
        Debug.Log(ypos);

This is working but changing the screen size makes the variables of the mouse position change. I do not see hardwiring it to full screen as a solution. Would it be better to use raycasts maybe?

This is how it is supposed to work. It’s the pixel position on the screen surface. More pixels, less pixels? Different numbers.

You can use Screen.width or Screen.height to normalize the mouse positions to some baseline that you expect them to be. This is quite common when working with numeric mouse inputs (vs for instance just clicking on buttons).

1 Like

Figured it out in case anyone needs to reference this in the future.

I used

Vector2 mousePos = Cam.ScreenToWorldPoint(Input.mousePosition);

instead of WorldToScreenPoint