void AnimatedSprite2D::OnSetEnabled()
{
    StaticSprite2D::OnSetEnabled();

    bool enabled = IsEnabledEffective();

    Scene* scene = GetScene();
    if (scene)
    {
        if (enabled)
            SubscribeToEvent(scene, E_SCENEPOSTUPDATE, HANDLER(AnimatedSprite2D, HandleScenePostUpdate));
        else
            UnsubscribeFromEvent(scene, E_SCENEPOSTUPDATE);
    }

    for (unsigned i = 0; i < trackNodes_.Size(); ++i)
    {
        if (!trackNodes_[i])
            continue;

        StaticSprite2D* staticSprite = trackNodes_[i]->GetComponent<StaticSprite2D>();
        if (staticSprite)
            staticSprite->SetEnabled(enabled);
    }
}
void AnimatedSprite2D::SetAnimation(Animation2D* animation, LoopMode2D loopMode)
{
    if (animation == animation_)
    {
        SetLoopMode(loopMode_);

        currentTime_ = 0.0f;
        UpdateAnimation(0.0f);
        return;
    }

    for (unsigned i = 0; i < numTracks_; ++i)
    {
        if (trackNodes_[i])
            trackNodes_[i]->SetEnabled(false);
    }

    numTracks_ = 0;
    trackNodes_.Clear();
    trackNodeInfos_.Clear();

    animation_ = animation;

    if (!animation_)
        return;

    currentTime_ = 0.0f;

    if (!rootNode_)
    {
        rootNode_ = GetNode()->CreateChild("_root_", LOCAL);
        rootNode_->SetTemporary(true);
    }

    numTracks_ = animation_->GetNumTracks();
    trackNodes_.Resize(numTracks_);
    trackNodeInfos_.Resize(numTracks_);

    for (unsigned i = 0; i < numTracks_; ++i)
    {
        const AnimationTrack2D& track = animation->GetTrack(i);
        SharedPtr<Node> trackNode(rootNode_->GetChild(track.name_));

        StaticSprite2D* staticSprite = 0;
        if (trackNode)
        {
            // Enable track node
            trackNode->SetEnabled(true);
            
            // Get StaticSprite2D component
            if (track.hasSprite_)
                staticSprite = trackNode->GetComponent<StaticSprite2D>();
        }
        else
        {
            // Create new track node
            trackNode = rootNode_->CreateChild(track.name_, LOCAL);
            trackNode->SetTemporary(true);

            // Create StaticSprite2D component
            if (track.hasSprite_)
            {
                staticSprite = trackNode->CreateComponent<StaticSprite2D>();
                staticSprite->SetEnabled(IsEnabledEffective());
            }
        }

        if (staticSprite)
        {
            staticSprite->SetLayer(layer_);
            staticSprite->SetBlendMode(blendMode_);
            staticSprite->SetFlip(flipX_, flipY_);
            staticSprite->SetUseHotSpot(true);
        }

        trackNodes_[i] = trackNode;

        trackNodeInfos_[i].hasSprite = track.hasSprite_;
    }

    SetLoopMode(loopMode);
    UpdateAnimation(0.0f);

    MarkNetworkUpdate();
}