SDL2 Mouse coordinates won't work

Started by
2 comments, last by Utfrugg 7 years, 3 months ago

I have this piece of code that should get the position of the mouse when a button is clicked, then I check if that click is inside a certain area. However, no matter where I click I still get game over. Am I doing something wrong? (btw if this post is in the wrong place, this is my first post so sorry)

Code:

if (gameEvent.type == SDL_MOUSEBUTTONDOWN)
{
SDL_GetMouseState(&mouseX, &mouseY);
if (mouseX >= buttonX && mouseX <= buttonW && mouseY >= buttonY && mouseY <= buttonH) {
win = true;
click = true;
SDL_Surface *winSurface = SDL_LoadBMP("Images/VictoryScreen.bmp");
SDL_Texture *winTexture = SDL_CreateTextureFromSurface(gamerenderer, winSurface);
SDL_RenderClear(gamerenderer);
SDL_RenderCopy(gamerenderer, winTexture, NULL, NULL);
SDL_RenderPresent(gamerenderer);
}
Advertisement
If `buttonW` is the button of the width, you’re comparing the X–coordinate with the width of the button as an X–coordinate. Did you mean something like this?

if ( mouseX >= buttonX && mouseX < (buttonX + buttonW) &&
     mouseY >= buttonY && mouseY < (buttonY + buttonH) ) {

Why don't you use the data you get with the event?


switch (event.type) {
    case SDL_MOUSEBUTTONDOWN:
        switch (event.button.button) {
            case SDL_BUTTON_LEFT:
                UpdateMousePosition(event.button.x, event.button.y);

that should also be correct wrt position of the click.

As for your problem, did you try checking what all the x/y positions are?

Maybe there different systems use different coordinates, which makes it never works.

Having a look at the values that you actually compare with each other makes such problems clear very easily.

If `buttonW` is the button of the width, you’re comparing the X–coordinate with the width of the button as an X–coordinate. Did you mean something like this?


if ( mouseX >= buttonX && mouseX < (buttonX + buttonW) &&
     mouseY >= buttonY && mouseY < (buttonY + buttonH) ) {

That worked! Thanks a lot!

This topic is closed to new replies.

Advertisement