Skip to content

Instantly share code, notes, and snippets.

@pnegri
Created March 22, 2014 15:55
Show Gist options
  • Save pnegri/9709391 to your computer and use it in GitHub Desktop.
Save pnegri/9709391 to your computer and use it in GitHub Desktop.
Diablo like mouse character lookAt
void Player::lookAtFromMouse() {
if (m_pCharacter == NULL) return;
//o-- Get Mouse Position
CEGUI::Vector2f absMouse = CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor().getPosition();
CEGUI::Vector2f relativeMouse = CEGUI::CoordConverter::screenToWindow(
*CEGUI::System::getSingleton().getDefaultGUIContext().getRootWindow(),
absMouse
);
//o-- Get Screen Coordinates
R32 screenX = relativeMouse.d_x;
R32 screenY = relativeMouse.d_y;
//o-- Get Window Size
R32 windowWidth = CEGUI::CoordConverter::screenToWindowX(
*CEGUI::System::getSingleton().getDefaultGUIContext().getRootWindow(),
CEGUI::UDim(1,0)
);
R32 windowHeight = CEGUI::CoordConverter::screenToWindowY(
*CEGUI::System::getSingleton().getDefaultGUIContext().getRootWindow(),
CEGUI::UDim(1,0)
);
Ogre::SceneManager *m_pSceneMgr = Ogre::Root::getSingletonPtr()->getSceneManager("SceneManager");
//o-- Assume we have a valid SceneManager
if (!m_pSceneMgr) return;
Ogre::Camera *m_pCamera = m_pSceneMgr->getCamera("Camera");
//o-- Assume we have a valid Camera
if (!m_pCamera) return;
//o-- Create a Ray
Ogre::Ray mouseRay = m_pCamera->getCameraToViewportRay(
screenX / windowWidth,
screenY / windowHeight
);
//o-- Create a Plane in Y Axis with Origin as Character Position
Ogre::Plane characterPlane(Ogre::Vector3::UNIT_Y, m_pCharacter->getPosition() );
//o-- Get an intersection point from Screen to that Plane
std::pair<bool, Ogre::Real> intersectionResult = mouseRay.intersects(characterPlane);
if (intersectionResult.first) {
//o-- Use the intersection point of the plane to calculate the rotation for the character
Ogre::Vector3 intersectionInWorldCoord = mouseRay.getPoint( intersectionResult.second );
Ogre::Vector3 lookingAt = intersectionInWorldCoord - m_pCharacter->getPosition();
Ogre::Vector3 facingTo = Ogre::Vector3::NEGATIVE_UNIT_Z;
lookingAt.y = 0;
facingTo.y = 0;
Ogre::Real mDistance = lookingAt.normalise();
Ogre::Quaternion newOrientation = facingTo.getRotationTo( lookingAt );
m_pCharacter->setOrientation( newOrientation );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment