Rafi Levy
Rafi Levy

Reputation: 123

Creating custom contact delegates with Xamarin SpriteKit in C#

I would like to override the didBeginContact function so as to implement custom logic when two physics objects in my scene collide.

I understand how this would be done in Swift by first setting the contact delegate to be the scene object itself and then setting up the didBeginContact function as below:

self.physicsWorld.contactDelegate = self

func didBeginContact(contact: SKPhysicsContact) {
    //logic goes here
}

I am unable to work out how to implement such a system when using SpriteKit with Xamarin in C#. I have tried creating a custom Contact Delegate class which is a subclass of SKPhysicsContactDelegate and setting the scene's PhysicsWorld.ContactDelegate property to be an instance of this class but I noticed no change when running my application.

public class CollisionDelegate : SKPhysicsContactDelegate
{
    public override void DidBeginContact(SKPhysicsContact contact)
    {
        if (contact.BodyA.CategoryBitMask == 1 && 
contact.BodyB.CategoryBitMask == 3)
        {
            contact.BodyB.Node.RemoveFromParent();
        }
        else if (contact.BodyA.CategoryBitMask == 3 && 
contact.BodyB.CategoryBitMask == 1)
        {
            contact.BodyA.Node.RemoveFromParent();
        }
    }
}

Then in my SKScene class:

public override void DidMoveToView(SKView view)
{
    PhysicsWorld.ContactDelegate = new CollisionDelegate();
    //Other scene initilaisation 
}

Upvotes: 0

Views: 185

Answers (0)

Related Questions