如何使用box2d做碰撞检测
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做碰撞检测的更多相关文章
- 使用 Box2D 做一个 JansenWalker 机器人
在 Box2DFlash 的官网的首页有一个小 Demo,这个 Demo 中有11个例子,可以通过左右方向键查看不同的例子,里面的每个例子都非常有趣,但最让我感兴趣的,是其中一个叫 JansenWal ...
- Cocos2d Box2D之碰撞检测
| 版权声明:本文为博主原创文章,未经博主允许不得转载. 在Box2D中碰撞事件由b2ContactListener类函数实现,b2ContactListener是Box2D提供的抽象类,它的抽象 ...
- 使用 JavaScript 和 canvas 做精确的像素碰撞检测
原文地址:Pixel accurate collision detection with Javascript and Canvas 译者:nzbin 我正在开发一个需要再次使用碰撞检测的游戏.我通常 ...
- 3D碰撞检测
为了确保任何区域的空间不被多于1个物体占用,我们需要基于物体间的空间信息来做碰撞检测. 碰撞检测中重要的事情是有大量的测试,因此需要理由GPU资源. 例如:如果我们有n个物体,一个物体将会碰撞n-1个 ...
- [Bullet3]三种碰撞检测及实现
官方文档:http://bulletphysics.org 开源代码:https://github.com/bulletphysics/bullet3/releases API文档:http://bu ...
- cocos creator 碰撞检测
creator的碰撞检测系统分为碰撞检测系统和物理碰撞检测系统两个模块,并且这两个模块是相互独立的(这边主要是非物理碰撞检测系统) 1.在制作碰撞检测系统的时候要对物体进行分组,即指定节点的分组与分组 ...
- “AS3.0高级动画编程”学习:第一章高级碰撞检测
AdvancED ActionScript 3.0 Animation 是Keith Peters大师继"Make Things Move"之后的又一力作,网上已经有中文翻译版本了 ...
- 白鹭引擎 - 碰撞检测 ( hitTestPoint )
1, 矩形碰撞检测 class Main extends egret.DisplayObjectContainer { /** * Main 类构造器, 初始化的时候自动执行, ( 子类的构造函数必须 ...
- Direct2D处理几何图形之间的碰撞检测(下)
转载请注明出处:http://www.cnblogs.com/Ray1024 一.概述 上一篇文章中我们介绍了几何图形与点的碰撞检测.几何图形与点的位置关系比较简单:点在几何图形内.点在几何图形外.点 ...
随机推荐
- .net架构设计读书笔记--第一章 基础
第一章 基础 第一节 软件架构与软件架构师 简单的说软件架构即是为客户构建一个软件系统.架构师随便软件架构应运而生,架构师是一个角色. 2000年9月ANSI和IEEE发布了<密集性软件架构建 ...
- UVA5874 Social Holidaying 二分匹配
二分匹配简单题,看懂题意,建图比较重要. #include<stdio.h> #include<string.h> #define maxn 1100 int map[maxn ...
- hdu1542矩阵的并 线段树+扫描线
求矩阵的并,也就是要求所有的面积.那可以吧总的图形按照矩阵来切割.使其为一块一块. 输入的时候用坐标表示,这里扫描线从下到上扫描.初始时让下面的边为1,上面的为-1: 用一条先从下面开始想上扫描.遇到 ...
- Cocos2d-X3.0 刨根问底(八)----- 场景(Scene)、层(Layer)相关源码分析
本章节我们重点分析Cocos2d-x3.0与 场景.层相关的源码.这部分源码集中在 libcocos2d –> layers_scenes_transitions_nodes目录下面 我先发个截 ...
- PLSQL中配置Oracle方法
在服务器上,用PL/SQL连接Oracle数据库时,出现了一个问题,提示: Initialization error Could not load "F:\oracle\bin\oci.dl ...
- 新建的 web 工程 有红色的惊叹号
新建的 web 工程 有红色的感叹号问题: 在eclipse 中新建一个web工程,但是工程上有红色的感叹号.解决: 1.右键工程,选择Build Path-->Configur ...
- MySQL存储过程解析
1.1 创建存储过程 MySQL中,创建存储过程的基本形式如下: CREATE PROCEDURE sp_name ([proc_parameter[,...]]) [charac ...
- SQLServer 数据导入导出 SSIS 包 位置
笔记:sqlserver 在执行数据导入导出的时候,可以选择是否保存SSIS包,如果选择保存,在保存方式有:SQlserver .文件系统.如果选择sqlserver 则 包信息保存在 msdb 系统 ...
- photon mapping阶段性总结
PM算法看了这么久,也该是到了总结的时候了.自己实现的是PPPM(Probabilistic progressive photon mapping)的一个简化形式.之所以是简化形式是由于我的光子搜集时 ...
- Homebrew安装
1. 安装Command Line Tools 终端输入 xcode-select --install 回车,若下载慢,可搜索Command line Tools的pkg文件,自行安装. 或者直接安装 ...