Exemplo n.º 1
0
void Node::setPhysicsBody(PhysicsBody* body)
{
    if (body != nullptr)
    {
        body->_node = this;
        body->retain();
        
        // physics rotation based on body position, but node rotation based on node anthor point
        // it cann't support both of them, so I clear the anthor point to default.
        if (!getAnchorPoint().equals(Vec2::ANCHOR_MIDDLE))
        {
            CCLOG("Node warning: setPhysicsBody sets anchor point to Vec2::ANCHOR_MIDDLE.");
            setAnchorPoint(Vec2::ANCHOR_MIDDLE);
        }
    }
    
    if (_physicsBody != nullptr)
    {
        PhysicsWorld* world = _physicsBody->getWorld();
        _physicsBody->removeFromWorld();
        _physicsBody->_node = nullptr;
        _physicsBody->release();
        
        if (world != nullptr && body != nullptr)
        {
            world->addBody(body);
        }
    }
    
    _physicsBody = body;
    
    if (body != nullptr)
    {
        Node* node;
        Scene* scene = nullptr;
        for (node = this->getParent(); node != nullptr; node = node->getParent())
        {
            Scene* tmpScene = dynamic_cast<Scene*>(node);
            if (tmpScene != nullptr && tmpScene->getPhysicsWorld() != nullptr)
            {
                scene = tmpScene;
                break;
            }
        }
        
        updatePhysicsBodyPosition(scene);
        updatePhysicsBodyRotation(scene);
    }
}
Exemplo n.º 2
0
void Node::setPhysicsBody(PhysicsBody* body)
{
    if (body != nullptr)
    {
        body->_node = this;
        body->retain();
        
        // physics rotation based on body position, but node rotation based on node anthor point
        // it cann't support both of them, so I clear the anthor point to default.
        if (!getAnchorPoint().equals(Point::ANCHOR_MIDDLE))
        {
            CCLOG("Node warning: setPhysicsBody sets anchor point to Point::ANCHOR_MIDDLE.");
            setAnchorPoint(Point::ANCHOR_MIDDLE);
        }
    }
    
    if (_physicsBody != nullptr)
    {
        PhysicsWorld* world = _physicsBody->getWorld();
        _physicsBody->removeFromWorld();
        _physicsBody->_node = nullptr;
        _physicsBody->release();
        
        if (world != nullptr && body != nullptr)
        {
            world->addBody(body);
        }
    }
    
    _physicsBody = body;
    if (body != nullptr)
    {
        Node* parent = getParent();
        Point pos = parent != nullptr ? parent->convertToWorldSpace(getPosition()) : getPosition();
        _physicsBody->setPosition(pos);
        _physicsBody->setRotation(getRotation());
    }
}