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. hdu1588 矩阵快速幂

    //看了很多的博客 后来队友指点才懂//sum=f(g(0))+f(g(1))+.... //sum=A^(b-1)*|...|.... //要将b-1换,防止出现b=0时有负一,用A^b代替,取下面 ...

  2. Java算法-堆排序

    package org.rut.util.algorithm.support; import org.rut.util.algorithm.SortUtil; public class HeapSor ...

  3. 获取和设置tinyMCE 4编辑器的内容

    对于tinymce编辑器是无法通过js进行内容的读写的,必须使用编辑器自身的方法才行,下面是一些方法,希望能对用到的朋友有所帮助: 1.如果当前页面只有一个编辑器: 获取内容:tinyMCE.acti ...

  4. HDU2509 Be the Winner

    Be the Winner Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Tot ...

  5. IRP IO_STACK_LOCATION 《寒江独钓》内核学习笔记(1)

    在学习内核过滤驱动的过程中,遇到了大量的涉及IRP操作的代码,这里有必要对IRP的数据结构和与之相关的API函数做一下笔记. 1. 相关阅读资料 <深入解析 windows 操作系统(第4版,中 ...

  6. Weak is not weak,Strong is not strong

    问题 今天做浏览器Controller的时候,碰到了一个奇怪的问题:每次pop浏览器controller之后,等几秒,总会碰到类似下面的错误(其中的xxxController就是浏览器或继承他的子类C ...

  7. js中的全选,不选,和反选按钮的设定

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  8. mybatis使用小记

    参考资料:http://blog.csdn.net/hupanfeng/article/details/9098453 1.设置不缓存每次查询的结果: 如题,通过设置 flushCache=" ...

  9. css3应用之自定义选中文字的背景颜色

    在看很多的博客主题时候发现大多数都对选中文字的背景颜色做了相应的处理.其实这样是很符合用户体验的.因为有很多的人会用鼠标选择着一行一行的阅读.其中就包括本人... 浏览器中默认的选中的文字颜色为白色, ...

  10. 安装 RPM 包或者安装源码包

    安装 RPM 包或者安装源码包 在windows下安装一个软件很轻松,只要双击.exe的文件,安装提示连续“下一步”即可,然而linux系统下安装一个软件似乎并不那么轻松了,因为我们不是在图形界面下. ...