2013-02-18 111 views
2

我設法現在加載TMX地圖,我想創建障礙的精靈不能移動的物體,我恢復這樣的障礙:AndEngine:處理衝突與TMX

try { 
     final TMXLoader tmxLoader = new TMXLoader(this, this.mEngine.getTextureManager(), TextureOptions.BILINEAR_PREMULTIPLYALPHA, new ITMXTilePropertiesListener() { 
      @Override 
      public void onTMXTileWithPropertiesCreated(final TMXTiledMap pTMXTiledMap, final TMXLayer pTMXLayer, final TMXTile pTMXTile, final TMXProperties<TMXTileProperty> pTMXTileProperties) { 
       /* We are going to count the tiles that have the property "cactus=true" set. */ 
       if(pTMXTileProperties.containsTMXProperty("obstacle", "true")) { 
        //TMXTiledMapExample.this.mCactusCount++; 
        //coffins[coffinPtr++] = pTMXTile.getTileRow() * 15 + pTMXTile.getTileColumn(); 

       } 
      } 
     }); 

如何處理與障礙物碰撞,以防止玩家穿過障礙物(即像牆壁)?

+0

你會使用Astar路徑嗎? – eBehbahani 2013-02-19 14:11:45

回答

1

,因爲我用這個

if(pTMXTileProperties.containsTMXProperty("obstacle", "true")) { 
        //TMXTiledMapExample.this.mCactusCount++; 
        //coffins[coffinPtr++] = pTMXTile.getTileRow() * 15 + pTMXTile.getTileColumn(); 
        //initRacetrackBorders2(); 
        // This is our "wall" layer. Create the boxes from it 
         final Rectangle rect = new Rectangle(pTMXTile.getTileX()+10, pTMXTile.getTileY(),14, 14); 
         final FixtureDef boxFixtureDef = PhysicsFactory.createFixtureDef(0, 0, 1f); 
         PhysicsFactory.createBoxBody(mPhysicsWorld, rect, BodyType.StaticBody, boxFixtureDef); 
         rect.setVisible(false); 
         mScene.attachChild(rect); 
       } 

玩得開心!

2

我相信你問的是如何實現碰撞處理。要清楚:碰撞檢測是您確定某件事與其他事物發生碰撞(重疊)的步驟。碰撞處理就是您將這些東西之一移動到不再重疊的地方。在這種情況下,我假設我們已經過去了碰撞檢測,並且正在進行碰撞處理,因爲您使用的是名爲「onTMXTileWithPropertiesCreated」的方法,我猜測這意味着玩家處於這樣的狀態。因此,這裏的想法,把很簡單:

enter image description here

時,由於玩家的你發現了精靈與你想成爲不可逾越的一個精靈碰撞運動(或其他一些精靈) - 在你的術語中「真實」,你會想要將精靈移回距離,以防止它重疊。

用矩形做這件事很簡單。用其他形狀做它會變得更復雜一點。因爲你正在使用TMX瓷磚地圖,所以現在矩形可能會工作。這是矩形的一個基本示例。

public boolean adjustForObstacle(Rect obstacle) { 
    if (!obstacle.intersect(this.getCollisionRect())) return false; 

    // There's an intersection. We need to adjust now. 
    // Due to the way intersect() works, obstacle now represents the 
    // intersection rectangle. 

    if (obstacle.width() < obstacle.height()) { 
     // The intersection is smaller left/right so we'll push accordingly. 
     if (this.getCollisionRect().left < obstacle.left) { 
      // push left until clear. 
      this.setX(this.getX() - obstacle.width()); 
     } else { 
      // push right until clear. 
      this.setX(this.getX() + obstacle.width()); 
     } 
    } else { 
     if (this.getCollisionRect().top < obstacle.top) { 
      // push up until clear. 
      this.setY(this.getY() - obstacle.height()); 
     } else { 
      // push down until clear. 
      this.setY(this.getY() + obstacle.height()); 
     } 
    } 
    return true; 
} 

這是做什麼是計算重疊的矩形和沿着重疊的最小維度移動精靈的數量,這將使其不再重疊。由於您使用的是AndEngine,因此可以使用IShape中的collidesWith()方法,該方法比上述方法更優雅地檢測碰撞。