我目前創建的物體是Dynamic,並以Vector2()以恆定速度移動。我想要的是當身體離開屏幕邊緣時,立即從當前點返回到其原始點。我該怎麼做呢?如何更改移動物體的位置 - Box2D
a.applyForceToCenter(aMovement, true);
a.applyTorque(3000, true);
FixtureDef fDef = new FixtureDef();
BodyDef ballD = new BodyDef();
ballD.type = BodyType.DynamicBody;
//random location for asteroid
int aLoc = (int) (aLocation * 15);
float x = 300;
switch(aLoc)
{
case 0:
ballD.position.set(x, -105);
break;
case 1:
ballD.position.set(x, -95);
break;
case 2:
ballD.position.set(x, -80);
break;
case 3:
ballD.position.set(x, -65);
break;
case 4:
ballD.position.set(x, -50);
break;
case 5:
ballD.position.set(x, -35);
break;
case 6:
ballD.position.set(x, -20);
break;
case 7:
ballD.position.set(x, -5);
break;
case 8:
ballD.position.set(x, 10);
break;
case 9:
ballD.position.set(x, 25);
break;
case 10:
ballD.position.set(x, 40);
break;
case 11:
ballD.position.set(x, 55);
break;
case 12:
ballD.position.set(x, 70);
break;
case 13:
ballD.position.set(x, 85);
break;
default:
ballD.position.set(x, 0);
}
PolygonShape asteroid = new PolygonShape();
asteroid.setAsBox(12.5f, 12.5f);
//asteroid definition
fDef.shape = asteroid;
fDef.density = .5f;
fDef.friction = .25f;
fDef.restitution = .75f;
a = world.createBody(ballD);
a.createFixture(fDef);
a.setFixedRotation(false);
//asteroid image
aSprite = new Sprite(new Texture("img/asteroid-icon.png"));
aSprite.setSize(12.5f * 4, 12.5f * 4);
aSprite.setOrigin(aSprite.getWidth()/2, aSprite.getHeight()/2);
a.setUserData(aSprite);
asteroid.dispose();
我如何獲得身體的位置? – Mercify
你可以通過'a.getPosition()'得到身體的位置'Vector2'。有關LibGDX/Box2D機構的更多信息,請查看[this](http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/physics/box2d/Body.html)鏈接。正如在其他人的回答中指出的那樣,使用'setTransform'可能會導致問題,所以使用此方法需要您自擔風險,或者避免出現問題,請遵循沒有人的建議並重新創建主體。 – user3312130