Is there a way which Image on the window have I clicked in SDL?

Is there a way which Image on the window have I clicked in SDL?

There are many boxes in my game and I want to figure out which box my mouse is hovering on. Is there a surface or something that detects if my mouse is on one of the boxes?

If you are plotting your boxes with something like:

SDL_RenderCopy(renderer, texture, NULL, &dstrect);

you can check whether the mouse coordinates are inside that rectangle with:

SDL_Point mouse;
SDL_GetMouseState(&mouse.x, &mouse.y); 
if (SDL_PointInRect(&mouse, &dstrect))
1 Like

Thanks, that should help!


I used your tip to figure if the mouse is on some image but i also want to check if left mouse button is clicked or not while it’s on the image.

I used this

SDL_Point mouse;
SDL_GetMouseState(&mouse.x, &mouse.y);
if (SDL_PointInRect(&mouse, &destRect) & SDL_BUTTON_LMASK)

but this doesn’t seem to work. Any suggestions?

Instead of use this condition if (SDL_PointInRect(&mouse, &destRect) & SDL_BUTTON_LMASK)
Try this :
To catch event and check:
if (SDL_PointInRect(&mouse, &destRect)&&event.type==SDL_MOUSEBUTTONDOWN)

note that this approach can work with any mouse button press(left,rigth)

You can use the value returned from SDL_GetMouseState(), see the documentation where it says “The current button state is returned as a bitmask”:

SDL_Point mouse;
buttons = SDL_GetMouseState(&mouse.x, &mouse.y); 
if (SDL_PointInRect(&mouse, &dstrect) && (buttons & SDL_BUTTON_LMASK))

As this is testing the button state, not detecting an event, you may not see a quick click (depending to some extent on how often you call SDL_GetMouseState()).

If this is a concern, and you need to detect a button click however short it is, you will need to handle the SDL_MOUSEBUTTONDOWN event.

Thank you so much. It helped. Yes, I want to use callbacks when I click on certain images