Saturday, 13 February 2010

HS: mouse camera

There are lots of tutorials around on how to create an FPS-style camera in XNA. However, no easy to find ones on how to create a click-and-drag mouse camera similar to the Java3d OrbitBehavior class.

Digression: if there's one thing to be said of Java3d it is its suite of sensible helper classes to get you up and running faster, even if you can't do much once you're there. Here's hoping JavaFX finally integrates shaders into Java3d.

My problem is comparatively simple: I want a camera I can click and drag to rotate a camera view around a sphere. In Quake, I'd store the X and Y angles of the rotation and call makevectors() on them to turn the angles into a vector. Not so in XNA, I spent quite a while fiddling around with different ways to solve the problem. Eventually, the easiest way was to only calculate the rotation about the poles using this code I found on a forum somewhere:

static Vector3 RotateAroundPoint( Vector3 point,
Vector3 originPoint,
Vector3 rotationAxis,
float radiansToRotate)
{
Vector3 diffVect = point - originPoint;

Vector3 rotatedVect = Vector3.Transform(diffVect, Matrix.CreateFromAxisAngle(rotationAxis, radiansToRotate));

rotatedVect += originPoint;

return rotatedVect;
}


And then to magick up the vertical position with a little bit of maths, thus:

pos.X = xpos.X * (float) Math.Cos(ang.Y);
pos.Z = xpos.Z * (float) Math.Cos(ang.Y);
pos.Y = (float)Math.Sin(ang.Y);


... where xpos is the output from using the above function. My camera recalculate position just needs to set the camera position, then it figures out the new view matrix using CreateLookAt.

No comments:

Post a Comment