• Advertisement
Sign in to follow this  

SDL2 Mouse coordinates won't work

This topic is 458 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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);
 
}

Share this post


Link to post
Share on other sites
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) ) {

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites

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!

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement