2014-03-05 51 views
5

我目前創建的物體是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(); 

回答

2

你可以設置你的Box2D a體的位置立即通過這種方法:

a.setTransform(new_x, new_y, new_angle);

有了這個,你可以創建一個套在身上的X和Y位置後面的條件當身體的x或y值超出屏幕時,將其移動到其原始位置。

if(outsideBounds()){ 
    a.setTransform(start_x, start_y, start_angle); 
} 

您可以檢查,或檢查精靈的位置,你的對象是否是由兩種檢查其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 
+0

我如何獲得身體的位置? – Mercify

+0

你可以通過'a.getPosition()'得到身體的位置'Vector2'。有關LibGDX/Box2D機構的更多信息,請查看[this](http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/physics/box2d/Body.html)鏈接。正如在其他人的回答中指出的那樣,使用'setTransform'可能會導致問題,所以使用此方法需要您自擔風險,或者避免出現問題,請遵循沒有人的建議並重新創建主體。 – user3312130

4

你可以使用Body.setTransform()該任務,但我不會那樣做。從長遠來看,setTransform()會造成很多麻煩。

對我來說,它會導致奇怪的錯誤。例如,使用setTransform在隨機時刻禁用了我的ContactFilter,這花費了我幾天的調試時間,直到我找到爲止。

此外,它會導致非物理行爲,因爲你基本上傳送了Body

更好的辦法是完全摧毀Body並在舊的相同的初始位置重新創建一個新的。

+0

我該怎麼做,我想要的方式?我想要的是,隨着小行星在屏幕上移動,然後放回到原來的位置再次移動,這種情況會永遠發生。 – Mercify