如何在2D游戏中获取相机视图矩阵

时间:2013-07-25 16:34:15

标签: matrix xna camera 2d game-engine

我的相机类是这个,我在我的屏幕类中使用它来渲染地图。我需要能够做到这一点,所以我可以绘制水银粒子引擎粒子而不会看起来像是被拖过屏幕。

   using System;

   using System.Threading;

   using Microsoft.Xna.Framework;

   using Microsoft.Xna.Framework.Content;

   using Microsoft.Xna.Framework.Graphics;

   using Microsoft.Xna.Framework.Input;

   using TiledLib;

   namespace TiledLib

    {
        public class Camera

{
    public Vector2 Position;
    public int Width;
    public int Height;
    public Vector2 Target;
    public Rectangle ClampRect;
    public Vector2 Origin = new Vector2(0,0);
    float Speed = 0.2f;


    public Camera(Viewport vp, Map map)
        : this(vp, new Rectangle(0, 0, (map.Width * map.TileWidth), (map.Height * map.TileHeight)))
    { }


    public Camera(Viewport vp, Rectangle clampRect)
    {
        Position = Origin;
        Width = vp.Width;
        Height = vp.Height;

        ClampRect = clampRect;

        // Set initial position and target
        Position.X = ClampRect.X;
        Position.Y = ClampRect.Y;
        Target = new Vector2(ClampRect.X, ClampRect.Y);
    }


    public void Update()
    {
        // Clamp target to map/camera bounds
        Target.X = (int)MathHelper.Clamp(Target.X, ClampRect.X, ClampRect.Width - Width);
        Target.Y = (int)MathHelper.Clamp(Target.Y, ClampRect.Y, ClampRect.Height - Height);

        // Move camera toward target
        Position = Vector2.SmoothStep(Position, Target, Speed);
    }

}

}

1 个答案:

答案 0 :(得分:0)

来自变换的通用相机矩阵。如果没有缩放或旋转,请删除这些行。

return 
    Matrix.CreateTranslation(new Vector3(-Location.X, -Location.Y, 0)) *
    Matrix.CreateRotationZ(Rotation) *
    Matrix.CreateScale(Zoom) *
    Matrix.CreateTranslation(new Vector3(Origin.X, Origin.Y, 0));