Reputation: 1199
I'm learning how to use box2d and andEngine. I am trying to make my sprite with body move. I made it work before when I coded everything in onCreateScene, but now I want to make a separate class for my sprite. So right now my onCreateScene looks like this:
mScene = new Scene();
mScene.registerUpdateHandler(physicsWorld);
Kapsel kapselBialy = new Kapsel(100, 100, 100, 100, ResourceManager.getInstance().mBialyKapselRegion, getVertexBufferObjectManager(), physicsWorld);
mScene.registerTouchArea(kapselBialy);
mScene.setTouchAreaBindingOnActionDownEnabled(true);
mScene.attachChild(kapselBialy);
pOnCreateSceneCallback.onCreateSceneFinished(mScene);
And my Kapsel class looks like this:
public class Kapsel extends Sprite {
private Body body;
public Kapsel(float pX, float pY, float pWidth, float pHeight,
ITextureRegion pTextureRegion,
VertexBufferObjectManager pVertexBufferObjectManager, PhysicsWorld physicsWorld) {
super(pX, pY, pWidth, pHeight, pTextureRegion, pVertexBufferObjectManager);
createPhysics(physicsWorld);
}
//definiowanie zahchowań po dotyku
@Override
public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY){
if(pSceneTouchEvent.getAction() == TouchEvent.ACTION_UP){
body.setLinearVelocity(-((pSceneTouchEvent.getX()/32 - body.getPosition().x) * 10), -((pSceneTouchEvent.getY()/32 - body.getPosition().y) * 10));
}
return true;
}
//Tworzenie ciała i fizyki dla kapsla
private void createPhysics(PhysicsWorld physicsWorld){
body = PhysicsFactory.createCircleBody(physicsWorld, this, BodyType.DynamicBody, PhysicsFactory.createFixtureDef(1.0f, 0.5f, 0.5f));
physicsWorld.registerPhysicsConnector(new PhysicsConnector(this, body, true, true));
}
}
My sprite shows properly, but the touch event doesn't work. Am I missing something?
Upvotes: 0
Views: 99
Reputation: 1199
Ok so the problem was that in onPopulateScene()
i did not put pOnPopulateSceneCallback.onPopulateSceneFinished();
. Turns out that even if you define your scene and sprites in onCreateScene() it is still needed t put that in onPopulateScene(). Still I will keep in mind that I should not put 'this' in constructor (even if it works :) ).
Upvotes: 0
Reputation: 6018
In Kapsel
you are referencing this
from within the constructor. This happens since the constructor calls createPhysics
which in turn calls physicsWorld.registerPhysicsConnector(new PhysicsConnector(this, body, true, true))
. Note how this
is referenced as it is passed to the PhysicsConnector
constructor.
Referencing this
that way in the constructor isn't a good idea, to say the least. You may read some more on this subject here.
I'm pretty sure that is why you are experiencing problems. Try rearranging the code so that does not happen. You can take a look at some suggestions here of how to work around these kinds of situations.
Upvotes: 1