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. [Bullet3]三种碰撞检测及实现

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

  6. cocos creator 碰撞检测

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

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

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

  8. 白鹭引擎 - 碰撞检测 ( hitTestPoint )

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

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

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

随机推荐

  1. hdu1950 最长上升子序列nlogn

    简单. #include<cstdio> #include<cstring> #include<iostream> using namespace std; ; i ...

  2. Freemarker-数字默认格式化问题

    freemarker在解析数据格式的时候,默认将数字按3位来分割 例如1000被格式化为1,000 这样做看似美观,但在实际操作时候会带来问题.例如我一个页面有一个元素,该元素的值由后台绑定且超过10 ...

  3. Netbeans 中的编译器相关配置

    gcc-core:C 编译器 gcc-g++:C++ 编译器 gdb:GNU 调试器 make:"make" 实用程序的 GNU 版本

  4. JAVA TIMER定时器

    备注:类实现ServletContextListener,在web.xml配置,之后服务启动该定时器类自动加载 package com.leadlt.common.util; import java. ...

  5. codevs2606 约数和问题

    题目描述 Description Smart最近沉迷于对约数的研究中. 对于一个数X,函数f(X)表示X所有约数的和.例如:f(6)=1+2+3+6=12.对于一个X,Smart可以很快的算出f(X) ...

  6. iframe 动态onload事件处理方式

    转自:http://w3help.org/zh-cn/causes/SD9022 标准参考 关于 HTML 4.01 规范中 BODY 标记的 onload 属性说明: http://www.w3.o ...

  7. Matlab中的括号()[]{}

    Matlab中的括号()[]{} Matlab中经常会用到括号去引用某Array或者是cell的内容,但三者有什么具体区别呢?[ ] 中括号用来构建向量(Vectors)或者是矩阵(Matrices) ...

  8. make -e install ,,,make命令的-e选项!

    -e, --environment-overrides Environment variables override makefiles.环境变量覆盖Makefile文件. 用这个时,一般都自己编写s ...

  9. 推迟调用以及Lambda表达式

    背景 GMock 我们项目中现在的模块测试框架使用了CATCH+GMock的方式实现回归测试和打桩. GMock的介绍在官网上有,这里为了铺垫,大概地描述一下GMock能实现的效果.大约可以看成这样: ...

  10. C语言代码优化(转)

    .选择合适的算法和数据结构 选择一种合适的数据结构很重要,如果在一堆随机存放的数中使用了大量的插入和删除指令,那使用链表要快得多.数组与指针语句具有十分密切的关系,一般来说,指针比较灵活简洁,而数组则 ...