Game Development Community

Checking if player is in view...

by Clark Kromenaker · in Torque Game Engine · 11/22/2005 (10:49 am) · 3 replies

Hi,

I was wondering how I might check to see if the player object is in the camera's field of view. If the player isn't, and the user clicks to move him somewhere, I want the player to warp to a few units behind the camera and go from there; it makes for less waiting around when traveling large distances.

#1
11/22/2005 (11:39 am)
Get a vector for the camera direction
Get a vector from camera to player:

eg. playervec = cameraPos - playerPos

Now check the angle between the two vectors. If it's > half the camera field of view then the player is offscreen and you need to call setTransform on the player to warp him to where you want.

There are many formulas for angles between vectors. This one works well.

F32 Angle = mAcos(mDot( cameraVec, cam2playerVec) );
#2
11/22/2005 (11:50 am)
Thanks!

I'll be sure to try this out!
#3
03/23/2006 (7:58 pm)
Sorry to post in an old thread folks,
but i just thought i'd point out for the benefit of future trawlers that if you're doing this a lot,
like say for every player every frame or something,
it's somewhat more efficient to do this instead:

F32 cosHalfFOV = mCos(cameraFOV * 0.5); // consider storing this in camera
F32 dot = mDot(cameraVec, cam2playerVec));
if (dot < 0)
  thePlayerIsBehindTheCamera();
else {
   // if cam2PlayerVec wasn't already normalized
   // (which it doesn't need to be for the code so far, so don't do it unless you've got a good reason)
   // then normalize the dot-product now like this:
   // (assumes cameraVec *is* normalize)
   dot /= cam2playerVec.length());
   if (dot < cosHalfFOV)
      thePlayerIsOutOfView();
}

- basically this saves you per player:
* mAcos(), always, if you store cos(fov) in the camera.
* one divide and one square root if the player is behind the camera

note the less-than/greater-than comparison is reversed from Duncan's code. both are correct.

edit1: i originally wrote this assuming that cameraVec was not normalized, which allowed for more optimization, but i realized that was a silly assumption. cameraVec is sure to be normalized by default.

edit2: i guess you *could* store cosHalfFOVSquared instead of cosHalfFOV, and then "normalize" dot with cam2playerVec.lengthSquared() and save one more sqaure root.. yeah ? - wait, no, because yr dividing by the length/lengthSquared, not multiplying. never mind.