我正在使用C#和XNA,我想在游戏中制作滚动背景。
我正在试图找出实现滚动纹理的最佳方法,该滚动纹理无限期地向某个方向移动。让我们说一个有星星的空间背景。因此,当船舶移动时,确实会产生纹理,但方向相反。有点像“平铺”模式。
我到目前为止唯一的猜测是渲染两个纹理,比如向左移动,然后只有当它超出可见性或类似的东西时,让最左边的一个跳到右边。
所以,我想知道是否有一些简单的方法在XNA中进行,也许是一些渲染模式,或者我描述的方式是否足够好?我只是不想让事情过于复杂。我显然首先尝试谷歌,但几乎没有找到任何东西,但考虑到很多游戏也使用类似的技术,这很奇怪。
答案 0 :(得分:2)
使用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
);
答案 1 :(得分:1)
Microsoft有一个XNA教程正是这样做的,您可以获取源代码并阅读滚动背景背后的实际编程逻辑。奖励点他们进行视差滚动以获得良好的效果。
链接:http://xbox.create.msdn.com/en-US/education/tutorial/2dgame/getting_started