gpt4 book ai didi

c# - 如何制作正确的抽象实体类

转载 作者:太空宇宙 更新时间:2023-11-03 13:00:36 24 4
gpt4 key购买 nike

我想创建一个抽象类 Entity,然后从中派生出几个类,如 Enemy、Friendly 和 Player。我这样做的原因是因为这些类有很多相似的属性/字段。我还有 2 个方法:updateEntitydrawEntity。我拥有更新和绘制实体的原因是 drawEntity & updateEntity 对于大多数从它继承的类来说是相同的。这是我的实体类的代码:

public abstract class Entity
{
private string name;

public string Name
{
get { return name; }
set { name = value; }
}

private Texture2D texture;

public Texture2D Texture
{
get { return texture; }
set { texture = value; }
}

private Vector2 position;

public Vector2 Position
{
get { return position; }
set { position = value; }
}

private int health;

public int Health
{
get { return health; }
set { health = value; }
}

private Color entColor;

public Color EntColor
{
get { return entColor; }
set { entColor = value; }
}

public Entity(string name, Texture2D texture, Vector2 position, int health, Color entColor)
{
this.name = name;
this.texture = texture;
this.position = position;
this.health = health;
this.entColor = entColor;
}

public virtual void updateEntity(GameTime gameTime)
{
//update stuff here
}

public virtual void drawEntity(SpriteBatch spriteBatch)
{
spriteBatch.Draw(texture, new Rectangle((int)position.X, (int)position.Y, texture.Width, texture.Height), entColor);
}
}

这就是我对 Enemy 类的设想:

public Enemy(string name, Texture2D texture, Vector2 position, int health, Color entColor)
{
Name = name;
Texture = texture;
Position = position;
Health = health;
EntColor = entColor;
}

谁能告诉我这是对抽象类的良好使用,还是我在游戏设计/架构方面做错了什么?

最佳答案

当抽象类的实现尚未完成时,您通常会使用抽象类,但它包含对从它派生的其他类型通用的属性和/或方法,或者它提供了一个应该由派生类型共享的接口(interface),但无法在这种抽象级别上实现,因此无法对其进行实例化。

这样的例子可以是一个抽象类 Fruit,它有一个 Color 属性,该属性对所有水果都是通用的,并且不必由每个水果实现.它也可以有一个没有实现的方法 Grow()。单独这个类还没有意义。您需要实现一个具体的水果,例如 Apple 类型,并为这个特定的水果实现 Grow() 方法。

在您的例子中,Entity 就是这样一个水果,而苹果可以是一个矩形或一个圆形,它们实现了自己的绘图逻辑。

基础实体:

public abstract class Entity
{
public abstract void Draw(); // no implementation here

public virtual void UpdateEntity(GameTime gameTime)
{
// default update
}
}

矩形:

public class Rectangle : Entity
{
public override void Draw()
{
// draw a rectangle here
}
}

Circle 对 UpdateEntity 使用不同的逻辑:

public class Circle : Entity
{
public override void Draw()
{
// draw a circle here
}

public override void UpdateEntity(GameTime gameTime)
{
// custom update for circles
}
}

关于c# - 如何制作正确的抽象实体类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32419012/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com