如果您打算将绘图留给单个静态方法,那么您将限制您能够绘制的内容。我建议创建一个接口并做一些抽象。
界面
public interface IGameObject
{
void Update(GameTime gameTime);
void Draw();
}
实用类
public sealed class GameUtility
{
private static GameUtility instance = null;
private static readonly object _lock = new object();
public ContentManager ContentManager { get; private set; }
public SpriteBatch SpriteBatch { get; private set; }
public static GameUtility Instance
{
get
{
lock (_lock)
{
if (instance == null)
{
instance = new GameUtility();
}
return instance;
}
}
}
public void SetContentManager(ContentManager contentManager)
{
this.ContentManager = contentManager;
}
public void SetSpriteBatch(SpriteBatch spriteBatch)
{
this.SpriteBatch = spriteBatch;
}
public GameUtility(ContentManager contentManager, SpriteBatch spriteBatch)
{
this.contentManager = contentManager;
this.spriteBatch = spriteBatch;
}
}
游戏对象
public class Hero : IGameObject
{
private Texture2D texture;
private Vector2 position;
private Color color;
public Hero(string path)
{
texture = GameUtility.Instance.ContentManager.Load<Texture2D>(path);
}
public void Update(GameTime gameTime)
{
// Do game update logic
}
public void Draw()
{
GameUtility.Instance.SpriteBatch.Begin();
GameUtility.Instance.SpriteBatch.Draw(texture, position, color);
GameUtility.Instance.SpriteBatch.End();
}
}
游戏类
初始化 GameUtility
GameUtility.Instance.SetContentManager(contentManager);
GameUtility.Instance.SetSpriteBatch(spriteBatch);
创建游戏对象
gameObects = new List<IGameObject>();
gameObjects.Add(new Hero("some path"));
使用接口
protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Clear(Color.CornflowerBlue);
foreach (IGameObject gameObject in gameObjects)
{
gameObject.Draw();
}
base.Draw(gameTime);
}
这种方法的美妙之处在于您可以根据需要执行不同的绘图。例如,您可以根据不同的场景使用Rectangle 而不是Vector2。您还可以绘制精灵字体或其他东西。
对于卸载内容,只有一个选项
GameUtility.Instance.ContentManager.Unload();
您最好在过渡到下一个级别期间卸载内容,因为调用 ContentManager.Unload() 将释放所有资源。至于为什么一次性处理所有东西,我不太明白,但这就是设计。
希望这个答案能给你一些见解。我不建议创建这个public static void DrawSprite。