我根据http://www.david-amador.com/2009/10/xna-camera-2d-with-zoom-and-rotation/中的类构建了一个摄像头。我目前正在制作一种太空射击游戏(但有故事和这些东西),并希望让相机正常工作。但是Zoom并不像我想的那样工作。我不知道为什么,但我希望你能帮助我^^ 问题是,精灵在某个方向上移动了大约30个像素。可能我没有正确设置主宇宙飞船的位置或摄像机只是窃听。 游戏全屏运行。
Game1方法:
InputHandler.Update(gameTime, graphics.GraphicsDevice);
World.Camera.Position = new Vector2(Player.Ship.Position.X + Player.Ship.Texture.Width/2, Player.Ship.Position.Y+Player.Ship.Texture.Height/2);
World.Camera.Zoom = InputHandler.ZoomValue;
我将主太空船纹理的一半大小添加到相机位置,以便纹理的中间位于中间。没有它它也无法工作..
我如何设置全屏(我知道......这不是我应该这样做的方式,但它不适用于普通代码。)
graphics.PreferredBackBufferHeight = 10000;
graphics.PreferredBackBufferWidth = 10000;
graphics.ToggleFullScreen();
graphics.PreferMultiSampling = true;
graphics.IsFullScreen = true;
graphics.ApplyChanges();
InputHandler类:
public static void Update(GameTime gameTime, GraphicsDevice graphics)
{
_oldKeyboardState = keyboardState;
_oldMouseState = mouseState;
keyboardState = Keyboard.GetState();
mouseState = Mouse.GetState();
MousePosition = new Vector2(mouseState.X, mouseState.Y);
MatrixMousePosition = Vector2.Transform(MousePosition, Matrix.Invert(World.Camera.GetTransformation(graphics)));
OldScrollWheelValue = ScrollWheelValue;
ScrollWheelValue = mouseState.ScrollWheelValue;
if (ScrollWheelValue > OldScrollWheelValue) ZoomValue += 0.1f;
if (ScrollWheelValue < OldScrollWheelValue) ZoomValue -= 0.1f;
ZoomValue = MathHelper.Clamp(ZoomValue, 0.5f, 1.5f);
}
最后是相机类:
protected float _zoom; // Camera Zoom
public Matrix _transform; // Matrix Transform
public Vector2 _pos; // Camera Position
protected float _rotation; // Camera Rotation
public float Zoom
{
get { return _zoom; }
set { _zoom = value; if (_zoom < 0.1f) _zoom = 0.1f; }
}
public float Rotation
{
get { return _rotation; }
set { _rotation = value; }
}
public Vector2 Position
{
get { return _pos; }
set { _pos = value; }
}
public Camera()
{
_zoom = 1.0f;
_rotation = 0.0f;
_pos = Vector2.Zero;
}
public Matrix GetTransformation(GraphicsDevice graphicsDevice)
{
var viewport = graphicsDevice.Viewport;
_transform =
Matrix.CreateTranslation(new Vector3(-_pos.X*Zoom, -_pos.Y*Zoom, 0)) *
Matrix.CreateRotationZ(Rotation) *
Matrix.CreateScale(new Vector3(Zoom, Zoom, 1)) *
Matrix.CreateTranslation(new Vector3(viewport.Width * 0.5f, viewport.Height * 0.5f, 0));
return _transform;
}
答案 0 :(得分:1)
我看到你做错了什么,这一行:
transform = Matrix.CreateTranslation(new Vector3(-_pos.X*Zoom, -_pos.Y*Zoom, 0)) * ....
应该是:
transform = Matrix.CreateTranslation(new Vector3(-_pos.X, -_pos.Y, 0)) * ....
因为现在当你缩放时你也会翻译图像,这会导致移动的精灵。