网上有文章介绍如何构造 撞球游戏( http://www.raywenderlich.com/28602/intro-to-box2d-with-cocos2d-2-x-tutorial-bouncing-balls )

但是它是基于 Apple, 我通过实践构造了 Android 下项目并成功编译运行


现假设已经生成 Android 下的 Hello World 项目 (可以参见 分析Cocos2d Android 项目的生成和运行)

现在我们通过改写 HelloWorldScene.h, HelloWorldScene.cpp 生成撞球游戏


集成 box2d

Cocos 已经帮我们集成了 Box2D ( cocos2d-2.1rc0-x-2.1.2\external\Box2D ), 并且 build 到 cocos_extension_static, 最终生成的 libgame 会被自动 load, 因此我们直接使用就可以了

就是头文件有些问题, 用下面方法解决

修改Cocos3\proj.android\jni\Android.mk

LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes

改为

LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes $(LOCAL_PATH)/../../../external/Box2D


修改文件

(参照 http://www.raywenderlich.com/28602/intro-to-box2d-with-cocos2d-2-x-tutorial-bouncing-balls) 

改动 HelloWorldScene.h

#ifndef __HELLOWORLD_SCENE_H__#define __HELLOWORLD_SCENE_H__#include "cocos2d.h"#include "Box2D.h"#define PTM_RATIO 32.0class HelloWorld : public cocos2d::CCLayer{public:    // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone    virtual bool init();      // there's no 'id' in cpp, so we recommand to return the exactly class pointer    static cocos2d::CCScene* scene();        // a selector callback    void menuCloseCallback(CCObject* pSender);    // implement the "static node()" method manually    CREATE_FUNC(HelloWorld);b2World *_world;    b2Body *_body;    cocos2d::CCSprite *_ball;#endif // __HELLOWORLD_SCENE_H__

改动 HelloWorldScene.cpp

#include "HelloWorldScene.h"#include "SimpleAudioEngine.h"using namespace cocos2d;using namespace CocosDenshion;CCScene* HelloWorld::scene(){// 'scene' is an autorelease objectCCScene *scene = CCScene::create();// 'layer' is an autorelease objectHelloWorld *layer = HelloWorld::create();// add layer as a child to scenescene->addChild(layer);// return the scenereturn scene;}// on "init" you need to initialize your instancebool HelloWorld::init(){//////////////////////////////// 1. super init firstif ( !CCLayer::init() ){return false;}CCMenuItemImage *pCloseItem = CCMenuItemImage::create("CloseNormal.png","CloseSelected.png",this,menu_selector(HelloWorld::menuCloseCallback) );pCloseItem->setPosition( ccp(CCDirector::sharedDirector()->getWinSize().width - 20, 20) );// create menu, it's an autorelease objectCCMenu* pMenu = CCMenu::create(pCloseItem, NULL);pMenu->setPosition( CCPointZero );this->addChild(pMenu, 1);CCSize winSize = CCDirector::sharedDirector()->getWinSize();CCSprite* _ball = CCSprite::create("ball.png");this->addChild(_ball, 0);_ball->setPosition( ccp(100,300) );b2Vec2 gravity(0.0f, -8.0f);_world = new b2World(gravity);b2BodyDef groundBodyDef;groundBodyDef.position.Set(0,0);b2Body *groundBody = _world->CreateBody(&groundBodyDef);b2EdgeShape groundEdge;b2FixtureDef boxShapeDef;boxShapeDef.shape = &groundEdge;//wall definitions//bottomgroundEdge.Set(b2Vec2(0,0), b2Vec2(winSize.width /PTM_RATIO, 0));groundBody->CreateFixture(&boxShapeDef);// leftgroundEdge.Set(b2Vec2(0,0), b2Vec2(0,winSize.height/PTM_RATIO));groundBody->CreateFixture(&boxShapeDef);// topgroundEdge.Set(b2Vec2(0, winSize.height/PTM_RATIO),b2Vec2(winSize.width/PTM_RATIO, winSize.height/PTM_RATIO));groundBody->CreateFixture(&boxShapeDef);// rightgroundEdge.Set(b2Vec2(winSize.width/PTM_RATIO, winSize.height/PTM_RATIO),b2Vec2(winSize.width/PTM_RATIO, 0));groundBody->CreateFixture(&boxShapeDef);b2BodyDef ballBodyDef;ballBodyDef.type = b2_dynamicBody;ballBodyDef.position.Set(100/PTM_RATIO, 300/PTM_RATIO);ballBodyDef.userData = _ball;_body = _world->CreateBody(&ballBodyDef);b2CircleShape circle;circle.m_radius = 26.0/PTM_RATIO;b2FixtureDef ballShapeDef;ballShapeDef.shape = &circle;ballShapeDef.density = 1.0f;ballShapeDef.friction = 0.2f;ballShapeDef.restitution = 0.8f;_body->CreateFixture(&ballShapeDef);schedule(schedule_selector(HelloWorld::tick)); //schedule(schedule_selector(HelloWorld::kick), 5); CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic("background-music-aac.wav", true);return true;}void HelloWorld::menuCloseCallback(CCObject* pSender){CCDirector::sharedDirector()->end();#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)exit(0);#endif}void HelloWorld::tick(float dt) { _world->Step(dt, 10, 10);for(b2Body *b = _world->GetBodyList(); b; b=b->GetNext()) {    if (b->GetUserData() != NULL) {CCSprite *ballData = (CCSprite *)b->GetUserData();ballData->setPosition(ccp(b->GetPosition().x * PTM_RATIO,b->GetPosition().y * PTM_RATIO));ballData->setRotation(-1 * CC_RADIANS_TO_DEGREES(b->GetAngle()));}        }}

复制资源文件

把这些文件放到 you_project\Resources 下面


ball.png 我贴在下面, 别的文件都可以在 cocos2d-2.1rc0-x-2.1.2/samples/Cpp/SimpleGame 下找到



生成程序

先用NDK ./build_native.sh 编译重新生成 libgame.so

而后在 eclipse 重新生成 .apk, 并安装到设备上



你现在得到一个自动四处碰撞但却会慢慢停下来的球, 同时会播放背景音乐


加入触摸互动

HelloWorldScene.h 加入

class HelloWorld : public cocos2d::CCLayer {...void kick(); void registerWithTouchDispatcher();void ccTouchesEnded(cocos2d::CCSet* touches, cocos2d::CCEvent* event);};...}


HelloWorldScene.cpp

void HelloWorld::kick() {b2Vec2 force = b2Vec2(30, 30);_body->ApplyLinearImpulse(force,_body->GetPosition());}void HelloWorld::registerWithTouchDispatcher(){// CCTouchDispatcher::sharedDispatcher()->addTargetedDelegate(this,0,true);CCDirector::sharedDirector()->getTouchDispatcher()->addStandardDelegate(this,0);}void HelloWorld::ccTouchesEnded(CCSet* touches, CCEvent* event){// Choose one of the touches to work withCCTouch* touch = (CCTouch*)( touches->anyObject() );CCPoint location = touch->getLocation();CCLog("++++++++after  x:%f, y:%f", location.x, location.y);kick();}

还要在 bool HelloWorld::init() enable touch

this->setTouchEnabled(true);


以后你每次触摸屏幕, 球将会强力弹一次.


最后你得到一个有音乐,有互动,画面平滑的简单游戏.





更多相关文章

  1. NPM 和webpack 的基础使用
  2. 【阿里云镜像】使用阿里巴巴DNS镜像源——DNS配置教程
  3. Android(安卓)Studio 3.0 正式版本 发行说明 (翻译)
  4. Android(安卓)文件的上传
  5. Android(安卓)APK反编译查看源码及资源文件
  6. Android中音乐文件的信息详解【安卓源码解析二】
  7. Android设备与外接U盘实现数据文件夹拷贝到android设备
  8. Android(安卓)studio 删除无用代码
  9. Android(安卓)数据存储方式

随机推荐

  1. Android 开启之旅-学习路线
  2. Android应用程序的消息处理机制
  3. 关于android应用程序签名的一些事儿
  4. android 屏幕尺寸适配实现方案
  5. Android(安卓)自学之进度条ProgressBar
  6. Android手势与触摸事件的分发和消费机制
  7. Android 硬解码MediaCodec配合SurfaceVie
  8. iOS移动互联网流量超Android两倍
  9. 2016年Windows Phone将超越iPhone
  10. 利用BeautifulSoup的find_all()函数查找