I'm trying to move player body while contact with teleport but setTransform isn't executed.This is my contact listener
mPhysicsWorld.setContactListener(new ContactListener()
{
@Override
public void beginContact(Contact contact)
{
final Fixture fixtureA = contact.getFixtureA();
final Body bodyA = fixtureA.getBody();
final Fixture fixtureB = contact.getFixtureB();
final Body bodyB = fixtureB.getBody();
if(bodyA.getUserData().equals("Player") || bodyB.getUserData().equals("Player") )
{
for(int i = 0; i < telList.size(); i++)
{
if(bodyA.getUserData() == telList.get(i))
{
Teleport tl = telList.get(i);
if(tl.look.getX() > pl.look.getX())
{
pl.moveTo(150, 320);
pl.setLinearVelocity(new Vector2(-4.5f,0));
}else
{
pl.moveTo(150, 320);
pl.setLinearVelocity(new Vector2(4.5f,0));
}
break;
}else if(bodyB.getUserData() == telList.get(i))
{
Teleport tl = telList.get(i);
if(tl.look.getX() > pl.look.getX())
{
pl.moveTo(150, 320);
pl.setLinearVelocity(new Vector2(-4.5f,0));
}else
{
pl.moveTo(150, 320);
pl.setLinearVelocity(new Vector2(4.5f,0));
}
break;
}
}
}
}
@Override
public void endContact(Contact contact)
{
}
});
Player class has method
public void moveTo(int x, int y)
{
body.setTransform(new Vector2(x/32,y/32), 0);
}
and it works fine but isn't executed inside contact listener. And I'm sure contact is occured because it enters the "if" block and pl.setLinearVelocity(new Vector2(-4.5f,0)); is executed.
Thanks in advance
I don't know why it's impossieble to use setTransform inside contact listener but I solved this problem in this way. Created class for tasks
public class moveBodyTask {
Player pl;
float x;
float y;
boolean direction;
moveBodyTask(Player b, float x1, float y1, boolean d)
{
pl = b;
x = x1;
y = y1;
direction = d;
}
public void move()
{
pl.moveTo(x, y);
if(direction)
pl.setLinearVelocity(new Vector2(5,0));
else
pl.setLinearVelocity(new Vector2(-5,0));
}
}
then inside contack listener i just add new task to list
taskList.add(new moveBodyTask(pl, x+TILE_SIZE, y, true));
and execute it while update
scene.registerUpdateHandler(new IUpdateHandler()
{
@Override
public void onUpdate(float pSecondsElapsed) {
if(!taskList.isEmpty())
{
for(int i = 0; i < taskList.size(); i++)
{
taskList.get(i).move();
}
taskList.clear();
}
}
@Override
public void reset() {
// TODO Auto-generated method stub
}
});
for me it works fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With