2013-02-18 113 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()方法,该方法比上述方法更优雅地检测碰撞。