超级玛丽,冒险岛,魂斗罗等游戏主场景都有瓦片地图画成,它的作用可见一斑,它可以用tiled Qt软件画成,在辅助篇中讲讲解tiled Qt软件的使用
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); }
物理世界想象成我们的世界就行,其中包括物理世界的实质,皮肤(人的衣服),刚体(人),连接器(设置弹性,密度,摩擦力),关节,碰撞检测,物体在物理世界中的添加与移除等
this.mPhysicsWorld = new FixedStepPhysicsWorld(30, new Vector2(0, 80), true, 8, 1);//Vector()设置的是力,就是向下为80N的力
很简单,就是一个Sprinte或者是AnimateSprite图片的创建,物体外边的变化就是皮肤的变化啦
// 创建player,并别加载到scene中 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.DynamicBody, playerFixtureDef);//BodyType有三种,一种是DynamicBody,运动的重型物体,一种是KinematicBody,运动的轻型物体,最后一种StaticBody,静态物体,比如墙体,就是这一种
this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector( player, mPlayerBody, true, false) );
mEngine.runOnUpdateThread(new Runnable() { @Override public void run() { final PhysicsConnector physicsConnector = mPhysicsWorld.getPhysicsConnectorManager().findPhysicsConnectorByShape(physicalmap.get(bodyb));//通过皮肤获得连接器 if (physicsConnector != null) { mPhysicsWorld.unregisterPhysicsConnector(physicsConnector);//注销连接器 bodya.setActive(false); mPhysicsWorld.destroyBody(bodyb);//摧毁物体 mScene.detachChild(physicalmap.get(bodyb)); physicalmap.remove(bodyb);//physicalmap是皮肤与刚体结合的结合 System.gc(); } } });
一定要放到一个线程中,不然很容易出错误
在物理世界上注册
this.mPhysicsWorld.setContactListener(new ContactListener() { @Override public void preSolve(Contact arg0, Manifold arg1) { // TODO Auto-generated method stub } @Override public void postSolve(Contact arg0, ContactImpulse arg1) { // TODO Auto-generated method stub } @Override public void endContact(Contact arg0) { // TODO Auto-generated method stub } @Override public void beginContact(Contact arg0) { // TODO Auto-generated method stub final Body bodya=arg0.getFixtureA().getBody();//获得bodya final Body bodyb=arg0.getFixtureB().getBody();//获得bodyb String ida=(String) bodya.getUserData();//通过bodya,bodyb对碰撞的物体进行处理 String idb=(String) bodyb.getUserData(); if("mPlayerBody".equals(idb)&&"bossBody".equals(ida)) { scoresEditor.putInt("user0", score); scoresEditor.commit(); lifeEditor.putInt("life", live); lifeEditor.commit(); System.gc(); mHandler.postDelayed(boss, 2000);//2秒钟后到gameover界面 } });