【问题标题】:Entity management, with inheritance method calls实体管理,带有继承方法调用
【发布时间】:2015-07-17 23:43:32
【问题描述】:

所以,我正在使用实体系统创建游戏。

公共类子弹:实体

公共类 Npc:实体

公共类坦克:实体

公共类实体

一个实体只有一些功能: 更新(),渲染()

我创建了一个这样的列表:

List<Entity> entities = new List<Entity>();

然后我循环遍历所有这些并调用 Update() / Render()

但是存储的 BulletsNpcs 不会被它们的 Update 或 Render 函数调用。

TL;DR

如何使用 Update/Render 函数存储所有不同的类,并在循环中为所有这些类调用它。

实体

class Entity
{
    public void Update(GameTime gameTime, GraphicsDevice gd, Player p, Tilemap tm, EntityManager em)
    {

    }
    public void Draw(SpriteBatch sb)
    {

    }
}

子弹

class Bullet : Entity
{
    public new void Update(GameTime gameTime, GraphicsDevice gd, Player p, Tilemap tm, EntityManager em)
    {
    }

    public new void Render(SpriteBatch spriteBatch)
    {
    }

}

实体管理器

class EntityManager
{
    public List<Entity> entityList = new List<Entity>();

    public void Update(GameTime gameTime, GraphicsDevice graphics, Player p, Tilemap tm, EntityManager em)
    {
        int i = 0;
        while (i < entityList.Count)
        {
            entityList[i].Update(gameTime, graphics, p, tm, em);
            i++;
        }
    }
    public void Render(SpriteBatch sb)
    {
        foreach (Bullet entity in entityList)
        {
            entity.Draw(sb);
        }
    }

}

【问题讨论】:

  • 我假设您需要帮助:But the stored Bullets or Npcs will not get called with their Update or Render functions.。但是您没有包含相关代码来帮助您。请包括Minimal, Complete, and Verifiable example。谢谢。
  • 把 List 弄错了例子。固定为列表。如果它的 List 效果很好。

标签: c# xna entity monogame


【解决方案1】:

Entity 的方法更改为使用virtual 关键字:

public virtual void Update(...

public virtual void Draw(...

在您的子类中,您希望通过使用 override 关键字而不是 new 关键字来覆盖基类的方法:

public override void Update(...

public override void Draw(...

通过在继承树中使用virtual/override 组合,您可以启用多态性,这将允许调用子类的方法,即使是从List&lt;Entity&gt; 调用。

链接到polymorphism in C#的更多信息。

【讨论】:

    猜你喜欢
    • 2020-12-17
    • 2013-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-06
    • 2017-09-08
    • 2016-03-31
    • 1970-01-01
    相关资源
    最近更新 更多