From 94cd8b6f2bec9c47e6cb4ec1e8ce61521cbc3fac Mon Sep 17 00:00:00 2001 From: Lukas Klingsbo Date: Sun, 3 May 2020 12:59:50 +0200 Subject: [PATCH] Set userdata on the body instead of on fixture --- doc/box2d.md | 8 ++++++++ doc/examples/box2d/contact_callbacks/lib/main.dart | 4 ++-- lib/box2d/contact_callbacks.dart | 4 ++-- 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/doc/box2d.md b/doc/box2d.md index b6b2cad4d..9106c5212 100644 --- a/doc/box2d.md +++ b/doc/box2d.md @@ -18,6 +18,14 @@ A simple `Box2DGame` implementation example can be seen in the [examples folder] If you are using `Box2DGame` you can take advantage of its way of handling contacts between two `BodyComponent`s. +When creating the body definition for your `BodyComponent` make sure that you set the userdata to the current object, otherwise it will not be possible to detect collisions. +Like this: +```dart +final bodyDef = BodyDef() + // To be able to determine object in collision + ..setUserData(this); +``` + To do this you have to make an implementation of `ContactCallback` where you set which two types that it should react when they come in contact. If you have two `BodyComponent`s named Ball and Wall and you want to do something when they come in contact you would do like this: diff --git a/doc/examples/box2d/contact_callbacks/lib/main.dart b/doc/examples/box2d/contact_callbacks/lib/main.dart index a18a08a1b..a7f513f41 100644 --- a/doc/examples/box2d/contact_callbacks/lib/main.dart +++ b/doc/examples/box2d/contact_callbacks/lib/main.dart @@ -38,14 +38,14 @@ class Ball extends BodyComponent { shape.radius = radius; final fixtureDef = FixtureDef() - // To be able to determine object in collision - ..setUserData(this) ..shape = shape ..restitution = 1.0 ..density = 1.0 ..friction = 0.1; final bodyDef = BodyDef() + // To be able to determine object in collision + ..setUserData(this) ..position = position ..type = BodyType.DYNAMIC; diff --git a/lib/box2d/contact_callbacks.dart b/lib/box2d/contact_callbacks.dart index ea70094ad..478c48618 100644 --- a/lib/box2d/contact_callbacks.dart +++ b/lib/box2d/contact_callbacks.dart @@ -40,8 +40,8 @@ class ContactCallbacks extends ContactListener { } void _maybeCallback(Contact contact, ContactCallback callback, Function f) { - final Object a = contact.fixtureA.userData; - final Object b = contact.fixtureB.userData; + final Object a = contact.fixtureA.getBody().userData; + final Object b = contact.fixtureB.getBody().userData; final ContactTypes wanted = callback.types; if (wanted.match(a, b) || (wanted.has(BodyComponent) && wanted.hasOne(a, b))) {