给 spine slot 绑定node

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

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值