2012-12-31 32 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