Time for action — controlling the model with the arrow keys

Now we are going to add interactivity to the scene by adding the user control to the movements of the model.

  1. The FrameListener needs two new members: one pointer to the node we want to move, and one float indicating the movement speed:
    float _WalkingSpeed;
    Ogre::SceneNode* _node;
    
  2. The pointer to the node is passed to us in the constructor:
    MyFrameListener(Ogre::RenderWindow* win,Ogre::Camera* cam,Ogre::Viewport* viewport,Ogre::SceneNode* node)
    
  3. Assign the node pointer to the member variable and set the walking speed to 50:
    _WalkingSpeed = 50.0f;
    _node = node;
    
  4. In the frameStarted function we need two new variables, which will hold the rotation and the translation the user wants to apply to the node:
    Ogre::Vector3 SinbadTranslate(0,0,0);
    float _rotation = 0.0f;
    
  5. Then we need code to calculate the translation and rotation depending on which arrow key the user has pressed:
    if(_Keyboard->isKeyDown(OIS::KC_UP))
    {
    SinbadTranslate += Ogre::Vector3(0,0,-1);
    _rotation = 3.14f;
    }
    if(_Keyboard->isKeyDown(OIS::KC_DOWN))
    {
    SinbadTranslate += Ogre::Vector3(0,0,1);
    _rotation = 0.0f;
    }
    if(_Keyboard->isKeyDown(OIS::KC_LEFT))
    {
    SinbadTranslate += Ogre::Vector3(-1,0,0);
    _rotation = -1.57f;
    }
    if(_Keyboard->isKeyDown(OIS::KC_RIGHT))
    {
    SinbadTranslate += Ogre::Vector3(1,0,0);
    _rotation = 1.57f;
    }
    
  6. Then we need to apply the translation and rotation to the node:
    _node->translate(SinbadTranslate * evt.timeSinceLastFrame * _WalkingSpeed);
    _node->resetOrientation();
    _node->yaw(Ogre::Radian(_rotation));
    
  7. The application itself also needs to store the node pointer of the entity we want to control:
    Ogre::SceneNode* _SinbadNode;
    
  8. The FrameListener instantiation needs this pointer:
    _listener = new MyFrameListener(window,camera,viewport,_SinbadNode);
    
  9. And the createScene function needs to use this pointer to create and store the node of the entity we want to move; modify the code in the function accordingly:
    _SinbadNode = _sceneManager->getRootSceneNode()->createChildSceneNode();
    _SinbadNode->attachObject(sinbadEnt);
    
  10. Compile and run the application. You should be able to move the entity with the arrow keys:
    Time for action — controlling the model with the arrow keys

What just happened?

We added entity movement using the arrow keys in the FrameListener. Now our entity floats over the plane like a wizard.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.157.54