我设法加载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 :(得分:2)
我相信你所问的是如何实现碰撞处理。需要明确的是:碰撞检测是确定某些东西与其他东西发生碰撞(重叠)的步骤。碰撞处理是指你移动其中一个不再重叠的地方。在这种情况下,我假设我们已经过了碰撞检测和碰撞处理,因为你在一个名为“onTMXTileWithPropertiesCreated”的方法中,我猜这意味着玩家在这样的牌上。所以这就是这个想法,非常简单:
当由于玩家(或其他一些精灵)的移动,你发现精灵正在与你想要无法通行的精灵发生碰撞时 - 你的术语中的“真实”,你会想要的将精灵移回阻止它重叠的距离。
使用矩形执行此操作非常简单。使用其他形状进行操作会变得更复杂一些。因为您正在使用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()方法,它比上述方法更优雅地检测碰撞。
答案 1 :(得分: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);
}
玩得开心!