XNA 中的无限滚动背景 [英] Infinite Scrolling Background in XNA

查看:28
本文介绍了XNA 中的无限滚动背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在像这样的横向卷轴平台游戏中绘制地面纹理:

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

还有一些问题.

它刚刚来到我身边.我在地面上将视差设置为 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.

这篇关于XNA 中的无限滚动背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆