Game Development Community

dev|Pro Game Development Curriculum

Advanced Camera

by Thomas \"Man of Ice\" Lund · 04/03/2008 (11:57 am) · 480 comments

Download Code File

Description
Over time a lot of people have released camera resources, but some do not work anymore, others are hard to implement etc.

I've tried to assemble a single class to add to the engine that implements them all in one go using the same basic architecture. This enables minimum code bloat and makes it way easier to keep the code up to date.

Change log
March 3rd, 2005
Manoel made some changes to the orbit camera. Works in multiplayer now and is much nicer by using console variables

February 3rd, 2005
Fixed small big in interpolation.

February 2nd, 2005
Major changes in this one with various contributors.
* Static camera mode
* Smooth interpolation and transition between modes
* Smooth orbit camera!!!
* Vertical freedom mode when in 3rd person
* Better collision check with terrain and interiors
* Mouse control of orbit camera
* Totally reworked codebase and lots of cleanups. Much more readable now

Manoel Neto contributed the new orbit camera and the interpolation
Zik Saleeba contributed the vertical freedom mode and better collision check

Thanks a lot!!!!

I have marked changes with a New in the text below for those who upgrade

January 23rd, 2005
Minor changes. Larger update soon with new functionality
* Now takes GameBase objects as target + player
* Removed debug message in orbit camera
* Added getters for player and target object

June 25th, 2004
Updated the bindings for orbit camera. Switched left+right.

June 23rd, 2004
A big thanks to Stephen Zepp for contributing with an orbit camera mode. Its added to the resource, and is perfect for RTS games and action adventures. It allows for a camera to rotate around a user as if placed on a sphere. The user can zoom in/out, rotate and tilt the camera.

June 9th, 2004
Added getter/setter for the 3 offset values accessible from script
Added a "follow terrain" mode for the third person camera, so the camera follows the terrain slope - doesnt work perfectly

April 5th, 2004
All camera modes now use a raycast to not get hidden behind terrain or interiors

April 3rd, 2004
This release is the first release, and might not be as "advanced" as the author would like, but its time to release it and get some feedback to further enhance it down the road.

Camera Modes Implemented
The resource currently implements the following camera systems:
* Track Mode
This is the same as the tracking camera resource posted by Cory Osborn. A stationary camera tracks the player and keeps him in focus.

* New Static Mode
Camera stays in its position and rotation. Useful for e.g. scene based adventures where the camera doesnt move with the players

* Third Person Mode
The camera is placed at an offset behind the player and rotates with the player. The camera itself is not controllable

* Third Person Track Mode
The camera is placed in third person mode but rotated so it always looks at a specified object, but with the player in full view

* God View
Camera is placed at an offset from the player and does not rotate with the player. This is your typical "Diablo" kind of camera.

* New Orbit Mode
Camera is placed on a sphere looking at the player, and can rotate/tilt and zoom controlled by the player. There are bindings to the mouse when in single player game (server and client on same machine)

Movie
Here is a small movie displaying the different camera modes (3 MB)
www.codejar.com/advancedcamerademo.wmv

How to Add
First off all you need to take the attached advancedCamera.cc/h files and add to engine\game and add them to the project.

Then you need to expose the camera object in GameConnection as described in Cory's resource www.garagegames.com/index.php?sec=mg&mod=resource&page=view&qid=4720

I took the liberty to paste the relevant parts in here too

Exposing mCameraObject
The first thing you want to do is add console method's to access the GameConnection setCameraObject/getCameraObject methods. I added these to GameConnection.cc right after the console method for getControlObject:

ConsoleMethod( GameConnection, setCameraObject, bool, 3, 3, "(ShapeBase object)")
{
   ShapeBase *gb;
   if(!Sim::findObject(argv[2], gb))
      return false;

   object->setCameraObject(gb);
   return true;
}

ConsoleMethod( GameConnection, getCameraObject, S32, 2, 2, "")
{
   argv;
   SimObject* cp = object->getCameraObject();
   return cp ? cp->getId(): 0;
}

ConsoleMethod( GameConnection, clearCameraObject, void, 2, 2, "")
{
   object->setCameraObject(NULL);
}

After playing around with it, I also found you need some adjustments to the setCameraObject and setControlObject methods - otherwise the client connection can screw things up if you bounce the same object from your connection's control to camera or vice versa. Here is my GameConnection::setControlObject:

void GameConnection::setControlObject(ShapeBase *obj)
{
   if(mControlObject == obj)
      return;

   if(mControlObject && mControlObject != mCameraObject) 
      mControlObject->setControllingClient(0);
   
   if(obj)
   {
      // Nothing else is permitted to control this object.
      if (ShapeBase* coo = obj->getControllingObject())
         coo->setControlObject(0);
      if (GameConnection *con = obj->getControllingClient()) 
      {
         if (this != con) 
         {
            // was it controlled via camera or control?
            if (con->getControlObject() == obj)
               con->setControlObject(0);
            else
               con->setCameraObject(0);
         }
      }

      // We are now the controlling client of this object.
      obj->setControllingClient(this);
   }

   // Okay, set our control object.
   mControlObject = obj;
   if (mCameraObject.isNull())
      setScopeObject(mControlObject);
}


and here is my GameConnection::setCameraObject:

void GameConnection::setCameraObject(ShapeBase *obj)
{
   if(mCameraObject == obj)
      return;

   if(mCameraObject && mCameraObject != mControlObject) 
      mCameraObject->setControllingClient(0);
   
   if (obj) {
      // Nothing else is permitted to control this object.
      if (ShapeBase* coo = obj->getControllingObject())
         coo->setControlObject(0);
      if (GameConnection *con = obj->getControllingClient()) 
      {
         if (this != con) 
         {
            // was it controlled via camera or control?
            if (con->getControlObject() == obj)
               con->setControlObject(0);
            else
               con->setCameraObject(0);
         }
      }

      // We are now the controlling client of this object.
      obj->setControllingClient(this);
   }

   // Okay, set our camera object.

   mCameraObject = obj;

   if (mCameraObject.isNull()) {
      setScopeObject(mControlObject);
   } else {
      setScopeObject(mCameraObject);
      // if this is a client then set the fov and active image
      if(isServerConnection())
      {
         F32 fov = mCameraObject->getDefaultCameraFov();
         GameSetCameraFov(fov);
      }
   }
}

Camera read/write packets
None of this will work unless the client copy of the camera object gets packets updated. Here we're going to modify GameConnection::readPacket and GameConnection::writePacket.

In GameConnection::readPacket, find this block of code:

if (bstream->readFlag())
      {
         S32 gIndex = bstream->readInt(10);
         ShapeBase* obj = static_cast<ShapeBase*>(resolveGhost(gIndex));
         setCameraObject(obj);
      }
      else
         setCameraObject(0);

and change it to

if (bstream->readFlag()) 
      {
         S32 gIndex = bstream->readInt(NetConnection::GhostIdBitSize);
         ShapeBase* obj = static_cast<ShapeBase*>(resolveGhost(gIndex));
         setCameraObject(obj);
         obj->readPacketData(this, bstream);
      }
      else
         setCameraObject(0);


In GameConnection::writePacket, find this block of code:

if (!mCameraObject.isNull() && mCameraObject != mControlObject)
      {
         gIndex = getGhostIndex(mCameraObject);
         if (bstream->writeFlag(gIndex != -1))
            bstream->writeInt(gIndex, 10);
      }
      else
         bstream->writeFlag( false );

and change it to:

if (!mCameraObject.isNull() && mCameraObject != mControlObject) 
      {
         gIndex = getGhostIndex(mCameraObject);
         if (bstream->writeFlag(gIndex != -1)) {
            bstream->writeInt(gIndex, NetConnection::GhostIdBitSize);
            mCameraObject->writePacketData(this, bstream);
         }
      }
      else
         bstream->writeFlag( false );

Recompile it all and the engine is ready to go.

Script

To use the camera you need to follow some of Corys resource, but with some modifications. Datablock and naming has changed

First, add a datablock for the tracking camera to /fps/server/scripts/camera.cs:

...
datablock AdvancedCameraData(AdvCameraData)
{
   lookAtOffset = "0 0 2";
   thirdPersonOffset = "0 -3 3";
   godViewOffset = "0 -20 20";
   maxTerrainDiff = 2;
   orbitMinMaxZoom = "5 100";
   orbitMinMaxDeclination = "10 80";
   damping = 0.25;

};
...

Next, add it to the connection just like is currently done with the base camera class. Add this inside GameConnection::onClientEnterGame (/fps/server/scripts/game.cs), right after %this.camera is set up:

...
   // create advanced camera
      %this.advCamera = new AdvancedCamera() {
      dataBlock = AdvCameraData;
   };
   MissionCleanup.add(%this.advCamera);
   %this.advCamera.scopeToClient(%this);
...


We'll need to clean it up after the client leaves the game, so add this to GameConnection::onClientLeaveGame

...
   if (isObject(%this.advCamera))

      %this.advCamera.delete();
...


We need to tell it what to do when added and assign the connection's camera object, so add this to the end of GameConnection::createPlayer:

...
  // We set the camera system to run in 3rd person mode around the %player
  %this.advCamera.setPlayerObject(%player);
  %this.advCamera.setThirdPersonMode();
  %this.advCamera.setFollowTerrainMode(false);
  %this.advCamera.setVerticalFreedomMode(false);
  %this.setCameraObject(%this.advCamera);
...


And we'll want to unhook it when the player dies. Insert this at the beginning of GameConnection::onDeath:

...
   // clear connections camera
   %this.advCamera.clearPlayerObject();
   %this.advCamera.clearTargetObject();
   %this.clearCameraObject();
...

The last thing to know, is if you're in first-person mode, GameConnection automatically uses the control object to render the engine rather than the camera object. So if you don't see this working when you first enter a mission, toggle out of first-person.

Orbit mode
To use the orbit camera, one needs to add some key binds to manipulating the camera.

All you need to do, is add the following to your client\config.cs or better to your client\scripts\default.bind.cs

//------------------------------------------------------------------------------
// Advanced Camera Movement
//------------------------------------------------------------------------------

$cameraYawSpeed = -100.0;
$cameraPitchSpeed = -50.0;
$cameraZoomSpeed = -5.0;

function rotateCameraHorizontal(%val)
{
     $advCamera::Yaw = getMouseAdjustAmount(%val)*$cameraYawSpeed ;
}

function rotateCameraVertical(%val)
{
     $advCamera::Pitch = getMouseAdjustAmount(%val)*$cameraPitchSpeed;
}

function zoomCamera(%val)
{
     $advCamera::Zoom = getMouseAdjustAmount(%val)*$cameraZoomSpeed;
}

moveMap.bind( mouse, xaxis, rotateCameraHorizontal);
moveMap.bind( mouse, yaxis, rotateCameraVertical );
moveMap.bind( mouse, zaxis, zoomCamera );

Remember to comment out the mouse commands for the player movement, as these are overwritten by the orbit camera controls
//moveMap.bind( mouse, xaxis, yaw );
//moveMap.bind( mouse, yaxis, pitch );

Script API
To use the different camera modes you can use the following API
Selecting the camera mode is done with e.g.:
%this.advCamera.setTrackMode();
  %this.advCamera.setThirdPersonMode();
  %this.advCamera.setThirdPersonTargetMode();
  %this.advCamera.setGodViewMode();
  %this.advCamera.setOrbitMode();
  %this.advCamera.setStaticMode();

Prior to calling the above modes you have to set the PlayerObject using
setPlayerObject();

To use the 3rd person target mode you also need to set a TargetObject using
setTargetObject();

To use the static or tracking camera you need to set the position the camera should be placed suing
setCameraPosition(Point3F pos);

To use the follow terrain mode in 3rd person you give a bool to
setFollowTerrainMode(true/false);

To use the vertical freedom mode in 3rd person you give a bool to
setVerticalFreedomMode(true/false);
This only works if the player object is a Player, because it uses the head movement.

The offset values in the datablock can be changed for the camera object via script using
get/setLookAtOffset();
get/setThirdPersonOffset();
get/setGodViewOffset();
The setters take a Point3F as argument.

The orbit camera can be manipulated from script using
get/setOrbitMinMaxZoom()
get/setOrbitMinMaxDeclination()
The min/max take a Point2F

You can also manipulate the orbit camera directly by assigning values to the following variables
[code]
$advCamera::Yaw
$advCamera::Pitch
$advCamera::Zoom
$advCamera::azimuth
$advCamera::declination
$advCamera::zoomDistance
[code]

All camera modes coexist, so you can set the position, player object and target object once and then switch camera modes around as you see fit. Switching mode will not clear the old objects/positions.
#401
07/10/2007 (11:09 am)
now my problem is, setcameraobject, and setplayerobject seem to only work once and only once. so respawning is totally thrown out of whack.... any ideas?
#402
07/11/2007 (4:23 am)
delete the whole camera object, and recreate it on spawn
#403
07/11/2007 (9:11 am)
nope, didnt work, i made these functions:
function GameConnection::destroyCamera(%this)
{
	%this.advcamera.clearplayerobject();
	%this.advcamera.cleartargetobject();
	%this.clearcameraobject();
	%this.advcamera.delete();

}

function GameConnection::createCamera(%this)
{
   // create advanced camera
      %this.advCamera = new AdvancedCamera() {
      dataBlock = AdvCameraData;
   };
   MissionCleanup.add(%this.advCamera);
   %this.advCamera.scopeToClient(%this);
   
   %this.advCamera.setPlayerObject(%this.player);
   %this.advCamera.setGodViewMode();
   %this.setCameraObject(%this.advCamera);
}

and it still froze up on respawn.

strangely enough it works flawlessly in debug mode.... but not in release mode, in release i keep getting blank skies and then it freezes up when i try to respawn.

Edit again: ok so its not so much compiling it as debug as it is linking vs the debug runtime.
somehow linking with the release runtime makes the advanced camera not work, but linking with the multithreaded debug runtime makes it work like a charm, but with a lower framerate since its debug, and it makes me very curious as to why it happens....
#404
07/18/2007 (12:40 pm)
I am using TGEA and am having some trouble getting my advanced camera to work. My Mission has a Camera and is using a Waypoint marker as the target. However when I try to switch to this camera, the engine crashes.
#405
07/19/2007 (4:46 am)
@benj
shouldnt be a problem really. You should check your settings.
#406
07/20/2007 (9:36 am)
compiler or camera settings... cause im using the stock torque project, just with added preprocessor defines for my custom stuff, as for camera settings im using the datablock from the post up top.

it just simply doesnt work unless i link it against the debug runtime.
#407
08/03/2007 (10:24 am)
Quote:
Entr0py (Feb 07, 2007 at 14:49)

BUGS
--The camera is jerky because it needs interpolation. I tried for days to get it to work but frankly I got sick of it. I am no math wiz, so perhaps one of you guys might be able to fix it.

To solve the problem of the advCamera coming from the (0, 0, 0) in the beginning of the game, I used EntrOpy's code.s When I press w key, I find the player run in a jerky way, I don't know if this is the bug which Entr0py has mentioned above.

Who can fix it? thank you very much!
#408
08/03/2007 (4:55 pm)
Is there an updated zip with all the optimizations and bug corrections?
#409
08/04/2007 (3:25 am)
The problem is solved, but I don't know if it is right in logic. :)
#410
08/20/2007 (10:17 pm)
this is very cool I just got it to work
#411
09/06/2007 (3:12 pm)
Hi all,
I dont know if this may help some people with the server camera position problem. At least with a 3rd person camera.
The point is that, the camera position can be computed in the server just by knowing the camera offset and the player position. All the math is there in the advanceTime function. So in order to compute the camera position with NO vertical freedom I stripped the advanceTime and I added to advancedCamera.cpp:
Point3F AdvancedCamera::getThirdPersonCameraPosition() {
	Point3F	cameraPosWorld;
	MatrixF	objToWorld;
	GameBase *castObj = mPlayerObject;
	ShapeBase* playerObj = dynamic_cast<ShapeBase*>(castObj);
	objToWorld = playerObj->getRenderTransform();
	objToWorld.mulP(mCurrentThirdPersonOffset, &cameraPosWorld);
	return cameraPosWorld;
}

And of course a method to access that function:
ConsoleMethod( AdvancedCamera, getThirdPersonCameraPosition, const char *, 2, 2, "()"
              "Get the position of the camera in third person mode.\n\n"
              "@returns A string of form \"x y z\".") {
   static char buffer[200];
   AdvancedCamera *camObj = (AdvancedCamera *) object;
   
   Point3F pos = camObj->getThirdPersonCameraPosition();
   dSprintf(buffer, sizeof(buffer),"%f %f %f",pos.x,pos.y,pos.z);
   return buffer;
}

Of course dont forget to add this to advancedCamera.h
Point3F getThirdPersonCameraPosition();

So in your script you call:
%cameraPoint = %client.advCamera.getThirdPersonCameraPosition();

And thats it. I guess you get the idea. You can strip and program your own functions. All the camera positions can be computed real time in the server.

Luck!
Guimo

P.S. I found that there may be a little difference in the position of about 0.02 units in each axis... I can live with it.

After reading the advanceTime a bit I found that it can be easilly used to compute the camera position in any mode but I'm too lazy for that. Hey Thomas this is your child after all!!
#412
09/26/2007 (6:43 pm)
I modify TGEA demo's scripts and want to handle mouse event when the application started.I hope that use mouse to control the camera movement and rotation(etc. model viewer).I think use setOrbitMode() function.

if mouseLeftButtonDown and drag it,the camera has been moved;
if mouseRightButtonDown and darg it,the camera has been rotated around a player.

But I have a question about bind mouse event.I changed default.bind.cs in demo\client\scripts directory.In this file,I add these codes:

moveMap.bind( mouse, button0, mouseMove );
moveMap.bind( mouse, button1, mouseRotate );

and

$MouseMove = false;
$MouseRotate = false;

function mouseMove(%val)
{
if(%val >0)
{
$MouseMove = true;
echo("MouseMove = true");
}
else
{
$MouseMove = false;
echo("MouseMove = false");
}
}

function mouseRotate(%val)
{
if(%val >0)
{
$MouseRotate = true;
echo("MouseRotate = true");
}
else
{
$MouseRotate = false;
echo("MouseRotate = false");
}
}

But it does't work.What's wrong these codes?And How tontrol camera by mouse like that model viewer in TGEA?

Thanks!
#413
09/26/2007 (11:31 pm)
Hey Wang

Not exactly a camera question. But my best bet is that you need to delete your config.cs(+dso) file in the client folder and have it regenerated by the engine. Thats the classic problem when chaning things in default.bind.cs

@Guimo

Thanks a lot. Good to see various improvements. For the last 1+ year I havent used this code myself. So I am not cleaning up - even if its heavily needed.

Original code is now 3
#414
10/04/2007 (2:19 pm)
My camera seems "floaty" like it has a delayed response to movement whereas before, it was quick and precise. The rest of the features are great!

What settings do I need to change so my camera is precise and not 'floaty'? (Although I do want to maintain the smooth transitions when switching cameraObjects)
#415
10/05/2007 (8:04 am)
Hi, In one of my posts I added an interpolation attribute. This way you may adjust the smoothness of the camera. Setting a value of 1 makes the camera fixed so it inmediatly follows you around.

Luck!
Guimo
#416
10/19/2007 (11:27 am)
Has anyone played with the orbitting camera controlled by a joystick?
#417
11/07/2007 (11:27 am)
Ok i guess im the only one getting this error. Ive implemented this with success, but anytime I try and go to the thirdperson camera mode It works, but... It changes my keyboard commands.

example.
firstperson mode

w - forward
a - moveleft
s - back
d - moveright

thirdperson

w - forward
a - turnleft
s - spin to back (rotate 360)
d - turnright

can anyone please tell me where in the source is this held? and how can I change it to not do this. (it is extremely annoying) and has kept me from using this very useful camera resource.
#418
11/07/2007 (11:36 am)
Never mind made a bad mistake on adding this resouce with "Player Movement with a Seperate Camera"
http://www.garagegames.com/index.php?sec=mg&mod=resource&page=view&qid=5474
#419
12/27/2007 (12:22 pm)
Can anyone tell me if it's possible (I have been reading and haven't seen anything related) to have this camera, with godview or orbit mode, without it being bound to a control object? Is there anyway to control the camera directly in god view or does it always have to be tied to a control object? An example would be a free roaming god view camera?
#420
12/29/2007 (2:03 pm)
i have tgea. i used the resource from here (advancedcamera.zip) with the modifications (date of Feb 07, 2007 at 03:49) that Entr0pys did, and now every time i exec the tgea.exe, an error pops up:
run-time failure #3. the varialble 'cam' is being used without being defined.
the weird thing is that the only place where the cam variable is used is in ProcessList::advanceObjects() and i didnt find anything wrong....
if anybody had this same error, and found out a way to solve it, please share the secret, im going nuts with the orbit camera...

thanks for reading

EDIT: Problem solved, in Entr0pys's modification, one should does this:
AdvancedCamera * cam; // instead go for: AdvancedCamera * cam = NULL:
and then
if(cam)	//  replace it with if (cam != NULL)			   
cam->processTick(&movePtr[m]);
with that no more
run-time failure #3. the varialble 'cam' is being used without being defined.

by the way, is was better (at least for my) to change the Entr0pys's modification "void AdvancedCamera::setPosition(const Point3F& pos)" for the old one (the one that came with the basic resource)