2012-12-31 33 views
2

我使用C#和XNA,我想對我做遊戲的滾動背景。滾動紋理週期

我試圖找出最好的方式來實現滾動的質感,在某些方向移動下去。讓我們說一個星星的空間背景。所以,當船舶移動時,做的是質地,但方向相反。有點像在「平鋪」模式。

我只能猜測,到目前爲止是渲染兩個紋理它們,讓我們說向左移動,然後只是讓最左邊一個跳權當它超出了可見性或與此類似。

所以,我想知道是否有一些簡單的方法來做到這一點的XNA,也許有些渲染模式,或者是我形容它是方法不夠好?我只是不想過分複雜的事情。我顯然首先嚐試谷歌,但幾乎沒有發現任何東西,但考慮到許多遊戲也使用類似的技術,這很奇怪。

回答

2

理論

滾動背景圖像很容易與XNA SpriteBatch類來實現。 Draw方法有幾個重載,讓調用者指定一個源矩形。這個源矩形定義了被繪製到指定的目標矩形屏幕上的紋理的部分:更改源矩形的位置將改變在目標矩形顯示的紋理的部分

enter image description here

爲了讓精靈覆蓋整個屏幕使用以下目標矩形:

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 
); 
+1

非常感謝您真正的深入解釋! – NewProger