感谢大家的鼓励和支持,今天进阶篇2奉献给大家。

不了解cocos2dx基本概念的朋友,请移步

http://blog.csdn.net/s_xing/article/details/18557631。

转载请注明出处http://blog.csdn.net/s_xing/article/details/20165097

感觉直接看代码太枯燥的,请关注视频讲解

更新:高清avi视频和源代码已经提供下载:

百度网盘:http://pan.baidu.com/s/1ELk78里面的进阶篇。

今天一共讲了五堂课,学习的是老外的一个游戏。原文地址:http://www.raywenderlich.com/28602/intro-to-box2d-with-cocos2d-2-x-tutorial-bouncing-balls。源代码如下

1. 主场景

#include "HelloWorldScene.h"
#include "Box2dUtils.h"
#include "MyContactListener.h"
#include "GameOverScense.h"
#include "SimpleAudioEngine.h"USING_NS_CC;#define PTM_RATIO 32.0fCCScene* 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 instance
bool HelloWorld::init()
{//// 1. super init firstif ( !CCLayer::init() ){return false;}CCSize screenSize = CCDirector::sharedDirector()->getVisibleSize();CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();// 创建球的cocos2d图形_ballSprite  = CCSprite::create("ball.png");_ballSprite->setPosition(ccp(39, 300));this->addChild(_ballSprite);_paddleSprite = CCSprite::create("paddle.png");_paddleSprite->setPosition(ccp(120, 50));this->addChild(_paddleSprite);// 创建box2d世界_world = new b2World(b2Vec2(0, 0));// 创建球_ball = Box2dUtils::createDynamicBody(_ballSprite->getPositionX() / PTM_RATIO,_ballSprite->getPositionY() / PTM_RATIO,_ballSprite,_world);b2CircleShape circle;circle.m_radius = _ballSprite->getContentSize().width / 2 / PTM_RATIO;Box2dUtils::createFixture(&circle,10, 0, 1.0, _ball);_ball->ApplyLinearImpulse(_ball->GetMass() * b2Vec2(11, 22), _ball->GetWorldCenter());// 添加底座_paddle = Box2dUtils::createDynamicBody(_paddleSprite->getPositionX() / PTM_RATIO,_paddleSprite->getPositionY() / PTM_RATIO,_paddleSprite,_world);b2PolygonShape boxShape;boxShape.SetAsBox(_paddleSprite->getContentSize().width / 2.0f / PTM_RATIO,_paddleSprite->getContentSize().height / 2.0f / PTM_RATIO);Box2dUtils::createFixture(&boxShape,8, 0, 0.5, _paddle);// 添加目标   被打击的砖块const int padding  = 10; float offsetX = 150.0f;for (int i = 0; i < 4; i ++){CCSprite* block = CCSprite::create("block.png");block->setPosition(ccp(offsetX, 400.0));block->setTag(3);this->addChild(block);//物理 实体b2Body* blockBody = Box2dUtils::createDynamicBody(offsetX/ PTM_RATIO, 400 / PTM_RATIO,block,_world);b2PolygonShape blockBox;blockBox.SetAsBox(block->getContentSize().width / 2.0f / PTM_RATIO,block->getContentSize().height / 2.0f / PTM_RATIO);Box2dUtils::createFixture(&blockBox,10.0f, 0.0f, 0.2f, blockBody);offsetX += (padding + block->getContentSize().width);}// 创建4面墙// b2BodyDef -->b2Bodyb2BodyDef groundBodyDef;groundBodyDef.type = b2_staticBody;groundBodyDef.position.Set(0, 0); // 相当于cocos2d 中的锚点_groundBody = _world->CreateBody(&groundBodyDef);// b2FixtureDef -->b2Fixtureb2EdgeShape groundShape;groundShape.Set(b2Vec2(0, 0), b2Vec2(screenSize.width / PTM_RATIO, 0));b2FixtureDef groundFixDef;groundFixDef.shape = &groundShape;groundFixDef.friction = 0.9f;_bottom = _groundBody->CreateFixture(&groundFixDef);// 创建左面 墙b2EdgeShape leftWall;leftWall.Set(b2Vec2(0, 0), b2Vec2(0, screenSize.height / PTM_RATIO));groundFixDef.shape = &leftWall;_groundBody->CreateFixture(&groundFixDef);// 创建右面的墙b2EdgeShape rightWall;rightWall.Set(b2Vec2(screenSize.width / PTM_RATIO, 0), b2Vec2(screenSize.width / PTM_RATIO, screenSize.height / PTM_RATIO));groundFixDef.shape = &rightWall;_groundBody->CreateFixture(&groundFixDef);// 创建 顶部b2EdgeShape top;top.Set(b2Vec2(0, screenSize.height / PTM_RATIO), b2Vec2(screenSize.width / PTM_RATIO, screenSize.height / PTM_RATIO));groundFixDef.shape = ⊤_groundBody->CreateFixture(&groundFixDef);this->scheduleUpdate();// 实现  指哪打哪  鼠标拖动到哪里 指定的物体移动到哪里// box2d joint 关节  this->setTouchEnabled(true);CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 0, true);_mouseJoint = NULL;// 平移关节 限制底座 只能水平方向移动b2PrismaticJointDef primaticJointDef;primaticJointDef.Initialize(_world->CreateBody(new b2BodyDef),_paddle,_paddle->GetWorldCenter(),b2Vec2(3.0, 0));_world->CreateJoint(&primaticJointDef);listener = new MyContactListener;_world->SetContactListener(listener);_score = 0;CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic("background-music-aac.WAV", true);return true;
}bool HelloWorld::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent){CCPoint touchPos = pTouch->getLocation();b2Vec2  touchPhysicsPos(touchPos.x / PTM_RATIO,touchPos.y / PTM_RATIO);b2Fixture* paddleFix = _paddle->GetFixtureList(); //得到底座的 fixture ---包含了形状信息/*CCRect paddleRect;   // 在cocos2d 世界中判断paddleRect.containsPoint(touchPos);*/if (paddleFix->TestPoint(touchPhysicsPos)){ //触摸点在paddle的范围内  在物理世界中判断// 鼠标关节  鼠标控制我们的底座    applyLinearImpulseb2MouseJointDef mouseJointDef;mouseJointDef.bodyA = _world->CreateBody(new b2BodyDef);mouseJointDef.bodyB = _paddle;mouseJointDef.maxForce = 1000.0 * _paddle->GetMass();mouseJointDef.target = touchPhysicsPos; //设置物体的目标位置_mouseJoint = (b2MouseJoint*)_world->CreateJoint(&mouseJointDef);//CCLog("touch began true.\n");return true;// 该 touch 代理上的ccTouchMoved  ccTouchEnded 会得到执行}CCLog("touch began false.\n");return false; // 该 touch 代理上的ccTouchMoved  ccTouchEnded 不会得到执行
}void HelloWorld::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent){if (_mouseJoint){CCPoint touchPos = pTouch->getLocation();b2Vec2  touchPhysicsPos(touchPos.x / PTM_RATIO,touchPos.y / PTM_RATIO);_mouseJoint->SetTarget(touchPhysicsPos);//设置物体的目标位置}//CCLog("touch ccTouchMoved func.\n");
}void HelloWorld::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent){if (_mouseJoint){_world->DestroyJoint(_mouseJoint);_mouseJoint = NULL;}//CCLog("touch ccTouchEnded func.\n");
}int _getTagForBody(b2Body* body){if (body->GetUserData()){CCSprite* sp = (CCSprite*) body->GetUserData();return sp->getTag();}return -1;
}void HelloWorld::update(float delta){_world->Step(delta, 6, 6);for(b2Body* body = _world->GetBodyList(); body != NULL; body = body->GetNext()){if (body->GetUserData()){CCSprite* sp = (CCSprite*)body->GetUserData();if (sp == _ballSprite){ // 限制球速b2Vec2 spped = body->GetLinearVelocity();if (spped.LengthSquared() > 200){body->SetLinearDamping(0.9); //设置 减震之后 持续生效}else if (spped.LengthSquared() <200){body->SetLinearDamping(0.0); //设置 减震之后 持续生效if  (spped.LengthSquared() < 60){body->ApplyLinearImpulse(body->GetMass() * 5.0 * spped,body->GetWorldCenter());}}}sp->setPosition(ccp(body->GetPosition().x * PTM_RATIO,body->GetPosition().y *PTM_RATIO));}}b2Body* bodyToDestroy = NULL;vector<MyContactPeer>::iterator it;for (it = listener->_contacts.begin();it != listener->_contacts.end();it ++){MyContactPeer curContact = *it;b2Body*   bodyA = curContact.fixA->GetBody();b2Body*  bodyB = curContact.fixB->GetBody();int tagA, tagB;tagA = _getTagForBody(bodyA);tagB = _getTagForBody(bodyB);// 小球和地面碰撞 失败if (bodyA == _ball && curContact.fixB == _bottom){//CCLog("fail");CCDirector::sharedDirector()->replaceScene(GameOverScene::scenseWithWin(false));}else if (bodyB == _ball && curContact.fixA == _bottom){//CCLog("fail");CCDirector::sharedDirector()->replaceScene(GameOverScene::scenseWithWin(false));}else if (bodyA == _ball && 3 == tagB){//CCLog("kill block");bodyToDestroy = bodyB;}else if (bodyB == _ball && 3 == tagA){//CCLog("kill block");//CCLog("kill block");bodyToDestroy = bodyA;}}if (bodyToDestroy){((CCSprite*)bodyToDestroy->GetUserData())->removeFromParentAndCleanup(true);_world->DestroyBody(bodyToDestroy);                _score ++;CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect("blip.WAV");CCLog("_score is %d", _score);if (_score >= 4){CCDirector::sharedDirector()->replaceScene(GameOverScene::scenseWithWin(true));}}}void HelloWorld::menuCloseCallback(CCObject* pSender)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8)CCMessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");
#elseCCDirector::sharedDirector()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)exit(0);
#endif
#endif
}

转载注明出处:http://blog.csdn.net/s_xing/article/details/20836727

csdn不给力,文章长度限制,所以请大家跳到续篇-- http://blog.csdn.net/s_xing/article/details/20836693

cocos2dx视频教程进阶篇--第2天--打砖块游戏-box2d物理引擎相关推荐

  1. cocos2dx视频教程进阶篇--第2天--打砖块游戏-box2d物理引擎--续

    注意:这是第二篇,上回地址:http://blog.csdn.net/s_xing/article/details/20836727, 我们接着写 感觉直接看代码太枯燥的,请关注视频讲解 更新:高清a ...

  2. cocos2dx视频教程进阶篇--第1天--吃西瓜游戏。

    感谢大家的鼓励和支持,给了我很多动力,今天进阶篇终于和大家见面了. 2014-03-16更新:出品了box2d编辑工具PhysicsEditor的视频(一起做一个实战级别的游戏,需要MAC操作系统)h ...

  3. 用cocos2d-x(初级)实现篮球投篮小游戏,控制篮球投篮,一共三关(第二第三关使用box2d物理引擎)

    实现的功能:(分关说明) 主界面: 1.点击三个不同的按钮实现界面跳转. 第一二三关: 1.用简单的物理公式在update控制小球的运动,实时刷新小球的坐标. 2.使用box2d物理引擎来制作游戏场景 ...

  4. Cocos2d-x视频教程

    目录 1. 我的技术专栏 2. 相关推荐 3. 下载链接 4. cocos2d-xx Lua+JS+C++教学视频 5. 杨丰盛Cocos2D-X游戏课程 6. [Cocos2d-x]塔防游戏开发实战 ...

  5. Cocos2dx物理引擎碰撞检测总结

     通常在游戏简单逻辑判断和模拟真实的物理世界时,我们只需要在定时器中判断游戏中各个精灵的条件是否满足判断条件就可以了.例如,在飞机大战中,判断我方子弹和敌机是否发生碰撞一般在定时器中通过敌机所在位 ...

  6. 一篇上手LayaAir的3D物理引擎

    昨天,我们分享了一篇2D物理文档<LayaAirIDE的可视化2D物理使用文档>. 今天,我们针对LayaAir引擎的初学者,以及对物理引擎使用不熟悉的开发者,再来分享一篇3D物理文档,本 ...

  7. Cocos2d-x学习笔记(十五)--------物理引擎

    物理引擎 Cocos2d-x引擎内置了两种物理引擎,它们分别是Box2D和Chipmunk,都是非常优秀的2D物理引擎,而且x引擎将它们都内置在SDK中.Box2D使用较为广泛,在这里选择Box2D来 ...

  8. C++语言程序设计视频教程_清华大学_郑莉(基础篇+进阶篇)

    C++语言程序设计视频教程_清华大学_郑莉(基础篇) 第一章:绪论 1.1 导学 1.2 计算机系统简介 1.3计算机语言和程序设计方法的发展 1.4 面向对象的基本概念 1.5 程序的开发过程 1. ...

  9. 视频教程-C语言程序设计--进阶篇教学视频-C/C++

    C语言程序设计--进阶篇教学视频 烟台大学计算机学院教师,二十年余教师生涯,看出了在错综复杂的教育环境中,坚持教育教学的价值与前景.和学生并肩,与不良学风作斗争,为IT菜鸟建跑道,让大一的孩子会编程, ...

最新文章

  1. 在自己的网站添加关注新浪关注按钮
  2. 思科PIX防火墙的实际应用配置
  3. PHP学习笔记-PHP语言基础3
  4. Vue、React、Angular最佳UI框架
  5. C语言实现最大堆max_heap(附完整源码)
  6. csgo怎么控制电脑玩家_电脑怎么远程控制他人电脑,教您给电脑设置远程控制的方法...
  7. JS 数据结构之旅 :通过JS实现栈、队列、二叉树、二分搜索树、AVL树、Trie树、并查集树、堆
  8. c语言商品货架管理_武威树脂蔬菜货架厂家价格,生鲜市场货架报价_欧固隆货架...
  9. HttpsessionListener 实现在线人数统计
  10. Cadence Orcad Capture CIS原理图数据库的基本使用方法与技巧图文教程
  11. RISC-V MCU 自动浇花装置设计
  12. 老师常用选择题,选择框,单选框,以及各行业产品配置表单选配置明细等
  13. 高质量代码命名规则 代码整洁之道
  14. ICMP协议详解和作用
  15. 尚硅谷python入门
  16. 为何电脑下载mp3等音乐导入U盘后无法在汽车上播放?网易云等音乐软件夹带私货!!
  17. yum安装报错:“Could not resolve host: mirrors.aliyun.com; Unknown error“--:-- ETA Trying
  18. QGIS 1. qgis的下载和安装(Windows和macOS)
  19. cesium入坑 -- 各种API调用与API本身使用的坑
  20. C练题笔记之:Leetcode-13. 罗马数字转整数

热门文章

  1. Leetcode 1.两数之和
  2. 第10篇 WINDOWS2003服务器 IIS上配置404页面的图文教程
  3. 理解JAVASCRIPT 闭包
  4. 3.0 Android组件之间的信使Intent
  5. 一起谈.NET技术,40条ASP.NET开发Tip
  6. 利用多线程提高程序性能(for Android)
  7. 菜鸟学python-基础(2)
  8. Shell_Shell调用SQLPlus简介(案例)
  9. 零点起飞学Visual C++
  10. 二种清空数据库的好方法