精灵行走和背景移动:XNA

时间:2014-04-02 10:28:49

标签: xna xna-4.0

我想在XNA中做一个简单的事情,当角色向右移动时背景会移动。

任何想法怎么做?

感谢

1 个答案:

答案 0 :(得分:3)

我认为你的意思就像在马里奥游戏中! 使用滚动。

创建游戏类。 按照绘制精灵的过程中所述加载资源。 加载背景纹理。

private ScrollingBackground myBackground;

protected override void LoadContent()
{
    // Create a new SpriteBatch, which can be used to draw textures.
    spriteBatch = new SpriteBatch(GraphicsDevice);
    myBackground = new ScrollingBackground();
    Texture2D background = Content.Load<Texture2D>("starfield");
    myBackground.Load(GraphicsDevice, background);
}

确定背景纹理的大小和屏幕的大小。

使用“高度”和“宽度”属性确定纹理大小,并使用图形设备上的“视口”属性确定屏幕大小。

使用纹理和屏幕信息,将纹理的原点设置为纹理顶边的中心,将初始屏幕位置设置为屏幕中心。

// class ScrollingBackground
private Vector2 screenpos, origin, texturesize;
private Texture2D mytexture;
private int screenheight;
public void Load( GraphicsDevice device, Texture2D backgroundTexture )
{
    mytexture = backgroundTexture;
    screenheight = device.Viewport.Height;
    int screenwidth = device.Viewport.Width;
    // Set the origin so that we're drawing from the 
    // center of the top edge.
    origin = new Vector2( mytexture.Width / 2, 0 );
    // Set the screen position to the center of the screen.
    screenpos = new Vector2( screenwidth / 2, screenheight / 2 );
    // Offset to draw the second texture, when necessary.
    texturesize = new Vector2( 0, mytexture.Height );
}

要滚动背景,请在Update方法中更改背景纹理的屏幕位置。 此示例通过增加屏幕位置的Y值将背景向下移动每秒100像素。

protected override void Update(GameTime gameTime)
{
    ...
    // The time since Update was called last.
    float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

    // TODO: Add your game logic here.
    myBackground.Update(elapsed * 100);

    base.Update(gameTime);
}

Y值保持不大于纹理高度,使背景从屏幕底部滚动回到顶部。

public void Update( float deltaY )
{
    screenpos.Y += deltaY;
    screenpos.Y = screenpos.Y % mytexture.Height;
}
// ScrollingBackground.Draw

使用在LoadContent和Update中计算的原点和屏幕位置绘制背景。

protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.CornflowerBlue);

    spriteBatch.Begin();
    myBackground.Draw(spriteBatch);
    spriteBatch.End();

    base.Draw(gameTime);
}

如果纹理未覆盖屏幕,则绘制另一个纹理。这会使用在加载时创建的Textureize矢量从屏幕位置减去纹理高度。这会产生循环的错觉。

public void Draw( SpriteBatch batch )
{
    // Draw the texture, if it is still onscreen.
    if (screenpos.Y < screenheight)
    {
        batch.Draw( mytexture, screenpos, null,
             Color.White, 0, origin, 1, SpriteEffects.None, 0f );
    }
    // Draw the texture a second time, behind the first,
    // to create the scrolling illusion.
    batch.Draw( mytexture, screenpos - texturesize, null,
         Color.White, 0, origin, 1, SpriteEffects.None, 0f );
}