3
\$\begingroup\$

I've implemented camera control with mouse and keyboard. My problem is that camera goes crazy when I'm using mouse and camera does not travel the way it is rotated. Could you explain me why and how to fix that?

My code:

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace Game_01
{
/// <summary>
/// This is the main type for your game.
/// </summary>
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
int windowWidth, windowHeight;
VertexPositionTexture[] floorVerts;
BasicEffect basicEffect;
Texture2D floorTexture;
Vector3 cameraPosition;
Vector3 cameraTarget;
float cameraYaw;
float cameraPitch;
Matrix projectionMatrix;
Matrix viewMatrix;
Matrix worldMatrix;
float speed;
float mouseSpeed;
Model model;
MouseState oldMouseState;
public Game1()
{
    graphics = new GraphicsDeviceManager(this);
    Content.RootDirectory = "Content";
}

/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content.  Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
    // TODO: Add your initialization logic here
    cameraPosition = new Vector3(0, 18, 0);
    cameraTarget = cameraPosition + Vector3.Forward;
    cameraYaw = 0;
    cameraPitch = 0;
    projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45), graphics.GraphicsDevice.Viewport.AspectRatio, 1, 1000);
    viewMatrix = Matrix.CreateLookAt(cameraPosition, cameraTarget, Vector3.Up) * Matrix.CreateFromYawPitchRoll(cameraYaw, cameraPitch, 0);
    worldMatrix = Matrix.CreateWorld(Vector3.Zero, Vector3.Forward, Vector3.Up);
    speed = 0.5f;
    mouseSpeed = 0.025f;
    windowWidth = graphics.PreferredBackBufferWidth;
    windowHeight = graphics.PreferredBackBufferHeight;
    Mouse.SetPosition(windowWidth / 2, windowHeight / 2);
    oldMouseState = Mouse.GetState();
    basicEffect = new BasicEffect(graphics.GraphicsDevice);
    base.Initialize();
}

/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
    // Create a new SpriteBatch, which can be used to draw textures.
    spriteBatch = new SpriteBatch(GraphicsDevice);

    // TODO: use this.Content to load your game content here
    floorTexture = Content.Load<Texture2D>("Textures/Ground");
    model = Content.Load<Model>("Models/Test");
}

/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// game-specific content.
/// </summary>
protected override void UnloadContent()
{
    // TODO: Unload any non ContentManager content here
}

/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
    if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
        Exit();

    // TODO: Add your update logic here
    if (Keyboard.GetState().IsKeyDown(Keys.W))
    {
        cameraPosition += Vector3.Forward * speed;
        cameraTarget += Vector3.Forward * speed;
    }
    if (Keyboard.GetState().IsKeyDown(Keys.S))
    {
        cameraPosition += Vector3.Backward * speed;
        cameraTarget += Vector3.Backward * speed;
    }
    if (Keyboard.GetState().IsKeyDown(Keys.A))
    {
        cameraPosition += Vector3.Left * speed;
        cameraTarget += Vector3.Left * speed;
    }
    if (Keyboard.GetState().IsKeyDown(Keys.D))
    {
        cameraPosition += Vector3.Right * speed;
        cameraTarget += Vector3.Right * speed;
    }
    if (Keyboard.GetState().IsKeyDown(Keys.Space))
    {
        cameraPosition += Vector3.Up * speed;
        cameraTarget += Vector3.Up * speed;
    }
    if (Keyboard.GetState().IsKeyDown(Keys.C))
    {
        cameraPosition += Vector3.Down * speed;
        cameraTarget += Vector3.Down * speed;
    }
    if (Mouse.GetState().X < 0 || Mouse.GetState().Y < 0 || Mouse.GetState().X >= windowWidth || Mouse.GetState().Y >= windowHeight)
    {
        Mouse.SetPosition(windowWidth / 2, windowHeight / 2);
    }
    else
    {
        if (Mouse.GetState().X - oldMouseState.X < 0)
        {
            cameraYaw -= mouseSpeed;
        }
        if (Mouse.GetState().X - oldMouseState.X > 0)
        {
            cameraYaw += mouseSpeed;
        }
        if (Mouse.GetState().Y - oldMouseState.Y < 0)
        {
            cameraPitch -= mouseSpeed;
        }
        if (Mouse.GetState().Y - oldMouseState.Y > 0)
        {
            cameraPitch += mouseSpeed;
        }
    }
    viewMatrix = Matrix.CreateLookAt(cameraPosition, cameraTarget, Vector3.Up) * Matrix.CreateFromYawPitchRoll(cameraYaw, cameraPitch, 0);
    oldMouseState = Mouse.GetState();
    base.Update(gameTime);
}
void DrawGround(Vector3 groundPosition)
{
    float x = 200, y = 200;
    int repetitions = 20;
    floorVerts = new VertexPositionTexture[6];
    floorVerts[0].Position = new Vector3(-x, -y, 0);
    floorVerts[1].Position = new Vector3(-x, y, 0);
    floorVerts[2].Position = new Vector3(x, -y, 0);
    floorVerts[3].Position = floorVerts[1].Position;
    floorVerts[4].Position = new Vector3(x, y, 0);
    floorVerts[5].Position = floorVerts[2].Position;
    floorVerts[0].TextureCoordinate = new Vector2(0, 0);
    floorVerts[1].TextureCoordinate = new Vector2(0, repetitions);
    floorVerts[2].TextureCoordinate = new Vector2(repetitions, 0);
    floorVerts[3].TextureCoordinate = floorVerts[1].TextureCoordinate;
    floorVerts[4].TextureCoordinate = new Vector2(repetitions, repetitions);
    floorVerts[5].TextureCoordinate = floorVerts[2].TextureCoordinate;
    basicEffect.Projection = projectionMatrix;
    basicEffect.View = viewMatrix;
    basicEffect.World = worldMatrix * Matrix.CreateTranslation(groundPosition);
    basicEffect.World *= Matrix.CreateRotationX(MathHelper.ToRadians(-90)) * Matrix.CreateRotationY(MathHelper.ToRadians(-90)) * Matrix.CreateRotationZ(MathHelper.ToRadians(0));
    basicEffect.TextureEnabled = true;
    basicEffect.Texture = floorTexture;
    foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
    {
        pass.Apply();
        graphics.GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleList, floorVerts, 0, 2);
    }
}
void DrawModel(Model model, Vector3 modelPosition, Vector3 modelRotation, Vector3 modelScale)
{
    foreach (ModelMesh mesh in model.Meshes)
    {
        foreach (BasicEffect effect in mesh.Effects)
        {
            effect.EnableDefaultLighting();
            effect.PreferPerPixelLighting = true;
            effect.Projection = projectionMatrix;
            effect.View = viewMatrix;
            effect.World = worldMatrix * Matrix.CreateTranslation(modelPosition);
            effect.World *= Matrix.CreateRotationX(MathHelper.ToRadians(modelRotation.X)) * Matrix.CreateRotationY(MathHelper.ToRadians(modelRotation.Y)) * Matrix.CreateRotationZ(MathHelper.ToRadians(modelRotation.Z));
            effect.World *= Matrix.CreateScale(modelScale);
        }
        mesh.Draw();
    }
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.CornflowerBlue);

    // TODO: Add your drawing code here
    DrawGround(new Vector3(0, 0, 0));
    DrawModel(model, new Vector3(0, 5, 0), Vector3.Zero, new Vector3(2, 2, 2));
    base.Draw(gameTime);
}
}
}
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

I don't have XNA setup to test any of this but looking at the code I would check a few things.

1) The changes in the camera relate vectors need to occur at elapsed time, not a constant time. Your code shows alot of: cameraPosition += Vector3.Forward * speed;

Should probably look like: cameraPosition += (Vector3.Forward * speed) * elasped_frame_time;

2) Your camera view matrix creation line shows you dropping the vectors into '* Matrix.CreateFromYawPitchRoll(cameraYaw, cameraPitch, 0);'. The vectors are still in degree format? Need to change to radians?

3) I think there is a fundamental problem with your logic on moving the camera. I'm guessing at your intention here, but I don't think you can apply those matrix by setting the cam position and target, then applying a rotation and getting the effect you want. Lets say it's kinda of FPS perspective with respect to the input your using. When the player hits 'W' are they really suppose to be moving in the direction of 'Vector.Forward', I would think they should be moving the the direction of whereever the camera is pointed (CameraTarget - CameraPosition). Your setup is placing the camera at some position, then rotating it. Well that rotation happens around 0,0,0, not the camera itself. If the camera's position is not 0,0,0 and then you rotate it, your not gonna get what you want.

Calculate the rotation first. Put the Camera at 0,0,0, and the camera target at 0,0,1 or whatever FORWARD is. Then rotate the camera target and camera up by your Y/P/R matrix. Then translate that by the camera position. Otherwise, leave the camera target alone.

Forget about the move input for the moment. Rebuild your code with hard coded input so you can remove that as a variable. Do something simple like have the yaw change rate match it's forward velocity such that it should move in a circle. Then you can see how a yaw input, plus forward movement effects the camera.

\$\endgroup\$

You must log in to answer this question.

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