Pages

Thursday, December 23, 2010

Unity3d + C#: Rect.Contains(Correct mouse postion)...

When using the Contains function:
void Update() {
    buttonRect = new Rect(20,20,50,50);
 
    if (buttonRect.Contains(Input.mousePosition))
    {
        print("haha");
    }

void OnGUI() {
    GUI.Button(buttonRect, "");
}

I realize that the phrase "haha" will be printed in the compiler only when the mouse position is at Rect(20, Screen.height - 20, 50, 50), instead of Rect (20, 20, 50, 50). So what happen is that the origin (0, 0) of the mouse's position starts at the bottom left of the screen... instead of the top left.

To solve the problem here, I created a function that return a value from reverting the mouse's Y position...
Vector2 RevertMousePosValue(Vector2 mousePos) {
    Vector2 newMousePos;
    newMousePos.x = mousePos.x;
    newMousePos.y = -mousePos.y + Screen.height;

    return newMousePos;
}

How the function and formula works:

And then applying it in the Update() function:
void Update() {
    Vector2 mousePos = RevertMousePosValue(Input.mousePosition);
}

So, what I do next is to compile all scripts together while switching the "Input.mousePosition" with "mousePos":
using UnityEngine;
using System.Collections;

public class TestingScript : MonoBehaviour {
    private Vector2 mousePos;
    
    void Update() {
        mousePos = RevertMousePosValue(Input.mousePosition);
    }

    void OnGUI() {
        Rect buttonRect = new Rect(20,20,50,50);
        GUI.Button(buttonRect, "");
        if (buttonRect.Contains(mousePos))
        {
            print("haha");
        }
    }
    Vector2 RevertMousePosValue(Vector2 mousePos) {
        Vector2 newMousePos;
        newMousePos.x = mousePos.x;
        newMousePos.y = -mousePos + Screen.height;

        return newMousePos;
    }
}

and... that should do it. Check out my mini coding project which uses similar method.

2 comments:

Daniel said...

Thanks for the code
It has two wrong lines

Rect -
Rect buttonRect = new Rect(20,20,50,50);

and Y
newMousePos.y = -mousePos.y + Screen.height;

JakeL168 said...

Daniel: Thanks for the remind... I'll change it right away~ :)