Question

I'm trying to get SFML.NET working with Box2DX.

I'm making a simple pong game, and only need to use collision detection and collision callbacks from Box2DX.

I have overridden ContactListener with my own, and it is working fine. The problem is that when I use body.SetUserData() and pass in Sprite object from SFML.NET, I have no idea how I can compare which Sprites collide.

This is what I have now, and it isn't working:

class MyContactListener : ContactListener
{
    public override void Add(ContactPoint point)
    {
        Sprite spriteA = (Sprite)point.Shape1.GetBody().GetUserData();
        Sprite spriteB = (Sprite)point.Shape2.GetBody().GetUserData();

        if (spriteA == spriteB || spriteB == spriteA)
            Console.WriteLine("Same sprites colliding.");
        else
            Console.WriteLine("Different sprites colliding.");

    }
    public override void Persist(ContactPoint point) { }
    public override void Remove(ContactPoint point) { }
    public override void Result(ContactResult point) { }
}

This always prints "Different sprites colliding" when a contact is added, even when the sprites are same.

I want to pass in Sprite object, because I need to draw the sprites using body.GetUserData();

Was it helpful?

Solution

I added a superclass Entity, which I inherited with my Ball, Enemy and Player classes. Now it's possible to compare classes.

I don't pass in Sprite as UserData anymore. I pass in the superclass Entity. I access the sprites through the class instances in my Draw() method.

In class Player : Entity

this.playerBody.SetUserData(this);

In class MyContactListener:

class MyContactListener : ContactListener
{
    public override void Add(ContactPoint point)
    {
        Body bodyA = point.Shape1.GetBody();
        Body bodyB = point.Shape2.GetBody();

        Entity typeA = (Entity)bodyA.GetUserData();
        Entity typeB = (Entity)bodyB.GetUserData();

        // Ball collision with Enemy
        if ((typeA is Enemy && typeB is Ball) || (typeB is Ball && typeA is Enemy))
        {
            // Do something based on the collision
        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top