今天在游戏中加了个战斗数值显示,其中就有用到渐变的效果,发现竟然没有生效,查看了源代码发现子节点的opacity值跟随父节点的opacity更新是有前提的,那就是这货:_cascadeOpacityEnabled。请看源代码:
void Node::setOpacity(GLubyte opacity) { _displayedOpacity = _realOpacity = opacity; updateCascadeOpacity(); }
void Node::updateCascadeOpacity() { GLubyte parentOpacity = 255; if (_parent != nullptr && _parent->isCascadeOpacityEnabled()) { parentOpacity = _parent->getDisplayedOpacity(); } updateDisplayedOpacity(parentOpacity); }
void Node::updateDisplayedOpacity(GLubyte parentOpacity) { _displayedOpacity = _realOpacity * parentOpacity/255.0; updateColor(); if (_cascadeOpacityEnabled) { for(const auto& child : _children) { child->updateDisplayedOpacity(_displayedOpacity); } } }
而_cascadeOpacityEnabled默认为false,所以在更新父节点的opacity时并不会更新子节点的opacity,现在知道原理了也就很好改了。
void Node::setCascadeOpacityEnabled(bool cascadeOpacityEnabled) { if (_cascadeOpacityEnabled == cascadeOpacityEnabled) { return; } _cascadeOpacityEnabled = cascadeOpacityEnabled; if (cascadeOpacityEnabled) { updateCascadeOpacity(); } else { disableCascadeOpacity(); } }来个这个方法就OK啦。 原文链接:https://www.f2er.com/cocos2dx/341328.html