float AppUtils::randomFloat(float low,float high) { //0.0-1.0 float r = rand()/(RAND_MAX+0.1); return ((high+1) - low) * r + low; }
2、点击区域判断
CCRect AppUtils::boundingBoxForWorld(CCNode* node) { CCRect rect = CCRectZero; if (node==NULL) { return rect; } CCPoint anchorPoint = node->getAnchorPoint(); CCSize widgetSize = node->boundingBox().size; CCPoint worldPosition = node->getPosition(); worldPosition.x -= widgetSize.width*anchorPoint.x; worldPosition.y -= widgetSize.height*anchorPoint.y; if (node!=NULL) { CCNode* parent = node->getParent(); while (parent != NULL) { float scaleX = parent->getScaleX(); float scaleY = parent->getScaleY(); float scaledWidth = widgetSize.width*scaleX; float scaledHeight = widgetSize.height*scaleY; worldPosition.x += (widgetSize.width - scaledWidth) / 2; worldPosition.y += (widgetSize.height - scaledHeight) / 2; widgetSize.width = scaledWidth; widgetSize.height = scaledHeight; worldPosition = worldPosition + parent->getBoundingBox().origin; parent = parent->getParent(); } rect.origin = worldPosition; rect.size= widgetSize; return rect; } return rect; }
3、触摸方法模拟按钮的触摸点击
static void setColorForAll(Sprite* target,Color3B color= Color3B::GRAY); static void btnTouchBegin(Sprite* target,Point p,Color3B color = Color3B::GRAY); static void btnTouchMoved(Sprite* target,Color3B color = Color3B::WHITE); static bool btnTouchEnded(Sprite* target,Color3B color = Color3B::WHITE);
方法实现:
void AppUtils::setColorForAll(Sprite* target,Color3B color) { if (target != NULL) { target->setColor(color); Vector<Node*> children = target->getChildren(); for (size_t i = 0; i < children.size(); i++) { Sprite* item = (Sprite*)children.at(i); if (item != NULL) { item->setColor(color); } } } } void AppUtils::btnTouchBegin(Sprite* target,Color3B color) { if (target != NULL&&target->boundingBox().containsPoint(p)) { setColorForAll(target,color); } } void AppUtils::btnTouchMoved(Sprite* target,Color3B color) { if (target != NULL&&!target->boundingBox().containsPoint(p) && (target->getColor()== Color3B::GRAY)) { setColorForAll(target,color); } } bool AppUtils::btnTouchEnded(Sprite* target,Color3B color) { if (target != NULL&&target->boundingBox().containsPoint(p) && (Color3B::GRAY==target->getColor())) { setColorForAll(target,color); return true; } return false; }原文链接:https://www.f2er.com/cocos2dx/340597.html