【cocos2d-x 3.5】C++物理引擎

来源:互联网 发布:移动网络电视信号不好 编辑:程序博客网 时间:2024/06/06 03:04

1.创建一个物理scene

Scene* HelloWorld::createScene(){    auto scene = Scene::createWithPhysics();    auto layer = HelloWorld::create();    scene->addChild(layer);    return scene;}

调试开关

scene->getPhysicsWorld()->setDebugDrawMask(PhysicsWorld::DEBUGDRAW_ALL);

2.创建一个世界

Size size = Director::getInstance()->getWinSize();auto edgeSp = Sprite::create();auto boundBody = PhysicsBody::createEdgeBox(size, PHYSICSBODY_MATERIAL_DEFAULT, 2);edgeSp->setPosition(Point(size.width / 2, size.height / 2));edgeSp->setPhysicsBody(boundBody); this->addChild(edgeSp); 

3.创建一个有物理属性的精灵

Sprite m_ball = Sprite::create("ball.png");m_ball->setPosition(100,100);auto body = PhysicsBody::createCircle(m_ball->getContentSize().width / 2);m_ball->setPhysicsBody(body);this->addChild(m_ball);


4.物理碰撞检测

auto s1 = Sprite::create("s1.png");s1->setPosition(100,200);auto b1 = PhysicsBody::createCircle(s1->getContentSize().width/2);b1->setContactTestBitmask(0x01);s1->setPhysicsBody(b1);this->addChild(s1);

auto s2 = Sprite::create("s2.png");s2->setPosition(100,200);auto b2 = PhysicsBody::createCircle(s2->getContentSize().width/2);b2->setContactTestBitmask(0x03);s2->setPhysicsBody(b2);this->addChild(s2);

auto listenCon = EventListenerPhysicsContact::create();listenCon->onContactBegin = [=](PhysicsContact& contact){     log("ok");     return true;};_eventDispatcher->addEventListenerWithFixedPriority(listenCon, 1);


注:setContactTestBitmask值“逻辑与”运算为真的两个物体发生碰撞监听

5. 设置完全反弹的属性(反弹不减速)

body->getShape(0)->setDensity(0.1);//密度body->getShape(0)->setFriction(0);//摩擦系数body->getShape(0)->setRestitution(1);//弹力系数
注:以上值范围均为0-1

0 0