我正在尝试在与传送接触时移动玩家身体但是没有执行setTransform。这是我的联系人听众
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)
{
}
});
玩家类有方法
public void moveTo(int x, int y)
{
body.setTransform(new Vector2(x/32,y/32), 0);
}
它工作正常,但不在联系人监听器内执行。我确定接触是因为它进入“if”块和pl.setLinearVelocity(新的Vector2(-4.5f,0));被执行。
提前致谢
答案 0 :(得分:6)
我不知道为什么在联系人监听器中使用setTransform是不可能的,但我以这种方式解决了这个问题。为任务创建的课程
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));
}
}
然后在contack监听器中我只是添加新任务列表
taskList.add(new moveBodyTask(pl, x+TILE_SIZE, y, true));
并在更新时执行
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
}
});
对我而言,它运作良好。