c# - 循环滚动纹理

标签 c# xna rendering textures spritebatch

我正在使用 C# 和 XNA,我想在我的游戏中制作滚动背景。

我正在尝试找出实现朝某个方向无限移动的滚动纹理的最佳方法。假设有星星的太空背景。因此,当船舶移动时,纹理也会发生变化,但方向相反。有点像“平铺”模式。

到目前为止,我唯一的猜测是渲染两个纹理,比如说向左移动,然后当最左边的一个纹理超出可见范围或类似的情况时,使其向右跳转。

所以,我想知道在 XNA 中是否有一些简单的方法可以做到这一点,也许是某种渲染模式,或者我描述的方式是否足够好?我只是不想让事情变得过于复杂。我显然先尝试用谷歌搜索,但几乎什么也没找到,但考虑到许多游戏也使用类似的技术,这很奇怪。

最佳答案

理论

使用 XNA 可以轻松实现滚动背景图像 SpriteBatch类(class)。 Draw 有多个重载让调用者指定源矩形的方法。此源矩形定义了绘制到屏幕上指定目标矩形的纹理部分:

enter image description here

更改源矩形的位置将更改目标矩形中显示的纹理部分。

为了让 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/

相关文章:

c# - 对象识别自身并运行特定逻辑的最佳方式是什么?

javascript - chart.renderTo 不起作用

c - Vulkan - 同步对单个缓冲区的访问

c++ - 关于光栅化: Stochastic Sampling, Pineda边函数和定点数的问题

c# - 为 int、float 等类型分配额外的属性以进行反射

c# - 获取 contact.LastName 时出现 System.Runtime.InteropServices.COMException (0x800706BE)

c# - xbox 性能陷阱

c# - 在 XNA 4.0 中绘制 3D 模型?

c# - 我需要什么来为这个游戏创建这个控件? (像管道)

c# - session 变量是否会在不同的时间后过期?