How can I detect the mouse over some object in OpenGL?

I am making a simple 3D game. What is the best way to detect the mouse over an object in a 3D scene?

+3


source to share


1 answer


Actually, I would avoid using these collection methods and just do it mathematically. Create a straight line from the position of the mouse cursor straight to your scene and intersect it with the bounding spheres of each object in the scene. For each boundary sphere it intersects, just check which vertex will be closer to the eye position.

A straight line can be created using this algorithm with z set to 0 respectively.



math::Vec3f windowToObjectf(const math::Vec3f& windowCoord) {
  math::Matrix4f modelViewMatrix;
  math::Matrix4f projectionMatrix;
  std::array <GLint, 4> viewport;
  glGetFloatv( GL_MODELVIEW_MATRIX, modelViewMatrix.data() );
  glGetFloatv( GL_PROJECTION_MATRIX, projectionMatrix.data() );
  glGetIntegerv( GL_VIEWPORT, &viewport.front() );
  math::Vec3f ret(0, 0, 0);
  auto succes = gluUnProject( windowCoord.x , windowCoord.y, windowCoord.z, modelViewMatrix.data(), projectionMatrix.data(), &viewport.front(), &ret.x, &ret.y, &ret.z );
  RASSERT(succes == GL_TRUE);
  GL_RASSERT();
  return ret;
}

      

+2


source







All Articles