I am using Farseer 3.3 and XNA.
I have a problem that i just cant solve in a nice way.
I ha开发者_如何学Cve a situation where there is a world with bodys in it all working away doing there thing.
I then have an object thats body is set to not enabled, is there a nice way of checking if the body is currently colliding with anything? i.e. to know if it would be a clean spawn should I make it enabled and set it to dynamic?
Thanks in advance.
For anyone else finding this post while trying to solve the same kind of problem here is how I did it in the end.
In this example I use the word Item to represent the class that contains a body etc, this could be your player / bullet / whatever.
In your Item class subscribe to the bodies on collision and on separation events.
this.Body.OnCollision += Body_OnCollision;
this.Body.OnSeparation += Body_OnSeperation;
then setup a member for the item to hold a count of collisions and separations.
private int _canBePlacedCounter = 0;
On the event handler methods, increase of decrease the member count. In the code below there are extra conditions as for myself, I only want to perform these operations when an item is being placed into the "world".
private bool Body_OnCollision(Fixture fixturea, Fixture fixtureb, Contact contact)
{
if(this.IsBeingPlaced)
{
_canBePlacedCounter++;
}
return true;
}
private void Body_OnSeperation(Fixture fixturea, Fixture fixtureb)
{
if (this.IsBeingPlaced)
{
_canBePlacedCounter--;
}
}
We then can setup a simple public property (this really should be a method if we want to get into coding standards but this is not the time or place)
public bool CanBeDropped
{
get
{
if (_canBePlacedCounter == 0) return true;
else return false;
}
}
The reason for this implementation is, I originally had a bool which I set to true or false whenever I got one of the events. The problem is... If your item collides with item A, then collides with item B then leaves item A you get a reading of not colliding. So... using a counter like this we can count in and count out all of the collisions and separations. Belive me this works like an absolute charm.
Hope it is of use to someone out there.
UPDATE: I have found that this only works well with basic rectangles. If you get into bodies with many polygons such as those automatically generated from images its very unreliable as for whatever reason farseer regularly raises less separation events than it does collision events meaning the counter often does not return to 0.
精彩评论