理論
滾動背景圖像很容易與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