单人游戏精灵类

时间:2018-11-12 05:11:21

标签: c# class monogame

我正在为我的引擎在Monogame中进行关卡编辑。

我想创建一个可以调用简单函数的类,它将绘制一个Sprite。

这是我要调用的函数-正如您可能知道的那样,您必须能够加载和卸载内容并使用draw方法。

问题:我如何使它能够使用这些功能,以便我要做的就是调用此函数并起作用?

功能如下:

public static void DrawSprite(Texture2D Texture, string Path, Vector2 Position, Color Color)
{

}

1 个答案:

答案 0 :(得分:1)

如果要将绘图保留为单个静态方法,则将限制您可以绘图的内容。我建议创建一个接口并进行一些抽象。

界面

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