我正在使用 C# 和 XNA,我想在我的游戏中制作滚动背景。
我正在尝试找出实现朝某个方向无限移动的滚动纹理的最佳方法。假设有星星的太空背景。因此,当船舶移动时,纹理也会发生变化,但方向相反。有点像“平铺”模式。
到目前为止,我唯一的猜测是渲染两个纹理,比如说向左移动,然后当最左边的一个纹理超出可见范围或类似的情况时,使其向右跳转。
所以,我想知道在 XNA 中是否有一些简单的方法可以做到这一点,也许是某种渲染模式,或者我描述的方式是否足够好?我只是不想让事情变得过于复杂。我显然先尝试用谷歌搜索,但几乎什么也没找到,但考虑到许多游戏也使用类似的技术,这很奇怪。
最佳答案
理论
使用 XNA 可以轻松实现滚动背景图像 SpriteBatch类(class)。 Draw 有多个重载让调用者指定源矩形的方法。此源矩形定义了绘制到屏幕上指定目标矩形的纹理部分:
更改源矩形的位置将更改目标矩形中显示的纹理部分。
为了让 Sprite 覆盖整个屏幕,请使用以下目标矩形:
var destination = new Rectangle(0, 0, screenWidth, screenHeight);
如果应显示整个纹理,请使用以下目标矩形:
var source = new Rectangle(0, 0, textureWidth, textureHeight);
您所要做的就是为源矩形的 X 和 Y 坐标设置动画,然后就完成了。
嗯,快完成了。即使源矩形移出纹理区域,纹理也应重新开始。为此,您必须设置 SamplerState使用纹理包裹。幸运的是Begin SpriteBatch 的方法允许使用自定义 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
);
关于c# - 循环滚动纹理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14104193/