Reputation: 1
How can I get sprite associated with body in andengine gles2? When bodies collide, I can get associated bodies but how can I get sprites associated with those bodies.
Please help me, I m new to andengine and box2d.
Thanks in advance.
Upvotes: 0
Views: 110
Reputation: 149
When you create the Body set the UserData to you sprite/entity like this:
yourBody.setUserData(yourSprite);
In the physic events you can get the sprite using:
public void beginContact(final Contact contact) {
final Body bA = contact.getFixtureA().getBody();
final Body bB = contact.getFixtureB().getBody();
final Object oA = contact.getFixtureA().getBody().getUserData();
final Object oB = contact.getFixtureB().getBody().getUserData();
final Sprite spriteA = (Sprite)oA;
final Sprite spriteB = (Sprite)oB;
}
Upvotes: 0
Reputation: 686
//Body variable in above Body bodyname;
//associate body with the sprite
body=PhysicsFactory.createBoxBody(physics_world, sprite_name, BodyType.DynamicBody, fixturedefinition);
Here in the last line fixture definition is to be defined as per your choice.
Upvotes: 0
Reputation: 11881
You've to register a PhysicConnector
so you can connect a sprite to a body:
physicsWorld.registerPhysicsConnector(new PhysicsConnector(sprite, body, true, true));
Hope it helps!
Upvotes: 0
Reputation: 961
When you create a Body that body let you set some extra data, like this:
myBody.setUserData( "Monster" ); //to set a String
myBody.setUserData( 333 ); //to set a number
myBody.setUserData( new MyData() ); //to set other Object
In fact this method accepts anything because it require a Object element. So you can create your own class to handle which sprite/entity is associated to that body, like this:
class BodyData{
public IEntity mEntity;
public String mName;
public BodyData(String pName, pEntity){
mEntity = pEntity;
mName = pName;
}
}
Then when you create your body and connect to a sprite you can do something like this:
myPlayerBody.setUserData( new BodyData("Player", myPlayerSprite ));
And when detecting the collide:
mPhysicsWorld.setContactListener(
new ContactListener(){
public void beginContact(Contact contact){
final Fixture mB1 = contact.getFixtureA();
final Fixture mB2 = contact.getFixtureB();
if(mB2.getBody().getUserData() != null && mB1.getBody().getUserData() != null){
final BodyData mBD1 = (BodyData)mB1.getBody().getUserData();
final BodyData mBD2 = (BodyData)mB2.getBody().getUserData();
Sprite mSprite1 = (Sprite) mBD1.mEntity;
Sprite mSprite2 = (Sprite) mBD2.mEntity;
// Do whatever you want to do with the sprites
}
}
public void endContact(Contact contact) {
}
public void preSolve(Contact contact, Manifold oldManifold) {
}
public void postSolve(Contact contact,
ContactImpulse impulse) {
}
}
);
Upvotes: 1