andengine游戏引擎实用篇-box2d与瓦片地图的结合使用

1)加载瓦片地图

 //加载TMX
		try {
			final TMXLoader tmxLoader = new TMXLoader(this,
					this.mEngine.getTextureManager(), TextureOptions.NEAREST,
					null);
			this.mTMXTiledMap = tmxLoader.loadFromAsset(this,"sence"+leave.getInt("leave", 1)+".tmx");
		} catch (final TMXLoadException tmxle) {
			Debug.e(tmxle);
		}

		//将每一层TMXLayer加载到scene中
		for (int i = 0; i < this.mTMXTiledMap.getTMXLayers().size(); i++) {
			TMXLayer layer = this.mTMXTiledMap.getTMXLayers().get(i);
				mScene.attachChild(layer);
		}


2)创建物理世界

	this.mPhysicsWorld = new FixedStepPhysicsWorld(30, new Vector2(0, 	80),
				true, 8, 1);

3)创建主要人物,屏幕更新方式注册为按照物理世界中的方式更新

final AnimatedSprite player = new AnimatedSprite(centerX-200, centerY-100,
				this.mPlayerTextureRegion);//
		this.mBoundChaseCamera.setChaseEntity(player);
		final FixtureDef playerFixtureDef = PhysicsFactory.createFixtureDef(0,
				0, 0.5f);
		mPlayerBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, player,
				BodyType.StaticBody, playerFixtureDef);
	
		this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(
				player, mPlayerBody, true, false) {
			@Override
			public void onUpdate(float pSecondsElapsed) {
				super.onUpdate(pSecondsElapsed);
				mBoundChaseCamera.updateChaseEntity();//相机更新方式
			}
		});
		physicalmap.put(mPlayerBody, player);
		mPlayerBody.setUserData("mPlayerBody");
		mScene.attachChild(player);


4)读取每个瓦片,与物理世界结合

	public void creatBox(TMXTiledMap map)
	{
		
		for (final TMXObjectGroup group : this.mTMXTiledMap
				.getTMXObjectGroups()) {
			if (group.getTMXObjectGroupProperties().containsTMXProperty("box",
					"true")) {
				//如果瓦片地图中图块的键为“box”,值为“true”
				
				for (final TMXObject object : group.getTMXObjects()) {
					final Sprite box = new Sprite(object.getX(), object.getY(),this.mBoxTextureRegion);//创建皮肤
					final FixtureDef boxFixtureDef = PhysicsFactory
							.createFixtureDef(0, 0, 1f);//连接器
					final Body boxBody=PhysicsFactory.createBoxBody(this.mPhysicsWorld, box,
							BodyType.DynamicBody, boxFixtureDef);//刚体
					boxBody.setUserData("boxBody");//为刚体设置值,供碰撞检测时使用
					
					physicalmap.put(boxBody, box);//供碰撞检测时使用,通过键找到值
					this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(
							box, boxBody, true, false));//注册到物理世界中
					mScene.attachChild(box);//将皮肤天剑到sence中
					
				}
			}
		}
	}


 

 

你可能感兴趣的:(andengine游戏引擎实用篇-box2d与瓦片地图的结合使用)