如何改变移动体的位置 - Box2D

Mer*_*ify 5 android box2d libgdx

我目前创建了一个动态的主体,并使用Vector2()以恒定速度移动.我想要的是当身体离开屏幕边缘时,瞬间从当前点回到原点.我该怎么做呢?

    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();
Run Code Online (Sandbox Code Playgroud)

noo*_*one 5

您可以使用Body.setTransform()该任务,但我不会这样做。setTransform()从长远来看会造成很多麻烦。

对我来说,这会导致奇怪的错误。例如,随机使用setTransform禁用我的代码ContactFilter,这花了我几天的调试时间,直到我发现为止。

此外,它还会引起非身体行为,因为您基本上可以传送Body

最好将其Body完全销毁,并在旧的相同初始位置重新创建一个新的。


use*_*130 2

a您可以通过此方法立即设置 Box2D 主体的位置:

a.setTransform(new_x, new_y, new_angle);

这样,您可以创建一个条件,当主体的 x 或 y 值位于屏幕之外时,将主体的 x 和 y 位置设置回其原始位置。

if(outsideBounds()){
    a.setTransform(start_x, start_y, start_angle);
}
Run Code Online (Sandbox Code Playgroud)

您可以通过检查对象的 Box2D 位置及其转换后的屏幕坐标,或者检查精灵的位置来检查对象是否在屏幕外。

收到 x 和 y 屏幕位置后,您可以将它们与屏幕边界进行比较,如下所示:

pos_x>screenWidth||pos_x<0||pos_y>screenHeight||pos_y<0

这可以通过包含对象的尺寸来改进,具体取决于您希望转换发生的时间:

(pos_x-objWidth)>screenWidth || (pos_x+objWidth)<0 ||
(pos_y-objHeight)>screenHeight || (pos_y+objHeight)<0
Run Code Online (Sandbox Code Playgroud)