【问题标题】:Scrolling texture in cycle循环滚动纹理
【发布时间】:2012-12-31 17:05:08
【问题描述】:

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

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

到目前为止,我唯一的猜测是渲染两个纹理,比如说向左移动,然后当它超出可见性或类似的东西时,让最左边的一个跳到右边。

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

【问题讨论】:

    标签: c# xna rendering textures spritebatch


    【解决方案1】:

    理论

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

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

    为了让精灵覆盖整个屏幕,请使用以下目标矩形:

    var destination = new Rectangle(0, 0, screenWidth, screenHeight);
    

    如果应该显示整个纹理,请使用以下目标矩形:

    var source = new Rectangle(0, 0, textureWidth, textureHeight);
    

    您只需为源矩形的 X 和 Y 坐标设置动画就完成了。

    嗯,差不多完成了。即使源矩形移出纹理区域,纹理也应该重新开始。为此,您必须设置一个使用 texture wrapSamplerState。幸运的是,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
    );
    

    【讨论】:

    • 非常感谢您真正深入的解释!
    【解决方案2】:

    Microsoft 有一个 XNA 教程可以做到这一点,您可以获取源代码并阅读滚动背景背后的实际编程逻辑。奖励积分他们会进行视差滚动以获得良好的效果。

    链接:http://xbox.create.msdn.com/en-US/education/tutorial/2dgame/getting_started

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-12
      • 2015-08-20
      • 1970-01-01
      • 1970-01-01
      • 2016-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多