Page 1 of 1

Is keyPressed working if the key was pressed seconds before?

Posted: Mon Sep 19, 2011 11:06 am
by siegmund
Hi,
I'm trying to write just a simple script to detect if a key was pressed.
The script needs i.e 5 seconds for a while loop. If I press and hold the key, it is detected, but not if the key is currently not pressed while calling keyPressed.
i.e.

Code: Select all

...
setting_DoLooting = 1;
while(true) do
		cprintf(cli.yellow, "x: %s\n\r", x);	
		x=x+1;
		if( keyPressed(key.VK_NUMPAD4) ) then	
			if (setting_DoLooting == 1) then
				TRACE(50, cli.red, "stop lootingn\r");	
				setting_DoLooting = 0
			else
				TRACE(50, cli.green, "LOOT = ON\n\r");	
				setting_DoLooting = 1
			end
		end
		yrest(1000);
	end
if the script sleeps (yrest) and the button is pressed, nothing is being traced.
If holding the key the next loop and call of (keyPressed) is detected.
Can you please tell me what is wrong?
Thanks
Siegmund

Re: Is keyPressed working if the key was pressed seconds bef

Posted: Tue Sep 20, 2011 1:02 am
by Administrator
No. keyPressed() only returns true if the key is currently pressed down when the function is called. In your code, you are only checking maybe 5 times throughout potentially millions of cycles.

Do this, instead:

Code: Select all

local do_looting = true;
local startTime = getTime();
while( deltaTime(getTime(), startTime)) < 5000 ) do
  if( keyPressed(key.VK_NUMPAD4) ) then
    do_looting = false;
  end

  yrest(1);
end

if( do_looting ) then
  TRACE(50, cli.green, "LOOT = ON\n\r"); 
else
  TRACE(50, cli.red, "stop lootingn\r"); 
end

Re: Is keyPressed working if the key was pressed seconds bef

Posted: Tue Sep 27, 2011 1:14 pm
by siegmund
Hi,
thank you that is working. Instead of yrest I'm using that code, so the chance of getting caught the key is bigger.
I thought there must be a function to get the next key in the queue.
Thanks
Siegmund