Infinite Scrolling Background in XNA

倖福魔咒の 提交于 2019-12-06 11:11:33

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

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);

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.

Draw the background twice in the Sprite Draw method, but offset one of them, something like this (untested):

spriteBatch.Draw(Texture, Position, new Rectangle(0, 0, Texture.Width, Texture.Height), Color.White, Rotation, Origin, Scale, SpriteEffects.None, ZIndex);

spriteBatch.Draw(Texture, Position-new Vector2(Texture.Width, 0), new Rectangle(0, 0, Texture.Width, Texture.Height), Color.White, Rotation, Origin, Scale, SpriteEffects.None, ZIndex);

And then in the update method:

if (Position.X > Texture.Width) {
    Position.X -= Texture.Width;
}
else if (Position.X < 0) {
    Position.X += Texture.Width;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!