我正在使用Box2d - Box2dx的XNA端口在C#中编写XNA游戏。Box2d:设置活动和不活动
树木或僵尸等实体表示为GameObjects。 GameObjectManager
增加,并从游戏世界中将其删除:
/// <summary>
/// Does the work of removing the GameObject.
/// </summary>
/// <param name="controller">The GameObject to be removed.</param>
private void removeGameObjectFromWorld(GameObjectController controller)
{
controllers.Remove(controller);
worldState.Models.Remove(controller.Model);
controller.Model.Body.SetActive(false);
}
public void addGameObjectToWorld(GameObjectController controller)
{
controllers.Add(controller);
worldState.Models.Add(controller.Model);
controller.Model.Body.SetActive(true);
}
controllers
是GameObjectController
实例的集合。
worldState.Models
是GameObjectModel
实例的集合。
当我从Box2D中删除GameObjects这种方式,这种方法被称为:
void IContactListener.EndContact(Contact contact)
{
GameObjectController collider1 = worldQueryUtils.gameObjectOfBody(contact.GetFixtureA().GetBody());
GameObjectController collider2 = worldQueryUtils.gameObjectOfBody(contact.GetFixtureB().GetBody());
collisionRecorder.removeCollision(collider1, collider2);
}
worldQueryUtils:
// this could be cached if we know bodies never change
public GameObjectController gameObjectOfBody(Body body)
{
return worldQueryEngine.GameObjectsForPredicate(x => x.Model.Body == body).Single();
}
此方法将引发错误:
System.InvalidOperationException was unhandled
Message="Sequence contains no elements"
Source="System.Core"
StackTrace:
at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
at etc
为什么这是否发生?我能做些什么来避免它?在调用body.SetActive()
之前,此方法已被调用很多次。我觉得这可能会搞砸了。
是controller.Model.Body一个box2d对象? – HyperCas 2010-04-07 15:55:58
这完全正确。 – 2010-04-07 16:55:54