无限滚动的背景在XNA背景、XNA

2023-09-07 14:08:05 作者:臟話比謊話幹凈

我画一个地面纹理的滚屏平台游戏是这样的:

I'm drawing a ground texture in a sidescrolling platformer like this:

spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, _camera.GetViewMatrix(Parallax));
foreach (Sprite sprite in Sprites)
     sprite.Draw(spriteBatch);
spriteBatch.End();

在Sprite.Draw()

In Sprite.Draw()

        public void Draw(SpriteBatch spriteBatch)
        {
            if (Texture != null)
                spriteBatch.Draw(Texture, Position, new Rectangle(0, 0, Texture.Width, Texture.Height), Color.White, Rotation, Origin, Scale, SpriteEffects.None, ZIndex);
        }

我怎样才能得到纹理在X方向重复无限?

任何解释如何做到这一点的资源将是巨大的。谢谢!

Any resources explaining how to do this would be great. Thanks!

我的实现照相机的是基于这样的: http://www.david-gouveia.com/2d-camera-with-parallax-scrolling-in-xna/

My implementation of camera is based on this: http://www.david-gouveia.com/2d-camera-with-parallax-scrolling-in-xna/

这是我试过了,我为背景的这样一个单独的平局:

This is what I tried, I made a separate draw for the background like this:

//Draw Background
spriteBatch.Begin(SpriteSortMode.Immediate, null, SamplerState.LinearWrap, null, null,null, camera.GetViewMatrix(Vector2.One));
groundSprite.Draw(spriteBatch, (int)camera.Position.X - (int)camera.Origin.X / 2);
spriteBatch.End();

在Sprite.Draw():

and in Sprite.Draw():

public void Draw(SpriteBatch spriteBatch, int scrollX = 0)
{
    if (Texture != null)
       spriteBatch.Draw(Texture, Position, new Rectangle(scrollX, 0, Texture.Width, Texture.Height), Color.White, Rotation, Origin, Scale, SpriteEffects.None, ZIndex);
}

还是有一些问题。

still have some issues.

这只是来找我。我有视差设置为1,在地面上。它应该是0,因此,它实际上从未移动。它只是看起来像它,当你用我选择下面的答案移动。

It just came to me. I had the parallax set to 1 on the ground. It should be 0 so that it never actually moves. It just looks like it moves when you use the answer I selected below.

谢谢!

推荐答案

不要滚动空间的精灵;滚动纹理坐标来呈现它。

Don't scroll the sprite in space; scroll the texture coordinates used to render it.

设置你的采样器来包装它的UV坐标:

Set your sampler to wrap its UV coordinates:

spriteBatch.Begin(..., SamplerState.LinearWrap, ...);

然后在渲染时指定源矩形:

Then specify a source rectangle when rendering:

var source = new Rectangle(scrollX, 0, texture.Width, texture.Height);
spriteBatch.Draw(texture, destination, source, Color.White);

如果所得的UV坐标脱落纹理的边缘,它们将由纹理采样包裹,这应该给你想要的滚动的效果。

If the resulting UV coordinates fall off the edge of the texture, they will wrapped by the texture sampler, which should give you the desired "scrolling" effect.