使用动作移动精灵时不会发生花栗鼠碰撞

时间:2016-03-04 04:03:53

标签: cocos2d-x chipmunk

真的是一个基本的问题,但是我正在用一个物理身体移动一个精灵A而不是另一个有另一个物理身体的精灵B.我希望为这些实体调用碰撞回调oncontact。它们使用setCategoryBitmask()设置各自的类别位掩码,并使用setContactTestBitmask()分别设置彼此的类别。

只要我不移动精灵A,碰撞就会起作用。我假设问题是我使用cocos2d动作移动精灵A,我需要做其他事情。但是使用cocos2d操作来编写像这样的东西看起来比我能想到的任何其他东西都简单得多。

  • 使用物理调用移动精灵A. (看起来很多工作,看起来很难实现完美的脚本编写)
  • 在update()中执行我自己的碰撞检测。 (看起来像是一堆工作,特别是如果精灵旋转等)

还有其他快捷方式吗?或者我错过了其他什么?

2 个答案:

答案 0 :(得分:0)

我最终做了“在update()中执行我自己的碰撞检测”。这不是问题。

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
    }
}

答案 1 :(得分:0)

碰撞检测应该没问题,而碰撞不起作用。

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;
}