Main Page Namespace List Class Hierarchy Compound List File List Namespace Members Compound Members Related Pages
Lesson5: Handling user input (mouse, keyboard). - In this lesson you will learn how mouse and keyboard can be used, to interact with the program. We will modify code from Lesson 1. We will use mouse to move our triangle around and keyboard key SPACE to control movement. Mouse buttons and keyboard keys are handled the same way, so if we would like to use left or right mouse button, we would just change, the name of the key. I suggest you to have a look at sjgui::CKeys class, which is not used inside of the gui widgets but could be very helpful.
- See also:
- sjgui::CWnd::OnKeyUp(), sjgui::CWnd::OnKeyDown(), sjgui::CWnd::OnMouseMove(),sjgui::CKeys
class CSpcWnd : public sjgui::CWnd
{
bool m_ySpacePressed;
float m_fTriX;
float m_fTriY;
public:
CSpcWnd():CWnd(){m_ySpacePressed=false;m_fTriX=0.0f;m_fTriY=0.0f;}
virtual void OnMouseMove(int iX, int iY)
{
if(m_ySpacePressed) return;
m_fTriX=(iX-GetWidth()/2)*0.03f;
m_fTriY=-(iY-GetHeight()/2)*0.03f;
}
virtual void OnKeyDown(int& iKey)
{
if(iKey==SJ_KEY_SPACE)
{
m_ySpacePressed=true;
m_fTriX=0.0f;m_fTriY=0.0f;
}
}
virtual void OnKeyUp(int& iKey){if(iKey==SJ_KEY_SPACE)m_ySpacePressed=false;}
virtual void OnDraw()
{
SET_GL_SIMPLE_PROSPECTIVE;
glTranslatef(m_fTriX,m_fTriY,-10.0f);
glColor3f(0.0f,0.0f,1.0f);
glBegin(GL_TRIANGLES);
glVertex3f( 0.0f, 1.0f, 0.0f);
glVertex3f(-1.0f,-1.0f, 0.0f);
glVertex3f( 1.0f,-1.0f, 0.0f);
glEnd();
}
};
By the way if you do not want parent windows to receive key value, you can change the value of iKey to SJ_KEY_IGNORE.
- Back to Lesson 4. Forward to Lesson 6.
- This is full source code:
#include <sjgui/sjgui.h>
class CSpcWnd : public sjgui::CWnd
{
bool m_ySpacePressed;
float m_fTriX;
float m_fTriY;
public:
CSpcWnd():CWnd(){m_ySpacePressed=false;m_fTriX=0.0f;m_fTriY=0.0f;}
virtual void OnMouseMove(int iX, int iY)
{
if(m_ySpacePressed) return;
m_fTriX=(iX-GetWidth()/2)*0.03f;
m_fTriY=-(iY-GetHeight()/2)*0.03f;
}
virtual void OnKeyDown(int& iKey)
{
if(iKey==SJ_KEY_SPACE)
{
m_ySpacePressed=true;
m_fTriX=0.0f;m_fTriY=0.0f;
}
}
virtual void OnKeyUp(int& iKey){if(iKey==SJ_KEY_SPACE)m_ySpacePressed=false;}
virtual void OnDraw()
{
SET_GL_SIMPLE_PROSPECTIVE;
glTranslatef(m_fTriX,m_fTriY,-10.0f);
glColor3f(0.0f,0.0f,1.0f);
glBegin(GL_TRIANGLES);
glVertex3f( 0.0f, 1.0f, 0.0f);
glVertex3f(-1.0f,-1.0f, 0.0f);
glVertex3f( 1.0f,-1.0f, 0.0f);
glEnd();
}
};
int main(int argc, char* argv[])
{
CSpcWnd SpcWnd;
SpcWnd.PosWnd(20,50,320,240);
if(sjgui::Create("Interactions(SPACE-stops movement)",&SpcWnd))
{
sjgui::GlobalMainLoop();
}
else
printf("Could not create opengl window.\n");
return 0;
}
|
|