我想在我的2d平台游戏中添加一个健康栏,但我无法从栏中删除健康状况..
这是我在火箭课上到目前为止所尝试的内容:
public void CheckPlayerCollision()
{
Player player = GameWorld.Find("player") as Player;
List<GameObject> gameObjects = new List<GameObject>();
Health health = new Health(3, "Sprites/spr_health");
if (this.CollidesWith(player) && this.Visible)
foreach (GameObject obj in gameObjects)
{
SpriteGameObject h = obj as SpriteGameObject;
{
gameObjects.Remove(h);
}
}
}
命中检测有效,我可以在不使用火箭和播放器的情况下减少健康等级的健康状况 - &gt;请参阅下面的第二个示例,但是当我在健康类中编写火箭和玩家对象时尝试检测te碰撞时我仍然会出现空错误,这就是我尝试这种方式的原因。 - &GT;见下面的例子
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
Player player = GameWorld.Find("player") as Player;
Rocket rocket = GameWorld.Find("rocket") as Rocket;
foreach (GameObject obj in gameObjects)
{
SpriteGameObject h = obj as SpriteGameObject;
if (rocket.CollidesWith(player))
{
this.Remove(h);
return;
}
}
}
这不起作用。因为火箭或玩家是空的。
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
Player player = GameWorld.Find("player") as Player;
//Rocket rocket = GameWorld.Find("rocket") as Rocket;
foreach (GameObject obj in gameObjects)
{
SpriteGameObject h = obj as SpriteGameObject;
if (player.Position.X > 200)
{
this.Remove(h);
return;
}
}
}
当播放器移动超过200像素时,这会消除健康状况。
我无法找到让这个健康栏工作的方法..
这是一些可能有用的信息:
class Health : GameObjectList
public Health(int layer = 3, string id = "") : base(layer, id)
{
for(int i = 0; i < 255; i+=85)
if(i % 85 == 0)
{
SpriteGameObject health = new SpriteGameObject("Sprites/spr_health", 3);
health.Position = new Vector2(120 + i, 15);
this.Add(health);
}
}
...
class Rocket : AnimatedGameObject
...
partial class Player : AnimatedGameObject
答案 0 :(得分:0)
在以下代码中,您正在设置health
,但引用了gameObjects。您没有为gameObjects添加运行状况:
Health health = new Health(3, "Sprites/spr_health");
if (this.CollidesWith(player) && this.Visible)
foreach (GameObject obj in gameObjects)
{
SpriteGameObject h = obj as SpriteGameObject;
{
gameObjects.Remove(h);
}
}
在第二个例子中,你说火箭或玩家是空的。您没有在添加它们的位置包含代码,但由于您使用的是以下构造:
Player player = GameWorld.Find("player") as Player;
如果.Find
函数失败,则player
将为空。
最后,你说当玩家通过200px时,以下代码不会删除健康状况:
SpriteGameObject h = obj as SpriteGameObject;
if (player.Position.X > 200)
{
this.Remove(h);
return;
}
您不是在任何时候搜索或检查Health
对象。