如果你只是想爲的是另一個類移動代碼,創建類(如類似GameWorld
似乎適合您的代碼)
public class GameWorld
{
// You may wish to move your gameTile definition into this class if it is the only
// class that uses it, and handle the content loading for it in here.
// e.g. if you're currently loading the texture in the LoadContent method in your game
// class, create a LoadContent method here and pass in ContentManger as a parameter.
// I've passed in the texture as a parameter to the Draw method in this example to
// simplify as I'm not sure how you're managing your textures.
public void Draw(SpriteBatch spriteBatch, GameTime gameTime, Texture2D gameTile)
{
// loop below loads the 'grass' tiles only
// assuming gameworld size of 770x450
for (int i = 0; i < 770; i += 31) // adds 31 to i (per tile)
{
Vector2 position = new Vector2(i, 392); // places incrementation into vector position
spriteBatch.Draw(gameTile, position, Color.White); // draws the tile each time
if (i == 744)
{
i = i + 26; // fills last space between 744 and 770
position = new Vector2(i, 392);
}
spriteBatch.Draw(gameTile, position, Color.White);
}
// loop below loads the brick tiles only (ones without grass)
}
}
然後在您的Game
類的Draw方法看起來像
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
spriteBatch.Draw(danChar, charPosition, Color.White);
// Assuming you've created/loaded an instance of the GameWorld class
// called gameWorld in Initialize/LoadContent
gameWorld.Draw(spriteBatch, gameTime, gameTile);
spriteBatch.End(); // ends the spriteBatch call
base.Draw(gameTime);
}
只要確保您按照正確的順序調用Draw
方法。例如您希望您的播放器出現在任何背景圖塊上方。
我相信默認SpriteSortMode
是Deferred
,它按調用的順序(即從後面到前面)繪製。
如果您需要,您可以在撥打spriteBatch.Begin()
時指定不同的SpriteSortMode
,但對於簡單遊戲,只需撥打Draw
來電。
更多關於SpriteSortMode
在MSDN如果需要。
同樣,如果您願意,您可以將您的Update
,LoadContent
方法鏈接到這些類中,確保傳遞任何您需要的參數作爲參數。
更新:
定義gameWorld
爲GameWorld
類的實例,你定義它靠近你的遊戲類的頂部,則通常在Initialize
方法初始化。
所以你的遊戲類看起來像
public class MyGameName : Microsoft.Xna.Framework.Game
{
private SpriteBatch spriteBatch;
// other variable declarations
// Add a declaration for gameWorld
private GameWorld gameWorld;
protected override Initialize()
{
// Add the following line to initialize your gameWorld instance
gameWorld = new GameWorld();
}
// other existing code - your LoadContent, Update, Draw methods etc.
}
多少經驗,你有寫作課? – paste
您可以使用的另一件事是[DrawableGameComponent](https://msdn.microsoft.com/en-us/library/microsoft.xna.framework.gamecomponent.aspx) – LibertyLocked