您的位置:首页 > Web前端 > Node.js

给 spine slot 绑定node

2016-01-31 13:36 585 查看
SkeletonRenderer.h中添加:

/** Draws a skeleton. */
class SkeletonRenderer: public cocos2d::Node, public cocos2d::BlendProtocol
{
public:
Node* getNodeForSlot(const char* slotName);
private:
struct sSlotNode
{
spSlot* slot;
Node* node;
};

typedef std::map<std::string, sSlotNode> SlotNodeMap;
typedef SlotNodeMap::iterator SlotNodeIter;
SlotNodeMap m_slotNodes;


方法getNodeForSlot用来根据一个slot name获取一个Node,如果node不存在则创建。

解释一下为什么不获取骨骼而是获取slot。因为spine runtime中一个骨骼可以带有多个slot,并且除了TSR动画(位移缩放旋转),我们还需要挂接上去的Node能支持Color动画(包含alpha),

那么slot就可以满足条件,并且从slot很容易获取相应的bone.

我们使用m_slotNodes来保存slot name到slot和node的映射。

下面是CCSkeleton.cpp中的实现

static void setEnableRecursiveCascadingRGBA(Node* node, bool enable)
{
CCRGBAProtocol* rgba = dynamic_cast<CCRGBAProtocol*>(node);
if (rgba)
{
rgba->setCascadeColorEnabled(enable);
rgba->setCascadeOpacityEnabled(enable);
}

CCObject* obj;
Vector<Node*> children = node->getChildren();
Vector<Node*>::iterator it;
for (it = children.begin(); it != children.end(); it++)
{
Node* child = *it;
setEnableRecursiveCascadingRGBA(child, enable);
}
}

Node* SkeletonRenderer::getNodeForSlot(const char* slotName){
SlotNodeIter iter = m_slotNodes.find(slotName);
if (iter != m_slotNodes.end()) {
sSlotNode& slot_node = iter->second;
return slot_node.node;
}
else{
spSlot* slot = findSlot(slotName);

if (slot != NULL){
Node* node = Node::create();
node->setPosition(0, 0);

this->addChild(node);
sSlotNode slot_node;
slot_node.slot = slot;
slot_node.node = node;
m_slotNodes.insert(SlotNodeMap::value_type(slotName, slot_node));
return node;
}
else{
return NULL;
}
}

}


getNodeForSlot是被客户代码调用的,使用场景是创建CCSkeletonAnimation后,需要将某个Node挂接到某个slot上一起动画。此时调用getNodeForSlot获取该slot对应的Node。

并且使用获取到的Node作为父node来执行addChild(需要挂接的node)。

getNodeForSlot的实现很简单:如果该slot name对应的Node不存在,则创建一个并且放入map中。

修改 drawSkeleton 函数
//原始代码
//我们添加的代码放到最后好了,放到if (debugSlots) 这行之前即可。
//for each attached CCNodeRGBA, update the TSR and RGBA
for (SlotNodeIter iter = m_slotNodes.begin(), end = m_slotNodes.end(); iter != end; ++iter) {
sSlotNode& slot_node = iter->second;
spSlot* slot = slot_node.slot;
Node* node = slot_node.node;
setEnableRecursiveCascadingRGBA(node, true);
spBone* bone = slot->bone;
if (bone != NULL){
node->setPosition(ccp(bone->worldX, bone->worldY));
node->setRotation(-bone->worldRotation);
node->setScaleX(bone->worldScaleX);
node->setScaleY(bone->worldScaleY);
}

node->setOpacity(255 * slot->a);
node->setColor(ccc3(255 * slot->r, 255 * slot->g, 255 * slot->b));
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: