如何使用box2d做碰撞检测

时间:2022-01-11 03:25:40

cocos2dx3.0+vs2012编译通过。

主要是通过body->SetTransform来设置body的位置和角度,然后自己写个ContactListener来监听碰撞事件

源代码下载

#include "HelloWorldScene.h"
#include "VisibleRect.h"
#include "GLES-Render.h"
#include "cocos-ext.h" USING_NS_CC;
USING_NS_CC_EXT; #define PTM_RATIO 32 Scene* HelloWorld::createScene()
{
// 'scene' is an autorelease object
auto scene = Scene::create(); // 'layer' is an autorelease object
auto layer = HelloWorld::create(); // add layer as a child to scene
scene->addChild(layer); // return the scene
return scene;
} // on "init" you need to initialize your instance
bool HelloWorld::init()
{
//////////////////////////////
// 1. super init first
if ( !Layer::init() )
{
return false;
}
setTouchEnabled( true );
Size visibleSize = Director::getInstance()->getVisibleSize();
Point origin = Director::getInstance()->getVisibleOrigin(); /////////////////////////////
// 2. add a menu item with "X" image, which is clicked to quit the program
// you may modify it. // add a "close" icon to exit the progress. it's an autorelease object
auto closeItem = MenuItemImage::create(
"CloseNormal.png",
"CloseSelected.png",
CC_CALLBACK_1(HelloWorld::menuCloseCallback, this)); closeItem->setPosition(Point(origin.x + visibleSize.width - closeItem->getContentSize().width/ ,
origin.y + closeItem->getContentSize().height/)); // create menu, it's an autorelease object
auto menu = Menu::create(closeItem, NULL);
menu->setPosition(Point::ZERO);
this->addChild(menu, ); /////////////////////////////
// 3. add your codes below... // add a label shows "Hello World"
// create and initialize a label auto label = LabelTTF::create("Hello World", "Arial", ); // position the label on the center of the screen
label->setPosition(Point(origin.x + visibleSize.width/,
origin.y + visibleSize.height - label->getContentSize().height)); // add the label as a child to this layer
this->addChild(label, ); // add "HelloWorld" splash screen"
auto sprite = Sprite::create("HelloWorld.png"); // position the sprite on the center of the screen
sprite->setPosition(Point(visibleSize.width/ + origin.x, visibleSize.height/ + origin.y)); // add the sprite as a child to this layer
//this->addChild(sprite, 0); initPhysics(); Point p(,);
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.position.Set(p.x/PTM_RATIO, p.y/PTM_RATIO); body = world->CreateBody(&bodyDef); // Define another box shape for our dynamic body.
b2PolygonShape dynamicBox;
dynamicBox.SetAsBox(.5f, .5f);//These are mid points for our 1m box // Define the dynamic body fixture.
b2FixtureDef fixtureDef;
fixtureDef.shape = &dynamicBox;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.3f;
body->CreateFixture(&fixtureDef); scheduleUpdate(); //UILayer* pUiLayer = UILayer::create();
//addChild(pUiLayer); //Layout* pWidget = dynamic_cast<Layout*>(CCUIHELPER->createWidgetFromJsonFile("cocoStudio/DemoShop.ExportJson"));
//pUiLayer->addWidget(pWidget); return true;
} void HelloWorld::menuCloseCallback(Object* pSender)
{
Director::getInstance()->end(); #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit();
#endif
} void HelloWorld::initPhysics()
{
b2Vec2 gravity;
gravity.Set(0.0f, -10.0f);
world = new b2World(gravity); // Do we want to let bodies sleep?
world->SetAllowSleeping(true); world->SetContinuousPhysics(true); _debugDraw = new GLESDebugDraw( PTM_RATIO );
world->SetDebugDraw(_debugDraw); uint32 flags = ;
flags += b2Draw::e_shapeBit;
flags += b2Draw::e_jointBit;
flags += b2Draw::e_aabbBit;
flags += b2Draw::e_pairBit;
flags += b2Draw::e_centerOfMassBit;
_debugDraw->SetFlags(flags); // Define the ground body.
b2BodyDef groundBodyDef;
groundBodyDef.position.Set(, ); // bottom-left corner // Call the body factory which allocates memory for the ground body
// from a pool and creates the ground box shape (also from a pool).
// The body is also added to the world.
b2Body* groundBody = world->CreateBody(&groundBodyDef); // Define the ground box shape.
b2EdgeShape groundBox; // bottom
groundBox.Set(b2Vec2(VisibleRect::leftBottom().x/PTM_RATIO,VisibleRect::leftBottom().y/PTM_RATIO), b2Vec2(VisibleRect::rightBottom().x/PTM_RATIO,VisibleRect::rightBottom().y/PTM_RATIO));
groundBody->CreateFixture(&groundBox,); // top
groundBox.Set(b2Vec2(VisibleRect::leftTop().x/PTM_RATIO,VisibleRect::leftTop().y/PTM_RATIO), b2Vec2(VisibleRect::rightTop().x/PTM_RATIO,VisibleRect::rightTop().y/PTM_RATIO));
groundBody->CreateFixture(&groundBox,); // left
groundBox.Set(b2Vec2(VisibleRect::leftTop().x/PTM_RATIO,VisibleRect::leftTop().y/PTM_RATIO), b2Vec2(VisibleRect::leftBottom().x/PTM_RATIO,VisibleRect::leftBottom().y/PTM_RATIO));
groundBody->CreateFixture(&groundBox,); // right
groundBox.Set(b2Vec2(VisibleRect::rightBottom().x/PTM_RATIO,VisibleRect::rightBottom().y/PTM_RATIO), b2Vec2(VisibleRect::rightTop().x/PTM_RATIO,VisibleRect::rightTop().y/PTM_RATIO));
groundBody->CreateFixture(&groundBox,); class TestListener : public b2ContactListener
{
virtual void BeginContact(b2Contact* contact)
{
//contact->GetFixtureA();
//contact->GetFixtureB();
}
virtual void EndContact(b2Contact* contact)
{
//contact->GetFixtureA();
//contact->GetFixtureB();
}
};
pListener = new TestListener(); //don't forget to delete it
world->SetContactListener(pListener); //groundBody->SetTransform
} void HelloWorld::draw()
{
//
// IMPORTANT:
// This is only for debug purposes
// It is recommend to disable it
//
CCLayer::draw(); GL::enableVertexAttribs( cocos2d::GL::VERTEX_ATTRIB_FLAG_POSITION ); kmGLPushMatrix(); world->DrawDebugData(); kmGLPopMatrix(); } void HelloWorld::update(float dt)
{
//It is recommended that a fixed time step is used with Box2D for stability
//of the simulation, however, we are using a variable time step here.
//You need to make an informed choice, the following URL is useful
//http://gafferongames.com/game-physics/fix-your-timestep/ int velocityIterations = ;
int positionIterations = ; // Instruct the world to perform a single step of simulation. It is
// generally best to keep the time step and iterations fixed.
world->Step(dt, velocityIterations, positionIterations);
} void HelloWorld::onTouchesEnded(const std::vector<Touch*>& touches, Event* event)
{
//Add a new body/atlas sprite at the touched location for (auto& touch : touches)
{
if(!touch)
break; auto location = touch->getLocation();
body->SetTransform(b2Vec2(location.x/PTM_RATIO,location.y/PTM_RATIO),);
body->SetAwake(true);//防止静止之后就再也不动了
//addNewSpriteAtPosition( location );
} }

如何使用box2d做碰撞检测的更多相关文章

  1. 使用 Box2D 做一个 JansenWalker 机器人

    在 Box2DFlash 的官网的首页有一个小 Demo,这个 Demo 中有11个例子,可以通过左右方向键查看不同的例子,里面的每个例子都非常有趣,但最让我感兴趣的,是其中一个叫 JansenWal ...

  2. Cocos2d Box2D之碰撞检测

    |   版权声明:本文为博主原创文章,未经博主允许不得转载. 在Box2D中碰撞事件由b2ContactListener类函数实现,b2ContactListener是Box2D提供的抽象类,它的抽象 ...

  3. 使用 JavaScript 和 canvas 做精确的像素碰撞检测

    原文地址:Pixel accurate collision detection with Javascript and Canvas 译者:nzbin 我正在开发一个需要再次使用碰撞检测的游戏.我通常 ...

  4. 3D碰撞检测

    为了确保任何区域的空间不被多于1个物体占用,我们需要基于物体间的空间信息来做碰撞检测. 碰撞检测中重要的事情是有大量的测试,因此需要理由GPU资源. 例如:如果我们有n个物体,一个物体将会碰撞n-1个 ...

  5. &lbrack;Bullet3&rsqb;三种碰撞检测及实现

    官方文档:http://bulletphysics.org 开源代码:https://github.com/bulletphysics/bullet3/releases API文档:http://bu ...

  6. cocos creator 碰撞检测

    creator的碰撞检测系统分为碰撞检测系统和物理碰撞检测系统两个模块,并且这两个模块是相互独立的(这边主要是非物理碰撞检测系统) 1.在制作碰撞检测系统的时候要对物体进行分组,即指定节点的分组与分组 ...

  7. &OpenCurlyDoubleQuote;AS3&period;0高级动画编程”学习:第一章高级碰撞检测

    AdvancED ActionScript 3.0 Animation 是Keith Peters大师继"Make Things Move"之后的又一力作,网上已经有中文翻译版本了 ...

  8. 白鹭引擎 - 碰撞检测 &lpar; hitTestPoint &rpar;

    1, 矩形碰撞检测 class Main extends egret.DisplayObjectContainer { /** * Main 类构造器, 初始化的时候自动执行, ( 子类的构造函数必须 ...

  9. Direct2D处理几何图形之间的碰撞检测(下)

    转载请注明出处:http://www.cnblogs.com/Ray1024 一.概述 上一篇文章中我们介绍了几何图形与点的碰撞检测.几何图形与点的位置关系比较简单:点在几何图形内.点在几何图形外.点 ...

随机推荐

  1. Qt之重写QLabel类

    在mylabel.h 文件中#ifndef MYLABEL_H#define MYLABEL_H #include <QLabel>/*重新实现QLabel类,使其支持点击事件*/clas ...

  2. ArcGIS Add-in开发&lpar;一&rpar;--获取选定要素的属性值

    刚刚接触AE开发,记录一下自己的学习心得! 欢迎大家一起交流探讨! 最近做大赛,突然想到可以让项目更加直观的操作,就在项目中加了幅底图(底图很简单) 我想在arcmap中选中相应的要素后,在后台通过写 ...

  3. Linux使用wake&lowbar;up&lowbar;interruptible&lpar;&rpar;唤醒注册到等待队列上的进程

    http://blog.sina.com.cn/s/blog_4770ef020101h48l.html     功能:唤醒注册到等待队列上的进程 原型:     #include     void ...

  4. 子查询解嵌套in改写为exists

    SELECT * FROM (SELECT pubformdat0_.id id332_, pubformdat0_.domain_id domain2_332_, pubformdat0_.proc ...

  5. Q:算法(第四版)—第一章

    1.1.14:编写一个静态方法lg(),接受一个整型参数N,返回不大于log2N的最大整数(ps:不使用Math库) 分析: 利用将公式k=log2N转化为N=2k的原理,不断的逼近其输入的值N,当N ...

  6. SCOPE&lowbar;IDENTITY&lpar;&rpar; 和 &commat;&commat;identity

    @@IDENTITY 和SCOPE_IDENTITY 返回在当前会话中的任何表内所生成的最后一个标识值.但是,SCOPE_IDENTITY 只返回插入到当前作用域中的值:@@IDENTITY 不受限于 ...

  7. 软件工程wc项目,基于py

    ###WC项目文件链接:https://github.com/ILTHEW/wc.git 个人项目:WC 实践是理论的基础和验证标准,希望读者贯彻"做中学"的思想,动手实现下面的项 ...

  8. U盘出现很多&period;exe的文件处理方案

    1.原来优盘显示隐藏系统文件后,会有MyDocument文件夹和MyDocument.exe文件两个. 2.在MyDocument文件夹下新建文件夹名为“安全区”的空文件夹. 3.在U盘的根目录下新建 ...

  9. 三维模型 DAE 导出格式结合 OpenGLES 要素浅析

    三维模型 DAE 导出格式结合 OpenGLES 要素浅析 太阳火神的漂亮人生 (http://blog.csdn.net/opengl_es) 本文遵循"署名-非商业用途-保持一致&quo ...

  10. &lbrack;BZOJ4653 区间&rsqb;

    Description 在数轴上有 n个闭区间 [l1,r1],[l2,r2],...,[ln,rn].现在要从中选出 m 个区间,使得这 m个区间共同包含至少一个位置.换句话说,就是使得存在一个 x ...