我目前正在对一所学校的项目,是由于周五&我做过了很多事情要做。 这个任务是使用Monogame制作XNA框架的视频游戏。我目前正在处理碰撞。如何在继承类中使用抽象方法?
对于碰撞,我有一个简单的碰撞类
class Collision{
public GameObject Other;
public GameObject Obj1;
public Collision(GameObject obj1, GameObject other)
{
Other = other;
Obj1 = obj1;
}}
的碰撞是一个静态方法在游戏对象类处理:
public static void UpdateCollisions()
{
//Empty the list
AllCollisions.Clear();
for (int a = 0; a < AllGameObjectsWithCollision.Count; a++)
{
GameObject obja = AllGameObjectsWithCollision[a];
for (int b = 0; b < AllGameObjectsWithCollision.Count; b++)
{
GameObject objb = AllGameObjectsWithCollision[b];
if (obja.Mask != null & objb.Mask!= null && obja != objb)
{
if (obja.Mask.CollisionRectangle.Intersects(objb.Mask.CollisionRectangle))
AllCollisions.Add(new Collision(obja, objb));
}
}
}
}
这远远它的工作,游戏是找到的所有碰撞喜欢它应该。但是现在我需要让我的对象知道他们正在碰撞,并告诉他们该做什么。 对于这一点,我做了实体类的抽象能够声明称“OnCollision(碰碰撞)”
abstract class Entity : GameObject
{
public float Health;
public float MaxHealth;
public bool Alive;
public float OriginalDmg;
public float Dmg;
public abstract void OnCollision(Collision collision);
}
然后我重写方法中的类抽象方法继承实体类
例。射弹
class Projectile : Entity
{
Entity Owner;
ProjectileType pType;
public Projectile(Texture2D image, float maxSpeed, Entity owner, float dmg, ProjectileType type)
{
Image = image;
MaxSpeed = maxSpeed;
AccelerationSpeed = MaxSpeed;
Owner = owner;
Dmg = dmg;
pType = type;
}
public override void OnCollision(Collision collision)
{
#region If this projectile friendly
if (pType == ProjectileType.Friendly)
{
//If colliding with an enemy
if (collision.Other.GetType() == typeof(Enemy))
{
var enemy = (Enemy)collision.Other;
enemy.Health -= Dmg;
Destroy(this);
}
}
#endregion
#region If this projectile is hostile
if (pType == ProjectileType.Hostile)
{
}
#endregion
}
}
然后我想从我的游戏对象类更新调用OnCollision方法。 这是我试图告诉我的对象,如果他们collding,他们正在与碰撞谁:
if (GetType().IsAssignableFrom(typeof(Entity)))
{
Entity entity = (Entity)this;
if (GetType() == typeof(Player))
entity = (Player)this;
if (GetType() == typeof(Enemy))
entity = (Enemy)this;
if (GetType() == typeof(Projectile))
entity = (Projectile)this;
var entityCol = FindCollision(entity);
if (entityCol != null)
entity.OnCollision(entityCol);
}
我是新来的抽象类&压倒一切,所以我可能已经得到了整个想法都是错误的。 但它似乎我试过的Debug.WriteLine的东西,但没有在输出窗口显示出来没有达到OnCollision方法。
感谢您阅读&也许是想帮我出:)
Mediafire link下载项目要查看所有代码的情况下。
这可能是entityCol为空,所以没有尝试调用OnCollision方法? – PaulF
我只是试着调试值,它似乎甚至没有通过'if(GetType()。IsAssignableFrom(typeof(Entity)))''。玩家,实体和子弹继承了实体类......那么这不正确? –
嗨。只需要1分:您在UpdateCollisions中的嵌套循环不需要从0开始。它可以从+1开始。在碰撞事件没有发生的情况下,您需要在调用UpdateCollisions之后建立AllCollisions所具有的功能。该容器中的数据应该是什么? FindCollision是否返回正确的值?你需要把它分开一点点,直到你找到断开的链接。不是一个答案,但我希望我已经把你推向了正确的方向。 –