My goal is to have a red square in the middle of a window and when I press it, it should give me my mouse position as long as I am holding the mouse button down. When I release the mouse button it should not give me the coordinates any longer. The problem is that in my code, it gives me the correct position, but then says the mouse position is (0, 0) maybe 300 times. Then it gives me the correct updated position again, and then 300 times (0,0). The output can look like this:
Mouse press detected!
Mouse position is (0, 0)
Mouse position is (0, 0)
Mouse position is (0, 0)
Mouse position is (0, 0)
...
Mouse position is (0, 0)
Mouse position is (0, 0)
Mouse position is (391, 207)
Mouse released!
This was with one click with the mouse button. Why is this? Here is my code:
#include <stdio.h>
#include <SDL.h>
#define WIDTH 760
#define HEIGHT 480
void moveRectangle(SDL_Event myEvent, SDL_Rect* pButton, SDL_Renderer* pRenderer) {
if (myEvent.motion.x >= 330 && myEvent.motion.x <= 430 && myEvent.motion.y >= 190 &&
myEvent.motion.y <= 290) {
while (myEvent.type != SDL_MOUSEBUTTONUP) {
SDL_PollEvent(&myEvent);
printf("Mouse position is (%d, %d)\n", myEvent.motion.x, myEvent.motion.y);
}
printf("Mouse released!\n");
}
}
int main(int argc, char** args) {
int running = 1;
SDL_Window* window;
SDL_Rect myButton;
SDL_Renderer* myRenderer;
SDL_Event event;
myButton.x = 330;
myButton.y = 190;
myButton.w = 100;
myButton.h = 100;
SDL_Init(SDL_INIT_VIDEO);
window = SDL_CreateWindow("Events", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
WIDTH, HEIGHT, 0);
myRenderer = SDL_CreateRenderer(window, -1, 0);
SDL_SetRenderDrawColor(myRenderer, 255, 0, 0, 0);
SDL_RenderFillRect(myRenderer, &myButton);
SDL_RenderPresent(myRenderer);
while (running) {
SDL_PollEvent(&event);
switch (event.type) {
case SDL_MOUSEBUTTONDOWN: printf("Mouse press detected!\n");
moveRectangle(event, &myButton, myRenderer); break;
case SDL_MOUSEBUTTONUP: printf("Mouse release detected!\n"); break;
case SDL_MOUSEMOTION: printf("Mouse movement detected!\n"); break;
case SDL_QUIT: printf("Exiting...\n"); running = 0; break;
}
}
SDL_DestroyRenderer(myRenderer);
SDL_Quit();
return 0;
}