1
加入Box2D相关的库

步骤1:右击项目所在的解决方式à加入—>现有项目àE:\Installed\cocos2d-x-3.2\cocos2d-x-3.2\external\Box2D\proj.win32\Box2D.vcxproj

步骤2:右击项目à生成依赖项à项目依赖项à将关于libBox2D的复选框选中

步骤3:为项目加入libBox2D的库

方法:右击项目à属性à链接器à输入—>附加依赖项à编辑,加入上libBox2d.lib,à确定

案例说明:

1.编写T32.h

#ifndef
__T32_H__

#define
__T32_H__

#include
"cocos2d.h"

USING_NS_CC;

#define
winSize
Director::getInstance()->getWinSize()

#define
CCLog
cocos2d::log

#endif

2.编写TBack.h

#ifndef
__TBack_H__

#define
__TBack_H__

#include
"T32.h"

class
TBack :
public
Layer

{

public:

CREATE_FUNC(TBack);

bool
init();

};

#endif

3编写TBack.cpp

#include
"TBack.h"

bool
TBack::init()

{

Layer::init();

setLocalZOrder(100);

Menu*
menu =
Menu::create();

MenuItemImage*
item =
MenuItemImage::create("CloseNormal.png",
"CloseSelected.png",

[](Ref*){

Director::getInstance()->popScene();

});

menu->addChild(item);

item->setPosition(winSize.width
/ 2 - item->getBoundingBox().size.width
/ 2,

item->getBoundingBox().size.height
/ 2 - winSize.height
/ 2);

addChild(menu);

return
true;

}

4.编写T06Box2D.h

#ifndef
__T06Box2D_H__

#define
__T06Box2D_H__

#include
"T32.h"

#include
"Box2D/Box2D.h"

class
T06Box2D :
public
Layer

{

public:

CREATE_FUNC(T06Box2D);

bool
init();

b2World*
_world;

b2Body*
_bat;

void
update(float);

};

#endif

5编写:T06Box2D.cpp

#include
"T06Box2D.h"

#define
PTM_RATIO 32.0f

bool
T06Box2D::init()

{

Layer::init();

//创建世界,后面的-9.8表示向下的重力加速度为9.8

//b2Vec2 gravity(0,-9.8f);

//这个表示没有重力加速度

b2Vec2
gravity(0,0.0f);

_world =
new
b2World(gravity);

{

b2BodyDef
def;

//这里是一个动态的body,默认是静态的body

def.type
= b2_dynamicBody;

//设置位置。要转换成重力场中的位置要除以PTM_RATIO

def.position.Set(winSize.width
/ 2 / PTM_RATIO,
winSize.height
/ 2 / PTM_RATIO);

b2Body*
body =
_world->CreateBody(&def);

//让body受力

body->SetLinearVelocity(b2Vec2(10,20));

//显示body的精灵

Sprite*
sprite =
Sprite::create("CloseNormal.png");

addChild(sprite);

sprite->setPosition(body->GetPosition().x*PTM_RATIO,
body->GetPosition().y*PTM_RATIO);

//设置body的形状,让它和sprite相一致,是圆形的

b2CircleShape
shape;

//设置半径

shape.m_radius
= sprite->getContentSize().width
/ 2 / PTM_RATIO;

//后面的一个參数表示的是密度系数

b2Fixture*
fixture =
body->CreateFixture(&shape,
1.0f);

//设置摩擦系统

fixture->SetFriction(0.0f);

//弹性系数

fixture->SetRestitution(1.0f);

//关联body和精灵

body->SetUserData(sprite);

}

//加个地板

{

b2BodyDef
def;

// def.position.Set(0, 0);

b2Body*
body =
_world->CreateBody(&def);

//设置边界类型的形状

b2EdgeShape
shape;

//设置地板的開始点和结束点

shape.Set(b2Vec2(0,
0), b2Vec2(winSize.width
/ PTM_RATIO, 0));

b2Fixture*
fixture =
body->CreateFixture(&shape,
1.0f);

//设置摩擦系数

fixture->SetFriction(0.0f);

//设置弹性系数

fixture->SetRestitution(1.0f);

}

//加个天花板

{

b2BodyDef
def;

def.position.Set(0,
winSize.height
/ PTM_RATIO);

b2Body*
body =
_world->CreateBody(&def);

b2EdgeShape
shape;

shape.Set(b2Vec2(0,
0), b2Vec2(winSize.width
/ PTM_RATIO, 0));

b2Fixture*
fixture =
body->CreateFixture(&shape,
1.0f);

//摩擦系统

fixture->SetFriction(0.0f);

//弹性系数

fixture->SetRestitution(1.0f);

}

//左挡板

{

b2BodyDef
def;

//def.position.Set(0, winSize.height / PTM_RATIO);

b2Body*
body =
_world->CreateBody(&def);

b2EdgeShape
shape;

shape.Set(b2Vec2(0,
0), b2Vec2(0,
winSize.height
/ PTM_RATIO));

b2Fixture*
fixture =
body->CreateFixture(&shape,
1.0f);

fixture->SetFriction(0.0f);
//摩擦系统

fixture->SetRestitution(1.0f);
//弹性系数

}

//右挡板

{

b2BodyDef
def;

def.position.Set(winSize.width
/ PTM_RATIO, 0);

b2Body*
body =
_world->CreateBody(&def);

b2EdgeShape
shape;

shape.Set(b2Vec2(0,
0), b2Vec2(0,
winSize.height
/ PTM_RATIO));

b2Fixture*
fixture =
body->CreateFixture(&shape,
1.0f);

//摩擦系数

fixture->SetFriction(0.0f);

//弹性系数

fixture->SetRestitution(1.0f);

}

//球拍

{

b2BodyDef
def;

def.position.Set(winSize.width
/ 2 / PTM_RATIO,
winSize.height
/ 4 / PTM_RATIO);

b2Body*
body =
_world->CreateBody(&def);

_bat =
body;

Sprite*
sprite =
Sprite::create("bat.png");

body->SetUserData(sprite);

addChild(sprite);

sprite->setPosition(body->GetPosition().x*PTM_RATIO,
body->GetPosition().y*PTM_RATIO);

Size
batSize =
Size(100,30);

Size
content =
sprite->getContentSize();

sprite->setScale(batSize.width
/ content.width,
batSize.height
/ content.height);

b2PolygonShape
shape;

shape.SetAsBox(batSize.width
/ 2 / PTM_RATIO,
batSize.height
/ 2 / PTM_RATIO);

b2Fixture*
fixture =
body->CreateFixture(&shape,
1.0f);

//摩擦系统

fixture->SetFriction(0.0f);

//弹性系统

fixture->SetRestitution(1.0f);

//touch

EventListenerTouchOneByOne*
ev =
EventListenerTouchOneByOne::create();

ev->onTouchBegan
= [](Touch*,
Event*){return
true; };

ev->onTouchMoved
= [&](Touch*
touch,
Event*){

float
dx =
touch->getDelta().x
/ PTM_RATIO;

b2Vec2
pos =
_bat->GetPosition();

pos.x
+= dx;

//以下的函数等价于setPosition()

_bat->SetTransform(pos,
0);

};

_eventDispatcher->addEventListenerWithSceneGraphPriority(ev,
this);

}

scheduleUpdate();

return
true;

}

void
T06Box2D::update(float
dt)

{

//时间在流逝

_world->Step(dt,
8, 1);

//遍历这个世界的body

b2Body*
body =
_world->GetBodyList();

while (body)

{

//设置body相关的精灵的位置

Sprite*
sprite = (Sprite*)body->GetUserData();

if (sprite)

{

sprite->setPosition(body->GetPosition().x*PTM_RATIO,
body->GetPosition().y*PTM_RATIO);

sprite->setRotation(body->GetAngle()*180.0
/ M_PI);

}

body =
body->GetNext();

}

}

6.编写TMenu.h

#ifndef
__TMenu_H__

#define
__TMenu_H__

#include
"T32.h"

class
TMenu :
public
Layer

{

public:

CREATE_FUNC(TMenu);

bool
init();

bool
TouchBegan(Touch*,
Event*);

};

#endif

7.
编写:TMenu.cpp

#include
"TMenu.h"

#include
"TBack.h"

#include
"T01CPP11.h"

#include
"T02Vector.h"

#include
"T03Map.h"

#include
"T04Label.h"

#include
"T06Box2D.h"

static
const
char*
title[] = {

"T01CPP11",

"T02Vector",

"T03Map",

"T04Label",

"T06Box2D"

};

bool
TMenu::init()

{

Layer::init();

Menu*
menu =
Menu::create();

addChild(menu);

for (int
i = 0;
i <
sizeof(title)
/ sizeof(*title);
++i)

{

MenuItemFont*
item =
MenuItemFont::create(title[i],
[](Ref*
sender){

MenuItem*
item = (MenuItem*)sender;

int
i =
item->getTag()-1000;

Layer*
l =
NULL;

if (title[i]
== "T01CPP11") 
l =
T01CPP11::create();

if (title[i]
== "T02Vector")
l =
T02Vector::create();

if (title[i]
== "T03Map")
l =
T03Map::create();

if (title[i]
== "T04Label")
l =
T04Label::create();

if (title[i]
== "T06Box2D")
l =
T06Box2D::create();

if (l)

{

TBack*
b =
TBack::create();

Scene*
s =
Scene::create();

s->addChild(b);

s->addChild(l);

Director::getInstance()->pushScene(s);

}

});

menu->addChild(item);

item->setTag(1000
+ i);

}

menu->alignItemsVertically();

//
触摸

auto
ev =
EventListenerTouchOneByOne::create();

#if 0

ev->onTouchBegan
= [](Touch*,
Event*){

return
true;

};

#endif

//ev->onTouchBegan = std::bind(&TMenu::TouchBegan, this, std::placeholders::_1, std::placeholders::_2);

ev->onTouchBegan
= CC_CALLBACK_2(TMenu::TouchBegan,
this);

ev->onTouchMoved
= [&](Touch*
touch,
Event*){

setPositionY(getPositionY()
+ touch->getDelta().y);

};

_eventDispatcher->addEventListenerWithSceneGraphPriority(ev,
this);

return
true;

}

bool
TMenu::TouchBegan(/*TMEnu*
this, */Touch*,
Event*)

{

return
true;

}

8.编写AppDelegate.cpp

#include
"AppDelegate.h"

#include
"TMenu.h"

#include
"TBack.h"

USING_NS_CC;

AppDelegate::AppDelegate()
{

}

AppDelegate::~AppDelegate()

{

}

bool
AppDelegate::applicationDidFinishLaunching()
{

// initialize director

auto
director =
Director::getInstance();

auto
glview =
director->getOpenGLView();

if(!glview)
{

glview =
GLView::create("My
Game");

glview->setFrameSize(480,
320);

director->setOpenGLView(glview);

}

glview->setDesignResolutionSize(480,
320, ResolutionPolicy::EXACT_FIT);

// turn on display FPS

director->setDisplayStats(true);

// set FPS. the default value is 1.0/60 if you don't call this

director->setAnimationInterval(1.0
/ 60);

// create a scene. it's an autorelease object

auto
scene =
Scene::create();

scene->addChild(TMenu::create());

scene->addChild(TBack::create());

// run

director->runWithScene(scene);

return
true;

}

// This function will be called when the app is inactive. When comes a phone call,it's be invoked too

void
AppDelegate::applicationDidEnterBackground()
{

Director::getInstance()->stopAnimation();

// if you use SimpleAudioEngine, it must be pause

// SimpleAudioEngine::getInstance()->pauseBackgroundMusic();

}

// this function will be called when the app is active again

void
AppDelegate::applicationWillEnterForeground()
{

Director::getInstance()->startAnimation();

// if you use SimpleAudioEngine, it must resume here

// SimpleAudioEngine::getInstance()->resumeBackgroundMusic();

}

执行效果:

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdG90b3R1enVvcXVhbg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdG90b3R1enVvcXVhbg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">

版权声明:本文博主原创文章,博客,未经同意不得转载。

2.Cocos2dx 3.2重力系统Box2D的更多相关文章

  1. 2.Cocos2dx 3.2中的重力系统Box2D

     1 添加Box2D相关的库 步骤1:右击项目所在的解决方案à添加->现有项目àE:\Installed\cocos2d-x-3.2\cocos2d-x-3.2\external\Box2D ...

  2. Cocos2d-x v3.1 GUI系统--环境构建(七)

    Cocos2d-x v3.1 GUI系统--环境构建(七) 在使用Cocos2d-x的GUI系统时,由于生成的工程默认是没有将GUI系统所需的库导入到项目的,所以我们必须把库导入到工程中并对工程做一些 ...

  3. 【极客学院出品】Cocos2d-X系列课程之九-BOX2D物理引擎

    Cocos2d-x 是时下最热门的手游引擎,在国内和国外手机游戏开发使用的份额各自是70%和25%,在App Store的top10中,有7个是用它开发的. 本节课程为Cocos2d-x系列课程之九, ...

  4. Cocos2d-x中由sprite来驱动Box2D的body运动(用来制作平台游戏中多变的机关)

    好久都没写文章了,就来一篇吧.这种方法是在制作<胖鸟大冒险>时用到的.<胖鸟大冒险>中使用Box2D来进行物理模拟和碰撞检測,因此对每一个机关须要创建一个b2body.然后&l ...

  5. cocos2d-x JS 获取当前系统时间(解决屏幕双击点击事件)

    记录一下,好开心,感觉今天自己又学到东西了,对于屏幕双击事件本来还毫无头绪的,今天得以解决总算没白费加班,其实原理很简单:就是在点击事件里做一个判断,这个判断就是需要获取当前系统的时间的毫秒差,第一次 ...

  6. cocos2dx 3.1获取系统当前时间

    std::string Tools::getcurrTime() { #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATF ...

  7. Android游戏开发:物理游戏之重力系统开发--圆形自由落体Demo

    本节为大家提供有关物理游戏的知识,讲解了一个简单的圆形自由落体Demo的编写.. Java代码 package com.himi; import java.util.Random; import ja ...

  8. 实例介绍Cocos2d-x中Box2D物理引擎:HelloBox2D

    我们通过一个实例介绍一下,在Cocos2d-x 3.x中使用Box2D物理引擎的开发过程,熟悉这些API的使用.这个实例运行后的场景如图所示,当场景启动后,玩家可以触摸点击屏幕,每次触摸时候,就会在触 ...

  9. [原创]cocos2d-x研习录-第三阶 特性之物理引擎

    游戏物理引擎是指在游戏中涉及物理现象的逻辑处理,它用于模拟现实世界的各种物理规律(如赛车碰撞.子弹飞行.物体掉落等),让玩家能够在游戏中有真实的体验. Cocos2D-x中支持Box2D和Chipmu ...

随机推荐

  1. HTML5拖动画布/拖放

    <!DOCTYPE HTML> <html> <head> <script type="text/javascript"> func ...

  2. NYOJ115 市叛乱 【SPFA】

    城市平乱 时间限制:1000 ms  |  内存限制:65535 KB 难度:4 描写叙述 南将军统领着N个部队,这N个部队分别驻扎在N个不同的城市. 他在用这N个部队维护着M个城市的治安,这M个城市 ...

  3. tar.bz2解压

    bzip2 -d gcc-4.1.0.tar.bz2 tar -xvf gcc-4.1.0.tar 或 tar -xvf *.tar

  4. Java8高中并发

    Java8中学并发 本文翻译自:http://jaxenter.com/lean-concurrency-in-java-8-49924.html 转载请注明出处:http://blog.csdn.n ...

  5. jstack(查看线程)、jmap(查看内存)和jstat(性能分析)命令

    jstack(查看线程).jmap(查看内存)和jstat(性能分析)命令   公司内部同事分享的一篇文章 周末看到一个用jstack查看死锁的例子.昨天晚上总结了一下jstack(查看线程).jma ...

  6. hdu 5017 Ellipsoid(西安网络赛 1011)

    Ellipsoid Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others) Total ...

  7. Javascript语言精粹之String常用方法分析

    Javascript语言精粹之String常用方法分析 1. String常用方法分析 1.1 String.prototype.slice() slice(start,end)方法复制string的 ...

  8. Hibernate主键生成策略简单总结

    数据库表主键的知识点: Generator 为每个 POJO 的实例提供唯一标识. 一般情况,我们使用"native".class 表示采用由生成器接口net.sf.hiberna ...

  9. BZOJ 1975 SDOI2010 魔法猪学院 A*k短路

    题目大意:给定一个值E 求起点到终点的最多条路径 使长度之和不超过E k短路的A*算法--每一个点有一个估价函数=g[x]+h[x] 当中g[x]是从源点出发已经走了的长度 h[x]是从这个点到汇点的 ...

  10. LDAPserver的安装

    源代码安装,以root用户进行 由于:由于openldap须要用Berkeley DB来存放数据,所以要先安装所以需先安装Berkeley DB 4.2.52数据库. 一 安装Berkeley DB ...