WASD
WASD

Reputation: 1

how to find the mouse position in the window sfml in c

im trying to just make a button in the middle of the screen but i cant check if the mouse is inside the sfRectangleShape

sfRectangleShape* newButton(sfVector2f size, sfVector2f position, sfColor color)
{
    sfRectangleShape *newButton;
    newButton = sfRectangleShape_create();
    sfRectangleShape_setSize(newButton, size);
    sfRectangleShape_setOrigin(newButton, (sfVector2f){sfRectangleShape_getSize(newButton).x / 2, sfRectangleShape_getSize(newButton).y / 2});
    sfRectangleShape_setFillColor(newButton, color);
    sfRectangleShape_setPosition(newButton, position);

    return newButton;
}

int main()
{
    sfRenderWindow* window;
    sfView *view = sfView_create();
    window = sfRenderWindow_create((sfVideoMode){600, 400, 32}, "", sfResize | sfClose, NULL);
    sfRectangleShape *screenButton = newButton((sfVector2f){100, 35}, (sfVector2f){300, 200}, rgba(72, 74, 89));
    sfVector2i mouse_pos;

    while (sfRenderWindow_isOpen(window))
    {
        sfRenderWindow_mapPixelToCoords(window, mouse_pos, view);

        sfEvent event;
        while (sfRenderWindow_pollEvent(window, &event))
        {
            /* Close window : exit */
            if (event.type == sfEvtClosed)
                sfRenderWindow_close(window);
        }

        printf("%d, %d", mouse_pos.x, mouse_pos.y);

        sfRenderWindow_clear(window, sfColor_fromRGBA(82, 84, 100, 1));
        sfRenderWindow_drawRectangleShape(window, screenButton, NULL);
        sfRenderWindow_display(window);
    }
 
    return 0;
}

i cant find a example or a tutorial that teach how to detect if my mouse are inside the sfRectangleShape and the function sfRenderWindow_mapPixelToCoords just return the number -40270372832704

Upvotes: 0

Views: 1092

Answers (2)

Monogeon
Monogeon

Reputation: 394

As Kolbjørn Christiansen said you can use sfMouse_getPosition(window) to get the position of the mouse on your window (not screen. if you want screen you have to remove window from the function arg: sfMouse_getPosition()).

I want to add that this function returns a vector 2f, which is an object containing x and y coords. You can also use with accordance to this the globalbounds function contains to see if that coord is inside that object, a full workup of the solution would be:

sf::RectangleShape rect;
//init rect sizes position etc.
//...
    if (rect.getGlobalBounds().contains(sf::Mouse::getPosition(window).x, sf::Mouse::getPosition(window).y))
    {
        //means mouse is in rect
    }
    else
    {
        //mouse is not in rect
    }

Upvotes: 2

Kolbjørn
Kolbjørn

Reputation: 46

You could use sfMouse_getPosition(window) to get the mouse coordinates, which returns as sfVector2i

Upvotes: 1

Related Questions