【发布时间】:2011-04-03 23:13:07
【问题描述】:
我正在开发一款 XNA 游戏,我正在使用 ViewPort.Project 和 ViewPort.Unproject 来转换世界坐标。目前,我将这些用于我用 SpriteBatch 绘制的每个对象。我想做的是计算一个矩阵,我可以发送给 SpriteBatch.Begin 来为我做屏幕空间转换。
以下是我目前用于在屏幕空间之间进行转换的函数:
Vector2 ToWorldCoordinates(Vector2 pixels)
{
Vector3 worldPosition = graphics.GraphicsDevice.Viewport.Unproject(new Vector3(pixels, 0),
Projection, View, Matrix.Identity);
return new Vector2(worldPosition.X, worldPosition.Y);
}
Vector2 ToScreenCoordinates(Vector2 worldCoords)
{
var screenPositon = graphics.GraphicsDevice.Viewport.Project(new Vector3(worldCoords, 0),
Projection, View, Matrix.Identity);
return new Vector2(screenPositon.X, screenPositon.Y);
}
View 设置为 Matrix.Identity,Projection 设置如下:
Projection = Matrix.CreateOrthographic(40 * graphics.GraphicsDevice.Viewport.AspectRatio, 40, 0, 1);
这是我目前的绘制方式:
spriteBatch.Begin();
foreach (var thing in thingsToDraw)
{
spriteBatch.Draw(thing.Texture, ToScreenCoordinates(thing.PositionInWorldCoordinates), thing.Color);
spriteBatch.End();
}
spriteBatch.End();
这就是我想要做的(使用 SpriteBatch.Begin() 的 XNA 4.0 版本)
// how do I calculate this matrix?
Matrix myTransformationMatrix = GetMyTransformationMatrix();
spriteBatch.Begin(SpriteSortMode.Immediate, null, null, null, null, null,
myTransformationMatrix);
foreach (var thing in thingsToDraw)
{
// note: no longer converting each object's position to screen coordinates
spriteBatch.Draw(thing.Texture, thing.PositionInWorldCoordinates, thing.Color);
spriteBatch.End();
}
spriteBatch.End();
【问题讨论】: