[XNA] Matrix Transformations: Pointing a gun at a crosshair

Started by
1 comment, last by Arjan B 14 years, 3 months ago
Hi there! I'm trying to make a game using XNA where a tank-like vehicle can be moved left and right, and automatically aims at the mouse cursor. I know I can calculate a direction vector like this:

Vector3 gunDirection = new Vector3(mousePosition, 0.0f) - tank.position;

A rotation around the Z-axis in radians could then be acquired like this:

float rotation = atan(gunDirection.Y/gunDirection.X);

I run into problems when I want to apply a rotation to the "Gun" mesh in the tank's model. The transformation matrix of the mesh can be retrieved this way:

Matrix gunTransform = tank.model.Bones["Gun"].Transform;

How do I alter the gun's transformation matrix to keep it's translation and scale, but have the new rotation? Thank you in advance, Arjan B
Advertisement
Unless I'm missing something, you can just multiply the matrix by Matrix.CreateRotationZ(rotation).
I have already tried saving the gun's initial transform in tank.gunTransform, and updating the transform in this way:

Vector3 gunDirection = new Vector3(mousePosition, 0.0f) - tank.position;float gunRotation = (float)Math.Atan2(gunDirection.Y, gunDirection.X);tank.model.Bones["Gun"].Transform = tank.gunTransform * Matrix.CreateRotationZ(gunRotation);


But this doesn't give the result I want it to. The pivot of the rotation seems off (which is fixable..), but also it doesn't seem to rotate more than 90 degrees, no matter where I move my mouse or tank.

What I just noticed while doing a second check is, when I rotate my mouse around the top-left corner of the window (so also outside the window), the gun does rotate 360 degrees (I'll clamp that later on).


EDIT:
I just realised that the tank's position is in world coordinates and the mouse's position is probably in screen coordinates.

I've defined a Camera class like this:
    class Camera    {        public Matrix viewMatrix;        public Matrix projectionMatrix;        public Vector3 position;        public Vector3 lookAt;        public Camera(Vector3 position, Vector3 lookAt, float aspectRatio)        {            this.position = position;            this.lookAt = lookAt;            viewMatrix = Matrix.CreateLookAt(position, lookAt, Vector3.Up);            projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspectRatio, 1.0f, 10000.0f);        }    }


Could I calculate the tank's screen coordinates using this information?

[Edited by - Arjan B on January 18, 2010 3:21:39 AM]

This topic is closed to new replies.

Advertisement