我目前正在开发一个使用 Farseer Physics for XNA 的游戏项目。现在我有两个类扩展了 Farseer 附带的 Body 类。下面是我让它们发生碰撞的代码。
下面的类应该有点不言自明。基本上,我希望玩家能够与世界上所有的瓷砖发生碰撞。
public Player(World gameWorld, GameWindow Window, int playernum, Texture2D sprite) : base(gameWorld)
{
//place the player in the center of the screen - this whole method can be changed
Position = new Vector2(Window.ClientBounds.Width / 2, Window.ClientBounds.Height / 2);
playerSprite = sprite;
playerNum = (PlayerIndex)playernum;
//Fixture stuff
playerFixture = FixtureFactory.AttachRectangle(sprite.Width, sprite.Height, 1, new Vector2(), this);
playerFixture.CollisionCategories = Category.Cat2;
playerFixture.CollidesWith = Category.Cat1;
playerFixture.OnCollision += playerOnCollision;
//initialize the melee weapon
//initialize the ranged weapon
}
public Tile(World gameWorld, Vector2 location, Game1 game, Vector2 offset) : base(gameWorld)
{
//Loading content in the constructor for simplicity's sake because the content manager is initialized by the time the stage is created
health = 100;
prevhealth = health;
maxhealth = health;
this.game = game;
contentName = game.random.NextDouble() > 0.5 ? "Images/Tiles/MarbleTilesBreak" : "Images/Tiles/MarbleTiles1Break";
tileTex = game.Content.Load<Texture2D>(contentName + "0");
//breakSound = game.Content.Load<SoundEffect>("Tiles/FloorBreaking");
location.X *= tileTex.Width;
location.Y *= tileTex.Height;
location += offset;
Position = location;
tileFixture = FixtureFactory.AttachRectangle(tileTex.Width, tileTex.Height, 1, new Vector2(), this);
tileFixture.CollisionCategories = Category.Cat1;
tileFixture.CollidesWith = Category.Cat2;
tileFixture.OnCollision += _OnCollision;
}
我的 _OnCollision 看起来像这样:
public bool _OnCollision(Fixture fix1, Fixture fix2, Contact con)
{
if (fix2.CollisionCategories == Category.Cat2)
{
health -= 10f;
}
return false;
}
然而,当我运行代码时,没有任何碰撞的迹象。当一个图块的生命值为 0 时,应该将其删除,但不会删除任何图块。