2016-03-04 91 views
0

真的是一個基本問題,但我正在將物理體的精靈A移動到另一種具有另一個物理體的精靈B上。我希望碰撞回調oncontact被稱爲這些機構。他們使用setCategoryBitmask()設置各自的類別位掩碼,並分別使用setContactTestBitmask()設置對方的類別。使用動作移動精靈時不會發生花栗鼠碰撞

只要我不移動精靈A,碰撞就會起作用。我假設問題是我使用cocos2d動作移動精靈A,並且我需要做其他事情。但使用cocos2d動作來編寫腳本這樣的東西看起來比我能想到的任何其他東西都簡單得多。

  • 使用物理調用移動精靈A. (看起來像很多工作,它看起來很難實現完美的腳本完美)
  • 而是在update()中執行我自己的碰撞檢測。 (看起來像一堆工作,尤其是如果精靈旋轉等)

是否有任何其他的捷徑?還是我錯過了別的東西?

回答

0

我最終做了「在update()中做我自己的碰撞檢測」。這不是太麻煩。

像這樣的東西在更新()...

const Rect RECT_A = spriteA->getBoundingBox(); 
for (auto spriteB : someparent->getChildren()) { 
    const Rect RECT_B = spriteB->getBoundingBox(); 
    if (RECT_A.intersectsRect(RECT_B)) { 
     // Hit 
    } 
} 
0

Contaction檢測要細而collion不起作用。

Scene* HelloWorld::createScene() 
{ 
    // 'scene' is an autorelease object 
    auto scene = Scene::createWithPhysics(); 

    // 'layer' is an autorelease object 
    auto layer = HelloWorld::create(); 

    // add layer as a child to scene 
    scene->addChild(layer); 

    scene->getPhysicsWorld()->setDebugDrawMask(PhysicsWorld::DEBUGDRAW_ALL); 
    scene->getPhysicsWorld()->setGravity(Vec2::ZERO); 

    // return the scene 
    return scene; 
} 

bool HelloWorld::init() 
{ 
    if (!Layer::init()) 
    { 
     return false; 
    } 

    auto createSprite = [this](const Vec2& pos) { 
     auto sprite = Sprite::create(); 
     auto bodyA = PhysicsBody::createCircle(20); 
     sprite->setPhysicsBody(bodyA); 
     sprite->setPosition(pos); 

     bodyA->setCollisionBitmask(0xff); 
     bodyA->setCategoryBitmask(0xff); 
     bodyA->setContactTestBitmask(0xff); 

     return sprite; 
    }; 

    auto spriteA = createSprite(Vec2(300, 300)); 
    auto moveBy = MoveBy::create(1.f, Vec2(200, 200)); 
    spriteA->runAction(moveBy); 

    auto spriteB = createSprite(Vec2(350, 350)); 

    addChild(spriteA); 
    addChild(spriteB); 

    auto contactListener = EventListenerPhysicsContact::create(); 
    contactListener->onContactBegin = [=](PhysicsContact& contact) { 
     auto a = contact.getShapeA()->getBody()->getNode(); 
     auto b = contact.getShapeB()->getBody()->getNode(); 

     assert((a == spriteA && b == spriteB) || (a == spriteB && b == spriteA)); 

     log("It is working"); 

     return false; 
    }; 

    _eventDispatcher->addEventListenerWithSceneGraphPriority(contactListener, this); 

    return true; 
}