xamarinbox2dcocossharp

b2World.CreateBody returns null with CocosSharp and Box2D


I am playing around with CocosSharp and Box2D. I'm trying to create a world and add a ground body to it. Here's my code:

var gravity = b2Vec2.Zero;
gravity.Set(0f, -9.8f);

world = new b2World(gravity);
world.SetAllowSleeping(false);
world.SetContinuousPhysics(true);

var groundBodyDef = new b2BodyDef();
groundBodyDef.position.Set(0, 0);

var groundBody = world.CreateBody(groundBodyDef);

The problem comes at the last line. world.CreateBody(groundBodyDef) returns null.

I looked at the implementation for b2World.CreateBody and saw that it will only return null if IsLocked is true. My understanding is that IsLocked is true when the world is stepping. However, I see when running my code that IsLocked is actually false, yet CreateBody still returns null.

All the examples I've looked at follow the same basic setup of the b2World. Is there something I'm missing?

I'm testing this on an Android emulator, if that makes a difference.

EDIT 5/27: After learning more about the problem, I now know that there is some important information that I didn't think was necessary to include in my original question. I was wrong. I used the CocosSharp Visual Studio template to create the solution and projects. This is the reason the whole thing doesn't work on Android. I'll explain in the answer.


Solution

  • So it turns out that it does matter very much that I was testing on Android. The VS Template for CocosSharp does not add a reference for box2d.dll to the Android project. The Windows Phone and iOS projects both have the reference and my above code works as expected on both of those platforms.

    The Android project has a Box2dTest.dll reference, which, I'm assuming, is what allowed my code to build and run at all.

    I was finally pointed in the right direction late last night after finding another question that doesn't seem like the same problem on the surface, but provides a working answer. I needed to install the CocosSharp.PCL.Shared Nuget package to my Android project. That wasn't the end of the road, however. I started getting build errors from it.

    So, my ultimate solution to the problem was to add a reference to the CocosSharp.PCL.Shared Nuget package to a separate test project, copy the package folder over to my current solution's Package folder, then add an assembly reference to only box2d.dll. The other stuff it added with the Nuget package just caused more grief for me.

    After doing all of this, my code runs on Android.

    CocosSharp is pretty cool so far, but there's definitely room for improvement in the Visual Studio templates for it.