CEGUI In Practice - Auto Repeat Key

From CEGUI Wiki - Crazy Eddie's GUI System (Open Source)
Revision as of 17:18, 24 March 2011 by Avengre (Talk | contribs)

Jump to: navigation, search

Auto Key

This is an example of how to implement an AutoRepeatKey using OIS. Although this uses OIS the concept is likely similar to other Input libraries, so you should be able to adapt it.

To implement this, you would have to define repeatKey in your own class (And inherit AutoRepeatKey) to do what you want when the repeatKey is triggered. For example.

class MyKeyInput : public AutoRepeatKey
{
protected:
  repeatKey(OIS::KeyCode a_nKey, unsigned int a_nChar)
  {
    CEGUI::System::getSingletonPtr()->injectKeyDown(a_nKey.key);
    CEGUI::System::getSingletonPtr()->injectKeyUp(a_nKey.key);
    CEGUI::System::getSingletonPtr()->injectChar(a_nKey.text);
  }
}


The Header File

#pragma once
 
#include <OIS.h>
 
class AutoRepeatKey {
private:
 
    OIS::KeyCode m_nKey;
    unsigned int m_nChar;
 
    float m_fElapsed;
    float m_fDelay;
 
    float m_fRepeatDelay;
    float m_fInitialDelay;
 
protected:
 
    virtual void repeatKey(OIS::KeyCode a_nKey, unsigned int a_nChar) = 0;
 
public:
 
    AutoRepeatKey(float a_fRepeatDelay = 0.035f, float a_fInitialDelay = 0.300f);
 
    void begin(const OIS::KeyEvent &evt);
 
    void end(const OIS::KeyEvent &evt);
 
    void update(float a_fElapsed); // Elapsed time in seconds
};

The CPP File

#include "AutoRepeatKey.h"
 
AutoRepeatKey::AutoRepeatKey(float a_fRepeatDelay, float a_fInitialDelay):
    m_nKey(OIS::KC_UNASSIGNED),
    m_fRepeatDelay(a_fRepeatDelay),
    m_fInitialDelay(a_fInitialDelay)
{}
 
void AutoRepeatKey::begin(const OIS::KeyEvent &evt) {
    m_nKey = evt.key;
    m_nChar = evt.text;
 
    m_fElapsed = 0;
    m_fDelay = m_fInitialDelay;
}
 
void AutoRepeatKey::end(const OIS::KeyEvent &evt) {
    if (m_nKey != evt.key) return;
 
    m_nKey = OIS::KC_UNASSIGNED;
}
 
void AutoRepeatKey::update(float a_fElapsed) {
    if (m_nKey == OIS::KC_UNASSIGNED) return;
 
    m_fElapsed += a_fElapsed;
    if (m_fElapsed < m_fDelay) return;
 
    m_fElapsed -= m_fDelay;
    m_fDelay = m_fRepeatDelay;
 
    do {
        repeatKey(m_nKey, m_nChar);
 
        m_fElapsed -= m_fRepeatDelay;
    } while (m_fElapsed >= m_fRepeatDelay);
 
    m_fElapsed = 0;
}

References

http://www.ogre3d.org/tikiwiki/Auto+Repeat+Key+Input&structure=Cookbook