I’m starting out with AndEngine (GLES2) and I’m trying to make a simple paddle Sprite and it’s connected body move when the TouchScreen is used. However, no matter how I tweak the code, it always returns a NullPointerException when I try to make a call on the body in question, no matter what the call happens to be.
Here’s my code for the creating the Paddle:
// Create the Paddle, body for said paddle, and register with the PhysicsWorld
final FixtureDef objectFixtureDef = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f);
paddleSprite = new Paddle(mPaddle, getVertexBufferObjectManager());
Body paddleBody = PhysicsFactory.createBoxBody(mPhysicsWorld, paddleSprite, BodyType.DynamicBody, objectFixtureDef);
mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(paddleSprite, paddleBody, true, false));
paddleBody.setUserData("Paddle");
// .... other Code for initializing sprites ..... //
mScene.attachChild(paddleSprite);
mScene.registerTouchArea(paddleSprite);
mScene.setTouchAreaBindingOnActionDownEnabled(true);
// Method for TouchScreenInteraction
public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
if(this.mPhysicsWorld != null){
paddleBody.setTransform(new Vector2((pSceneTouchEvent.getX() - paddleSprite.getWidth() / 2)/PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT,
(pSceneTouchEvent.getY() - paddleSprite.getHeight() / 2)/PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT),
0);
return true;
}
return false;
}
paddleSprite, paddleBody, and physicsWorld are global objects so access is not an issue.
The NullPointerException occurs the moment I touch the screen. If I remove the offending function call, it works, for after a bit of touching it occasionally breaks the game. Besides this problem, the Box2D engine runs smoothly and another dynamic object (a small ball) interacts with the paddle just fine.
I can post the rest of the code if the problem can’t be determined from this, but I’ve been stuck on this for a week and I’d really appreciate some help so I can actually get started with project.
Thank you very much in advance!
This line right here is your problem. You’re creating a new, locally scoped
paddleBody.When you try to use it for the touch event, you’re using a class level
paddleBodywhich probably hasn’t been initialized at all. Just remove theBodyfrom the offending line to avoid creating a new object: