I'm trying to use Nape with HaxeFlixel. Sadly, there's almost no documentation on how to use the addons.nape
package and I just can't figure out why this code isn't moving the white rectangle (_test
). (I left out imports for simplicity)
class PlayState extends FlxNapeState
{
var _test = new FlxNapeSprite(16, 16);
override public function create():Void
{
super.create();
_test.makeGraphic(16, 16);
_test.body.type = BodyType.KINEMATIC;
add(_test);
}
override public function update():Void
{
_test.body.velocity.x = 100;
super.update();
}
}
There are two issues with your code:
Directly initializing the _test
variable leads to the FlxNapeSprite
constructor call happening in the constructor of your PlayState
. create()
is called after the state constructor. This can cause crashes and otherwise weird behavior since Flixel does its internal cleanup between the constructor call of the new state and create()
(graphics are disposed, for example, and in this case the Nape Space
instance doesn't exist yet since it's created in the super.create()
call).
The FlxNapeSprite
constructor has a createRectangularBody
argument which defaults to true
and calls the function of that same name if true
. Since you're not passing any asset to the constructor, it ends up creating a Shape
with a width and height of 0. This leads to the following error:
Error: Cannot simulate with an invalid Polygon
Instead, you'll want to call createRectangularBody()
manually after makeGraphic()
to create a Shape
that matches the graphic's dimensions.
The complete, working code looks like this:
package;
import flixel.addons.nape.FlxNapeSprite;
import flixel.addons.nape.FlxNapeState;
class PlayState extends FlxNapeState
{
override public function create():Void
{
super.create();
var _test = new FlxNapeSprite(16, 16);
_test.makeGraphic(16, 16);
_test.createRectangularBody();
_test.body.velocity.x = 100;
add(_test);
}
}
Regarding documentation, the FlxNape demo is a great resource to learn from.