Showing posts with label RaySceneQuery. Show all posts
Showing posts with label RaySceneQuery. Show all posts

Wednesday, August 15, 2007

Ogre: Object Picking

To create the effect that we are clicking on an object in Ogre we use a ray query. The ray is traced from the place were the mouse is and then goes perpendicularly to the screen. The query will result in a list of objects that were in the ray's way. An object is in the way, if its bounding box is in the way.

fig.1 - In this example if we click inside
the box that contains the Ogre's Head
it will play a sound

This is the code that I used, first we must declare a RaySceneQuery *mRaySceneQuery as a global, and then initialize it:

mRaySceneQuery = mSceneMgr->createRayQuery(Ray());
then in the mouse clicking event we make the following sorted query and try to see if the touched the Entity named "Head" :

bool GuiScene::mousePressed(const OIS::MouseEvent &arg, OIS::MouseButtonID id)
{
OgreApplication::mousePressed( arg, id );

mGUISystem->injectMouseButtonDown(convertOISMouseButtonToCegui(id));


CEGUI::Point mousePos = CEGUI::MouseCursor::getSingleton().getPosition();
Ray mouseRay = mCamera->getCameraToViewportRay(mousePos.d_x/float(mWindow->getWidth()), mousePos.d_y/float(mWindow->getHeight()));

mRaySceneQuery->setRay(mouseRay);
mRaySceneQuery->setSortByDistance(true);

// Execute query
RaySceneQueryResult &result = mRaySceneQuery->execute();
RaySceneQueryResult::iterator itr;

// Get results, create a node/entity on the position
for ( itr = result.begin(); itr != result.end(); itr++ )
{
if (itr->movable && itr->movable->getName() == "Head")
{
soundMgr->StopSound( &jaguarSoundChannel );
soundMgr->PlaySound( jaguarSound, headNode, &jaguarSoundChannel );
break;
} // if
}
return true;
}
Now if you touch the bounding box a jaguar sound will be heard.