SDL2 button click registering many hundreds of times...

Hi guys, I'm trying to make it so that when the user clicks on a sprite it runs a function. However, everytime I click it runs the function a couple of hundred times...

I've tried a lot of thing such as making booleans that become false on every loop or or using SDL_GetTicks() to try to control the time but nothing seems to be working...

Someone help please?
Here is my code.

1
2
3
4
5
6
7
8
9
10
11
12
13

if (heart->CheckBounds(mousePosX, mousePosY))//checks whether mouse is over sprite
	{
		if (events->type == SDL_MOUSEBUTTONDOWN)
		{
			if (events->button.button == SDL_BUTTON_LEFT)
			{
			    Character_Visual->CCreation_Add_HP(); 
                            //the above function executes about a hundred times
			}
		}
	}


1
2
3
4
5
6
7

void character::CCreation_Add_HP()
{
	health_total += HP_CONS;
	health_current = health_total;
}


Can anyone explain why this is happening or how I can fix it?
If i remember correctly SDL will send\trigger that event time in your loop when the button is down. the thing is you could loop through 1000 times int the time(0.1sec) it takes you to release the button.

try using SDL_MOUSEBUTTONUP so you trigger on release. this gets fired just once
Last edited on
I actually solved this, thanks for your reply though.

Here is my solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
unsigned int lastTime = 0, currentTime;
int Speed = 250; //will wait 250 milliseconds before executing statement if applicable



if (heart->CheckBounds(mousePosX, mousePosY)) //simple check hover
{
	if (events->type == SDL_MOUSEBUTTONDOWN) //mouse button down
	{
		if (events->button.button == SDL_BUTTON_LEFT)
		{
			currentTime = SDL_GetTicks();
			if (currentTime > lastTime + Speed)
			{
				index = Speed; //this line isnt necessary
				enlarge = true; //this line isnt necessary
				Character_Visual->CCreation_Manage_HP(true);
				Character_Visual->Manage_Attribute_Point(true);
				lastTime = currentTime; //necessary
			}
		}
         }
}
Last edited on
Topic archived. No new replies allowed.