一个约束(constraint)就是消除物体自由度的物理连接。在 2D 中,一个物体有 3 个自由度。如果我们把一个物体钉在墙上(像摆锤那样),那我们就把它约束到了墙上。这样,此物体就只能绕着这个钉子旋转,所以这个约束消除了它 2 个自由度。
接触约束(contact constraint)
一个防止刚体穿透,以及用于模拟摩擦(friction)和恢复(restitution)的特殊约束。你永远都不必创建一个接触约束,它们会自动被 Box2D 创建。
关节(joint)
它是一种用于把两个或多个物体固定到一起的约束。Box2D 支持的关节类型有:旋转,棱柱,距离等等。关节可以支持限制(limits)和马达(motors)。
关节限制(joint limit)
一个关节限制(joint limit)限定了一个关节的运动范围。例如人类的胳膊肘只能做某一范围角度的运动。
关节马达(joint motor)
一个关节马达能依照关节的自由度来驱动所连接的物体。例如,你可以使用一个马达来驱动一个肘的旋转。
世界(world)
一个物理世界就是物体,形状和约束相互作用的集合。Box2D 支持创建多个世界,但这通常是不必要的。
//
// HelloWorldScene.cpp
// Box2d
//
// Created by XiangZi on 14-6-23.
// Copyright __MyCompanyName__ 2014年. All rights reserved.
//
#include "HelloWorldScene.h"
//单位:Box2D中距离以米为单位,质量以公斤为单位,时间以秒为单位。
//屏幕的宽度和高度值除以一个名为 PTM_RATIO 的常量,把像素值转换成了以米为单位来计算长度。
#define PTM_RATIO 32 //PTM_RATIO用于定义32个像素在Box2D世界中等同于1米。
enum {
kTagParentNode = 1,
};
PhysicsSprite::PhysicsSprite()
: m_pBody(NULL)
{
}
void PhysicsSprite::setPhysicsBody(b2Body * body)
{
m_pBody = body;
}
//重写isDirty方法,返回YES,目的是让每次layer的update调用后重新绘制PhysicsSprite精灵。
bool PhysicsSprite::isDirty(void)
{
return true;
}
/*
重写精灵的矩阵变换方法nodeToParentTransform,模板提供的这个实现,能改变精灵的位置和角度。
我们会看到,在update函数中,调用了Box2D的Step方法,这个方法根据时间流逝计算出每个刚体的新位置和角度,
然后在这里被使用最终达到精灵移动旋转的目的。
*/
CCAffineTransform PhysicsSprite::nodeToParentTransform(void)
{
b2Vec2 pos = m_pBody->GetPosition();
float x = pos.x * PTM_RATIO;
float y = pos.y * PTM_RATIO;
if ( isIgnoreAnchorPointForPosition() ) {
x += m_obAnchorPointInPoints.x;
y += m_obAnchorPointInPoints.y;
}
// Make matrix
float radians = m_pBody->GetAngle();
float c = cosf(radians);
float s = sinf(radians);
if( ! m_obAnchorPointInPoints.equals(CCPointZero) ){
x += c*-m_obAnchorPointInPoints.x + -s*-m_obAnchorPointInPoints.y;
y += s*-m_obAnchorPointInPoints.x + c*-m_obAnchorPointInPoints.y;
}
// Rot, Translate Matrix
m_sTransform = CCAffineTransformMake( c, s,
-s, c,
x, y );
return m_sTransform;
}
HelloWorld::HelloWorld()
{
setTouchEnabled( true );
setAccelerometerEnabled( true );
CCSize s = CCDirector::sharedDirector()->getWinSize();
// init physics
this->initPhysics();
CCSpriteBatchNode *parent = CCSpriteBatchNode::create("blocks.png", 100);
m_pSpriteTexture = parent->getTexture();
addChild(parent, 0, kTagParentNode);
addNewSpriteAtPosition(ccp(s.width/2, s.height/2));
CCLabelTTF *label = CCLabelTTF::create("Tap screen", "Marker Felt", 32);
addChild(label, 0);
label->setColor(ccc3(0,0,255));
label->setPosition(ccp( s.width/2, s.height-50));
scheduleUpdate();
}
HelloWorld::~HelloWorld()
{
delete world;
world = NULL;
}
void HelloWorld::initPhysics()
{
CCSize s = CCDirector::sharedDirector()->getWinSize();
b2Vec2 gravity;
gravity.Set(0.0f, -10.0f);
//对Box2D世界进行初始化
world = new b2World(gravity);
/*
会“睡眠”的动态刚体:当施加到某个刚体上的力量小于临界值一段时间以后,这个刚体将会进入“睡眠”状态。
换句话说,如果某个刚体移动或者旋转的很慢或者根本不在动的话,物理引擎将会把它标记为“睡眠”状态,
不再对其施加力量,直到新的力量施加到刚体上让其再次移动或者旋转。通过把一些刚体标记为“睡眠”状态,
物理引擎可以省下很多时间。除非你游戏中的所有动态刚体处于持续的运动中,否则应该把
SetAllowSleeping变量设置为true。
*/
world->SetAllowSleeping(true);
//设置检测连续碰撞
world->SetContinuousPhysics(true);
//1.创建一个body定义结构体,用以指定body的初始属性,比如位置或者速度。
b2BodyDef groundBodyDef;
groundBodyDef.position.Set(0, 0);
//2.调用world对象来创建一个body对象
b2Body* groundBody = world->CreateBody(&groundBodyDef);
//3.为body对象定义一个shape,用以指定想要仿真的物体的几何形状。
b2EdgeShape groundBox;
//4.创建一个fixture定义,同时设置之前创建好的shape为fixture的一个属性,并且设置其它的属性,比如质量或者摩擦力。
// bottom
groundBox.Set(b2Vec2(0,0), b2Vec2(s.width/PTM_RATIO,0));
groundBody->CreateFixture(&groundBox,0);
// top
groundBox.Set(b2Vec2(0,s.height/PTM_RATIO), b2Vec2(s.width/PTM_RATIO,s.height/PTM_RATIO));
groundBody->CreateFixture(&groundBox,0);
// left
groundBox.Set(b2Vec2(0,s.height/PTM_RATIO), b2Vec2(0,0));
groundBody->CreateFixture(&groundBox,0);
// right
groundBox.Set(b2Vec2(s.width/PTM_RATIO,s.height/PTM_RATIO), b2Vec2(s.width/PTM_RATIO,0));
groundBody->CreateFixture(&groundBox,0);
}
void HelloWorld::draw()
{
//
// IMPORTANT:
// This is only for debug purposes
// It is recommend to disable it
CCLayer::draw();
ccGLEnableVertexAttribs( kCCVertexAttribFlag_Position );
kmGLPushMatrix();
world->DrawDebugData();
kmGLPopMatrix();
}
void HelloWorld::addNewSpriteAtPosition(CCPoint p)
{
CCNode* parent = getChildByTag(kTagParentNode);
//有一个64x64的精灵表有4种不同的32x32的图像,只是随机挑选其中一个图像。
int idx = (CCRANDOM_0_1() > .5 ? 0:1);
int idy = (CCRANDOM_0_1() > .5 ? 0:1);
PhysicsSprite *sprite = new PhysicsSprite();
sprite->initWithTexture(m_pSpriteTexture, CCRectMake(32 * idx,32 * idy,32,32));
sprite->autorelease();
parent->addChild(sprite);
sprite->setPosition( CCPointMake( p.x, p.y) );
//1.创建一个body定义结构体,用以指定body的初始属性,比如位置或者速度。
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.position.Set(p.x/PTM_RATIO, p.y/PTM_RATIO);
//2.调用world对象来创建一个body对象
b2Body *body = world->CreateBody(&bodyDef);
//3.为body对象定义一个shape,用以指定想要仿真的物体的几何形状。
b2PolygonShape dynamicBox;
dynamicBox.SetAsBox(.5f, .5f);//These are mid points for our 1m box
/*4.创建一个fixture定义,同时设置之前创建好的shape为fixture的一个属性,并且设置其它的属性,比如质量或者摩擦力。
density,friction和restitution参数的意义:
Density 就是单位体积的质量(密度)。因此,一个对象的密度越大,那么它就有更多的质量,当然就会越难以移动.
Friction 就是摩擦力。它的范围是0-1.0, 0意味着没有摩擦,1代表最大摩擦,几乎移不动的摩擦。
Restitution 回复力。它的范围也是0到1.0. 0意味着对象碰撞之后不会反弹,1意味着是完全弹性碰撞,会以同样的速度反弹。
*/
b2FixtureDef fixtureDef;
fixtureDef.shape = &dynamicBox;
fixtureDef.density = 1.0f; //密度
fixtureDef.friction = 0.3f; //摩擦力
body->CreateFixture(&fixtureDef);
//调用sprite的setPhysicsBody来为一个sprite设定body。
sprite->setPhysicsBody(body);
}
//更新每个刚体相关联的精灵的位置和旋转信息
void HelloWorld::update(float dt)
{
int velocityIterations = 8;
int positionIterations = 1;
/*
Box2D的world是通过定期地调用Step方法来实现动画的。
Step方法需要三个参数。
第一个是timeStep,它会告诉Box2D自从上次更新以后已经过去多长时间了,直接影响着刚体会在这一步移动多长距离。
不建议使用dt来作为timeStep的值,因为dt会上下浮动,刚体就不能以相同的速度移动了。
第二和第三个参数是迭代次数。它们被用于决定物理模拟的精确程度,也决定着计算刚体移动所需要的时间。
*/
world->Step(0.015, velocityIterations, positionIterations);
//在物理世界world中遍历每一个刚体body
for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
{
if (b->GetUserData() != NULL) {
//Synchronize the AtlasSprites position and rotation with the corresponding body
CCSprite* myActor = (CCSprite*)b->GetUserData();
myActor->setPosition( CCPointMake( b->GetPosition().x * PTM_RATIO, b->GetPosition().y * PTM_RATIO) ); //单位转换 米->像素
myActor->setRotation( -1 * CC_RADIANS_TO_DEGREES(b->GetAngle()) ); //单位转换 弧度->角度
}
}
}
void HelloWorld::ccTouchesEnded(CCSet* touches, CCEvent* event)
{
CCSetIterator it;
CCTouch* touch;
for( it = touches->begin(); it != touches->end(); it++)
{
touch = (CCTouch*)(*it);
if(!touch) break;
CCPoint location = touch->getLocation();
addNewSpriteAtPosition( location );
}
}
CCScene* HelloWorld::scene()
{
CCScene *scene = CCScene::create();
CCLayer* layer = new HelloWorld();
scene->addChild(layer);
layer->release();
return scene;
}
相关推荐
MIPool 小台球 demo Box2d cocos2d-x 2.2.3 源代码
压缩文件目录内容: AngryBird source 愤怒的小鸟Demo源代码,基于Cocos2dx C++,box2d技术。 run 可执行程序目录
box2d的demo和cocos2d的利用第三方工具的粒子系统demo
cocos2d制作的割绳子游戏demo,基于box2d开发的割绳子
box2d小车demo int velocityIterations = 8; //速度迭代,可以调整物体的运动 int positionIterations = 1; //位置迭代,可以调整物体的位置,减少物体间的重叠。 world->Step(time,velocityIterations,...
你的第一炮游戏----- 关于这个 ----- 这是2013年创建的小项目,是我第一个使用cocos2d/box2d的demo项目。 该演示实际上是众所周知的游戏纸炮的克隆。 游戏的目的是向敌人发射炮弹。 当这些炮弹爆炸时,它们必须尽...