Crouch while key pressed issue

If you are a new Irrlicht Engine user, and have a newbie-question, this is the forum for you. You may also post general programming questions here.
Post Reply
The_Dark_Avenger
Posts: 2
Joined: Thu Nov 03, 2005 1:28 pm

Crouch while key pressed issue

Post 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.
Conquistador
Posts: 340
Joined: Wed Sep 28, 2005 4:38 pm
Location: Canada, Eh!

re:

Post 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]
FlyHigh
Posts: 111
Joined: Wed Mar 23, 2005 12:05 am

Re: Crouch while key pressed issue

Post 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.
Post Reply