2014-04-02 29 views
0

我想在XNA中做一個簡單的事情,當角色向右移動時背景會移動。雪碧散步和背景移動太:XNA

任何想法如何做到這一點?

謝謝

+0

當你移動的字符背景的權increament X ...背景將移動 – pravin

+0

,但在這種情況下該角色會始終在同一位置。 – pinker

+1

然後從背景X中減去一個值,然後向左移動。更好的是,如果您將其表現爲玩家的相反X方向,向左移動也會起作用! amountOfPlayerMovement * -1 * backgroundMoveSpeed *(float)gameTime.ElapsedGameTime.TotalSeconds; – Beanish

回答

2

我覺得你的意思就像是在遊戲馬里奧! 使用滾動。

創建遊戲類。 按照繪製雪碧的過程中所述加載資源。 加載背景紋理。

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

如果紋理不覆蓋屏幕,將繪製另一個紋理。這使用加載時創建的紋理矢量從屏幕位置減去紋理高度。這產生了循環的幻覺。

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