理论
滚动背景图像很容易与XNA SpriteBatch类来实现。 Draw方法有几个重载,让调用者指定一个源矩形。这个源矩形定义了被绘制到指定的目标矩形屏幕上的纹理的部分:更改源矩形的位置将改变在目标矩形显示的纹理的部分
。
为了让精灵覆盖整个屏幕使用以下目标矩形:
var destination = new Rectangle(0, 0, screenWidth, screenHeight);
如果整机质感应显示使用以下目标矩形:
var source = new Rectangle(0, 0, textureWidth, textureHeight);
比你必须做的是动画源矩形的X和Y坐标,然后完成。
好了,差不多了。即使源矩形移出纹理区域,纹理也应该重新开始。要做到这一点,你必须设置使用质地包裹一个SamplerState。幸运的是,SpriteBatch的Begin方法允许使用自定义的SamplerState。您可以使用下列之一:
// Either one of the three is fine, the only difference is the filter quality
SamplerState sampler;
sampler = SamplerState.PointWrap;
sampler = SamplerState.LinearWrap;
sampler = SamplerState.AnisotropicWrap;
例
// Begin drawing with the default states
// Except the SamplerState should be set to PointWrap, LinearWrap or AnisotropicWrap
spriteBatch.Begin(
SpriteSortMode.Deferred,
BlendState.Opaque,
SamplerState.AnisotropicWrap, // Make the texture wrap
DepthStencilState.Default,
RasterizerState.CullCounterClockwise
);
// Rectangle over the whole game screen
var screenArea = new Rectangle(0, 0, 800, 600);
// Calculate the current offset of the texture
// For this example I use the game time
var offset = (int)gameTime.TotalGameTime.TotalMilliseconds;
// Offset increases over time, so the texture moves from the bottom to the top of the screen
var destination = new Rectangle(0, offset, texture.Width, texture.Height);
// Draw the texture
spriteBatch.Draw(
texture,
screenArea,
destination,
Color.White
);
非常感谢您真正的深入解释! – NewProger