I'm having difficulty moving my camera behind an object in a 3D world. I'd like to have two view modes:

  1. for fps (first person).
  2. external view behind the character (third person).

I've searched the net for examples but they don't work in my project.

Here is my code used to change the view when F2 is pressed:

        double X1 = this.camera.PositionX;
        double X2 = this.player.Position.X;
        double Z1 = this.camera.PositionZ;
        double Z2 = this.player.Position.Z;

        //Verify that the user must not let the press F2
        if (!this.camera.IsF2TurnedInBoucle)
            // If the view mode is the second person
            if (this.camera.ViewCamera_type == CameraSimples.ChangeView.SecondPerson)
                this.camera.ViewCamera_type = CameraSimples.ChangeView.firstPerson;

                //Calcul position - ?? Here my problem
                double direction = Math.Atan2(X2 - X1, Z2 - Z1) * 180.0 / 3.14159265;
                //Calcul angle - ?? Here my problem

                this.camera.position = ..
                this.camera.rotation = ..

                this.camera.MouseRadian_LeftrightRot = (float)direction;
            //IF mode view is first person
  • 2
    \$\begingroup\$ If you're having trouble searching for examples, try "third person" not "second person". Second person view would likely be a "first person view" from a character that's not the player. Like controlling your character while they're being watched on a video camera. Third person is a view outside of any characters, like the follow camera you describe. \$\endgroup\$ – MichaelHouse Dec 7 '12 at 22:39

You try to calculate the angle between the current camera position and the current player position but Math.Atan2 returns a radian so you don't need the * 180 / PI part so that part is wrong.

However I don't know why you need the angle between the camera position and the player position. Assuming the camera points forward as seen from the player:

From 1st person to 3rd person you just need to do something like this:

camera.Position = camera.Position - Vector3.Normalize(Camera.LookAt) * distance + Vector3.Up * height

This will place the camera distance behind the player and will move the camera up by height.

From 3rd person to 1st person:

camera.Position.X = player.Position.X camera.Position.Z = player.Position.Z camera.Position.Y = camera.Position.Y - Vector3.Up * -height

This will move the camera back to the position of the player and will lower it to the original height.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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