泰然的跑酷用的chipmunk物理引擎,我没有仔细学过这个东西。不过我看了一下他们的用法,感觉跟box2d差不多。box2d用纯真的面向对象C++开发,用在这里应该没有问题,试一下。
泰然的工程没有加入box2d模块,所以需要添加。将external/Box2D加入工程,将无用的引用删掉,加入后结构如下
然后新建一个PlayScene类,开始创建物理世界。
为了方便调试box2d物理世界,需要接入debug渲染器,将TestCpp/Classes/Box2DTestBed/下的GLES-Render.h和GLES-Render.cpp加入到工程,这个可以绘制出物理模型的形状。
因为box2d针对0-10米的仿真做过优化,所以我这里将像素大小映射到10左右
#define RATIO 32看下PlayScene.h
//
// PlayScene.h
// Parkour
//
// Created by lerry on 14-3-14.
// Copyright (c) 2014年 Goonear Co.,Ltd. All rights reserved.
//
#ifndef __Parkour__PlayScene__
#define __Parkour__PlayScene__
#include "cocos2d.h"
#include "Box2D.h"
#include "GLES-Render.h"
#define RATIO 32
#define GROUND_HEIGHT 57
#define RUUNER_STARTX 80
class PlayScene : public cocos2d::CCLayer
{
b2World* mWorld;
GLESDebugDraw* mDebugDraw;
private:
// 初始化物理世界
void initPhysics();
// 绘制物理世界debug区域
void draw();
// 开启物理世界debug
void setDebug(bool isDebug);
public:
virtual bool init();
virtual void update(float dt);
CREATE_FUNC(PlayScene);
static cocos2d::CCScene* scene();
};
#endif /* defined(__Parkour__PlayScene__) */
void PlayScene::initPhysics()
{
mWorld = new b2World(b2Vec2(0, -10));
mWorld->SetAllowSleeping(true);
mWorld->SetContinuousPhysics(true);
// mWorld->SetContactListener(this);
// 地板body
b2Body* ground = NULL;
b2BodyDef bd;
ground = mWorld->CreateBody(&bd);
// 地板
b2EdgeShape shape;
shape.Set(b2Vec2(0, GROUND_HEIGHT / RATIO), b2Vec2(INT_MAX, GROUND_HEIGHT / RATIO));
ground->CreateFixture(&shape, 0.0f);
setDebug(true);
}
box2d的物理世界有自己的世界循环函数,跟cocos2d-x的update函数类似,所以在update函数里面调用box2d的迭代函数
void PlayScene::update(float dt)
{
// 物理世界的迭代函数
mWorld->Step(dt, 10, 8);
}
然后在MainScene.cpp的onPlay函数里面填上回调的时间:
// start按钮回调
void MainScene::onPay()
{
CCLog("onPlay click");
// 创建带过渡的场景
CCScene* s = CCTransitionFade::create(1, PlayScene::scene());
CCDirector::sharedDirector()->replaceScene(s);
}
cocos2d-x游戏开发 跑酷(二) 物理世界,布布扣,bubuko.com
原文:http://blog.csdn.net/dawn_moon/article/details/21240343