4
\$\begingroup\$

How would I create a camera that with the mouse, it allows you to orbit around a specifc position, with the camera always facing that point? I would also like it to be able to always be at a constant distance from the point, and be able to orbit around it in every direction.

Any ideas?

\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

What you're looking for is an ArcBall Camera. I've got a full snippet over here https://roy-t.nl/2010/02/21/xna-simple-arcballcamera but just to explain the general idea:

You set a look-at point in space which you want to orbit. Then you create a vector from that point by rotate around it using the Pitch Yaw and Roll. You then lengthen the vector to your desired distance from the object.

Anyway the most interesting stuff happens in this method:

private void ReCreateViewMatrix()
        {
            //Calculate the relative position of the camera
            position = Vector3.Transform(Vector3.Backward, Matrix.CreateFromYawPitchRoll(yaw, pitch, 0));
            //Convert the relative position to the absolute position
            position *= zoom;
            position += lookAt;
 
            //Calculate a new viewmatrix
            viewMatrix = Matrix.CreateLookAt(position, lookAt, Vector3.Up);
            viewMatrixDirty = false;
        }
\$\endgroup\$
6
  • \$\begingroup\$ Cool thanks, could you please provide a working example of this? \$\endgroup\$
    – Darestium
    Commented Mar 16, 2012 at 7:13
  • \$\begingroup\$ The snippet I linked is fully functional, you just need to plug it into any working XNA app and use its view and projection Matrix. \$\endgroup\$
    – Roy T.
    Commented Mar 16, 2012 at 8:18
  • \$\begingroup\$ So, when you change the (yaw) rotation value you (the camera) are rotating around the object, rather then you rotating around it (the objects)? And if so, do you have any idea how I could control it with the mouse? And nice snippet! Thanks for the help \$\endgroup\$
    – Darestium
    Commented Mar 31, 2012 at 1:44
  • \$\begingroup\$ Yes the camera orbits the point in space. You could easily wire the yaw and pitch variables to the X and Y changes of the mouse since last frame. Just do something like MousePDelta = prevMouseP - MouseP; arcballCamera.Yaw += mousePDelta.X; arcBallCamera.Pitch += mousePDelta.Y; prevMouseP = MouseP; \$\endgroup\$
    – Roy T.
    Commented Mar 31, 2012 at 6:28
  • 1
    \$\begingroup\$ I found a simple solution to get rid of that nasty flip: Vector3 up = Vector3.Transform(Vector3.Up, rotMat) where rotMat is the same CreateFromYawPitchRoll; and then viewMatrix = Matrix.CreateLookAt(position, lookAt, up); \$\endgroup\$ Commented Oct 20, 2023 at 15:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .