Sample03
简介:
键盘,鼠标事件的演示。
键盘、鼠标是游戏中主要的输入设备,往往会要求获取当前鼠标对象、鼠标坐标等。该例展示了OGF框架的事件处理机制,并介绍如何运用。
1.在GameBody.h文件重载OnMouseMove(),OnMouseClick(),OnMouseIn(),OnMouseOut(),OnMouseOver(),OnKeyPass()事件.
2.在GameBody.cpp文件底部添加以下代码:
//鼠标移动
bool CMyGameBody::OnMouseMove(float x, float y){
char szText[128];
sprintf(szText, "Mouse Move:x=%f, y=%f", x, y);
IGameObject* pGameObject = (IGameObject*)m_pCurrentSection->GetGameView()->GetObject("default\\default\\Text");
//查询接口方法1
IGameObjectText* pIGOText = (IGameObjectText*)pGameObject->QueryInterface(IID_IGameObjectText, VER_IGameObjectText);
pIGOText->SetText(szText);
return true;
}
//鼠标点击
bool CMyGameBody::OnMouseClick(CGameScene* pGameScene, CGameLayer* pGameLayer, IGameObject* pGameObject, int nType, int nKey){
char szText[128];
sprintf(szText, "Object:%s Clicked", pGameObject->GetObjectName());
//查询接口方法2
IGameObjectText* pIGOText = GET_OBJECTPTR_INTERFACE(pGameObject, IGameObjectText);
pIGOText->SetText(szText);
return true;
}
//鼠标移入
bool CMyGameBody::OnMouseIn(CGameScene* pGameScene, CGameLayer* pGameLayer, IGameObject* pGameObject){
char szText[128];
sprintf(szText, "Mov In:%s", pGameObject->GetObjectName());
//查询接口方法2
IGameObjectText* pIGOText = GET_OBJECTPTR_INTERFACE(pGameObject, IGameObjectText);
pIGOText->SetText(szText);
return true;
}
//鼠标移出
bool CMyGameBody::OnMouseOut(CGameScene* pGameScene, CGameLayer* pGameLayer, IGameObject* pGameObject){
char szText[128];
sprintf(szText, "Mov Out:%s", pGameObject->GetObjectName());
//查询接口方法2
IGameObjectText* pIGOText = GET_OBJECTPTR_INTERFACE(pGameObject, IGameObjectText);
pIGOText->SetText(szText);
return true;
}
//鼠标移过
bool CMyGameBody::OnMouseOver(CGameScene* pGameScene, CGameLayer* pGameLayer, IGameObject* pGameObject){
char szText[128];
sprintf(szText, "Mov Over:%s", pGameObject->GetObjectName());
//查询接口方法2
IGameObjectText* pIGOText = GET_OBJECTPTR_INTERFACE(pGameObject, IGameObjectText);
pIGOText->SetText(szText);
return true;
}
//键盘事件
bool CMyGameBody::OnKeyPass(int nType, int nKey, char cChar){
char szText[128];
sprintf(szText, "Type:%d Key:%d Char:%c", nType, nKey, cChar);
IGameObject* pGameObject = (IGameObject*)m_pCurrentSection->GetGameView()->GetObject("default\\default\\Text");
//查询接口方法1
IGameObjectText* pIGOText = (IGameObjectText*)pGameObject->QueryInterface(IID_IGameObjectText, VER_IGameObjectText);
pIGOText->SetText(szText);
return true;
}
3.编译并运行项目
运行结果:
运行后在屏幕中心显示"None"字样,当任意键点击后会显示:"Key:xx",当鼠标点击后会显示:"Mouse Clicked"等.在OGF框架中,键盘,鼠标的事件触发后会分发至CGameBody类的OnMouseMove(),OnMouseClick(),OnMouseIn(),OnMouseOut(),OnMouseOver(),OnKeyPass()事件中,游戏可在这些事件中进行回调处理