Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I want to be able to click on a monster to walk to him and start attacking him. The part that doesnt make sense to me is the conversion between the mouse position, and the actual terrain position. There are camera angles to worry about, heights, seperate terrains, how is this done???? I am using Java LWJGL and rendering with OpenGL 4.4

share|improve this question
    
You can start by googling "3D picking", it is the keyword you are looking for. –  wondra Jan 21 at 15:58

1 Answer 1

Here's how I convert screen point to a ray in C++, but should be easily converted to Java:

void Scene::ScreenPointToRay( int screenX, int screenY, Vec3& outRayOrigin, Vec3& outRayTarget ) const
{
    const float aspect = Screen::Height() / (float)Screen::Width();
    const float halfWidth = (float)(Screen::Width()) * 0.5f;
    const float halfHeight = (float)(Screen::Height()) * 0.5f;
    const float fov = activeCamera->FOV() * (MathUtil::pi / 180.0f);

    // Normalizes screen coordinates and scales them to the FOV.
    const float dx = std::tan( fov * 0.5f ) * (screenX / halfWidth - 1.0f) / aspect;
    const float dy = std::tan( fov * 0.5f ) * (screenY / halfHeight - 1.0f);

    Matrix44 invView;
    Matrix44::Invert( activeCamera->ViewMatrix(), invView );

    const float farp = activeCamera->FarClipPlane();

    outRayOrigin = activeCamera->GetPosition();
    outRayTarget = -Vec3( -dx * farp, dy * farp, farp );

    Matrix44::TransformPoint( outRayTarget, invView, &outRayTarget );
}

Then you just test a ray-AABB intersection with your objects' AABBs.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.