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. 人工鱼群算法-python实现

    AFSIndividual.py import numpy as np import ObjFunction import copy class AFSIndividual: "" ...

  2. php复习

    最近要用php,好久不用感觉手生.抓起<零基础学PHP>一书复习了下,顺带学了smarty模板语言,然后到慕课网看了些php中级视频教程,这里记录下. php最基本的文件上传 不用任何第三 ...

  3. Hibernate 缓存机制

    一.why(为什么要用Hibernate缓存?) Hibernate是一个持久层框架,经常访问物理数据库. 为了降低应用程序对物理数据源访问的频次,从而提高应用程序的运行性能. 缓存内的数据是对物理数 ...

  4. PL/0编译器(java version)–PL0.java

    1: package compiler; 2:   3: import java.io.BufferedWriter; 4: import java.io.FileWriter; 5:   6: /* ...

  5. Struts2 自定义Result

    注意:我只要是解决自定义返回Json 和异常处理问题 新建一个类 AjaxResult   继承 StrutsResultSupport 看看代码吧 public class AjaxResult e ...

  6. Nginx 配置文件详解

    user nginx ; #用户 worker_processes 8; #工作进程,根据硬件调整,大于等于cpu核数 error_log logs/nginx_error.log crit; #错误 ...

  7. ios 判断控制器是否是第一次进入画页的做法

    什么是第一次进入画页,只viewDidLoad一次: 所以只需要在viewDidLoad中加一个标识就行了. 加一个成员变量,或者属性,用来记录这个标识 一旦viewDidLoad后,这个就说明不是第 ...

  8. Bootstrap新手学习笔记——css

    Css模块: 1.网格系统: class前缀:.col-xs-*,.col-sm-*,.col-md-*,.col-lg-* <div class="container"&g ...

  9. jquery 使用方法<转载>

    jquery 使用方法 jQuery是目前使用最广泛的javascript函数库.据统计,全世界排名前100万的网站,有46%使用jQuery,远远超过其他库.微软公司 甚至把jQuery作为他们的官 ...

  10. thinkphp 3.23 第三方登录sdk集成包

    本集成包在官方包上扩展了支付宝登录和微信,支持最新的3.23版本 config    /* URL配置 */     'URL_CASE_INSENSITIVE' => true, //默认fa ...