Page 1 of 1

Crouch while key pressed issue

Posted: Thu Nov 03, 2005 5:43 pm
by The_Dark_Avenger
Hi everyone,

I've successfully managed to get crouching down (no pun intended) thanks to help from other posts in the forum. However, there's an issue which I don't think has been addressed yet. Here's my code:

bool OnEvent(SEvent event) {
if (event.EventType == irr::EET_KEY_INPUT_EVENT && !event.KeyInput.PressedDown) {
switch(event.KeyInput.Key) {
case irr::KEY_KEY_C: { // crouch
core::vector3df vCrouching = Camera->getPosition();
vCrouching.Y -= 50;
Camera->setPosition(vCrouching);
return true;
}
}
}

The problem is: the crouching happens after I press and release the 'c' key, but I want to crouch when I first press the 'c' key (and stay crouching as long as I hold it) and then when I release the 'c' key I'll stand back up again. I can't figure out how to do that.

Can anyone help?
Thanks.

re:

Posted: Thu Nov 03, 2005 6:29 pm
by Conquistador
You should look in the Wiki, there is code for an event receiver that sets the index representing which key was pressed in a bool array, so that way, you can handle events in the main loop.

Here's the header code I use for the event receiver:

Code: Select all

class CEventReceiver : public IEventReceiver
{
   public:
      CEventReceiver();
      virtual bool OnEvent(SEvent Event);
      bool getKeyState(EKEY_CODE key);
   private:
      bool keys[KEY_KEY_CODES_COUNT];
};
And here's the implementations:

Code: Select all

// Constructor
CEventReceiver::CEventReceiver()
{
   for (int i = 0; i < KEY_KEY_CODES_COUNT; i++)
   {
      keys[i] = false;
   }   
}

// Event handler function
bool CEventReceiver::OnEvent(SEvent Event)
{
   if (Event.EventType == EET_KEY_INPUT_EVENT)
   {
      keys[Event.KeyInput.Key] = Event.KeyInput.PressedDown;
   }
   
   return true;
}

// Get key state
bool CEventReceiver::getKeyState(EKEY_CODE key)
{
   return keys[key];   
}
That way, in the main loop. you can hande key presses like so:

Code: Select all

while (Device->run())
{
    if (Receiver->getKeyState(KEY_UP))
    {
        // Perform action here
    }
}
[/code]

Re: Crouch while key pressed issue

Posted: Thu Nov 03, 2005 8:01 pm
by FlyHigh
The_Dark_Avenger wrote: bool OnEvent(SEvent event) {
if (event.EventType == irr::EET_KEY_INPUT_EVENT && event.KeyInput.PressedDown) {
switch(event.KeyInput.Key) {
case irr::KEY_KEY_C: {
Crouch()
return true;
}
}
if (event.EventType == irr::EET_KEY_INPUT_EVENT && !event.KeyInput.PressedDown) {
switch(event.KeyInput.Key) {
case irr::KEY_KEY_C: {
UnCrouch()
return true;
}
}
}
Just replace Crouch() && UnCrouch() with your actual code etc.