简体   繁体   中英

Moving a camera in XNA, C#

I am trying to make a scrolling level to a test game I am doing as a learning exercise. I have created a map containing lots of tiles which are drawn according to their position in an array. I basically want the camera to scroll down the level, but at the moment it just frantically shakes up and down a little bit.

I have a camera class which is just a blank static class containing a static vector2 for the camera location. It is just set as 50, 50 as all the tiles are 50 by 50.

Then in my maps update method I have the following:

public void Update(GameTime gameTime) {

Camera.Location.Y = MathHelper.Clamp(Camera.Location.Y + (float)speed, 0, (300 - 18) * 50)

}

The 300 and 18 are the total number of tiles and the number of tiles on screen (vertically).

I am completely lost so would appreciate any help or advice.

Here's a simple 2D camera class that I use in my games.

public class Camera2D
{
    public Camera2D()
    {
        Zoom = 1;
        Position = Vector2.Zero;
        Rotation = 0;
        Origin = Vector2.Zero;
        Position = Vector2.Zero;
    }

    public float Zoom { get; set; }
    public Vector2 Position { get; set; }
    public float Rotation { get; set; }
    public Vector2 Origin { get; set; }

    public void Move(Vector2 direction)
    {
        Position += direction;
    }

    public Matrix GetTransform()
    {
        var translationMatrix = Matrix.CreateTranslation(new Vector3(Position.X, Position.Y, 0));
        var rotationMatrix = Matrix.CreateRotationZ(Rotation);
        var scaleMatrix = Matrix.CreateScale(new Vector3(Zoom, Zoom, 1));
        var originMatrix = Matrix.CreateTranslation(new Vector3(Origin.X, Origin.Y, 0));

        return translationMatrix * rotationMatrix * scaleMatrix * originMatrix;
    }
}

The idea is to apply it as a transform when you are about you draw your sprite batch like so:

var screenScale = GetScreenScale();
var viewMatrix = Camera.GetTransform();

_spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied,
                           null, null, null, null, viewMatrix * Matrix.CreateScale(screenScale));

You probably also noticed the use of a screen scale. Although not directly related to the camera, it's a way to make sure your screen is scaled to the desired resolution. This way you can draw your scene independent of resolution and scale it at the end. Here's the screen scale method for reference:

    public Vector3 GetScreenScale()
    {
        var scaleX = (float)_graphicsDevice.Viewport.Width / (float)_width;
        var scaleY = (float)_graphicsDevice.Viewport.Height / (float)_height;
        return new Vector3(scaleX, scaleY, 1.0f);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM