In my game I have an action performed whenever the left mouse button is pressed. Is there a way to restrict how fast the player can click? Right now the event will trigger as many times as they can press the button, but I would like to put a cap on that so that the action can't be spammed so many times per second.
I'm afraid I'm not familiar with the game engine side of Blender, but the principle would be to have a timer (or other condition) that gets checked on each mouse click. If the timer has expired (or other condition is met), then the click triggers whatever action it's liked to, and resets the timer. If the timer has not yet expired, then the click is ignored.
If you doing some scripting, then you want to use
lastClickTime = time.time() to store the time of the first click. Then use
time.time() - lastClickTime > 1 as your condition.
Time.time() will give you the current time (in seconds since 1970). If the current time minus your stored time is greater than 1, then at least one second has elapsed.
So (SUUUUPER pseudo-code... this won't actually do anything):
#somewhere else you initialized lastClickTime to zero OnClick(): if time.time() - lastClickTime > 1: #do the click thing and... lastClickTime = time.time() else: #do nothing..
So you handle every single click you get, it's just that you don't have to DO anything when you get a click. If your timer has expired, do what the click is supposed to do and reset the timer. If not, then just do nothing.
time() is a member of the
time external module, so you have to import the
time module in order to use the
Time.time() only gives 1 second resolution. There are ways to get sub-second resolution, but the principle is the same. You'll just use getRealtimeClock() or something like that, instead of time.time().
It is also possible to use timer properties. After playing around with Cobra's method, I found that this works reliably and allows you to use the full accuracy of the timer property.
Fire = cont.sensors["Fire"] fireRate = own["fireRate"] #adjust the value to be >= to your liking if fireRate >= 0 and Fire.positive: # Do not set fireRate = -1 That does not work. own["fireRate"] = -1 #anything you want to limit the action of
You can create a timer property in the logic editor panel and name it whatever you want. Say - "dTimer". Now when your game runs it will run. And in your python script do like this -
if mouse_click.positive and own["dTimer"] >= 2: #2 seconds #do whatever you want own["dTimer"] = 0 #Reset the counter to zero
As soon as you reset it to 0, it will start the counting from 0 again. You can debug the property if you want.