void CCLayerPanZoom::setPosition(const cocos2d::CCPoint& position)
 {
     CCNode::setPosition(position);
     
     if(!_panBoundsRect.equals(CCRectZero))
     {
         CCSize size = CCDirector::sharedDirector()->getWinSize();
         
         if(_panBoundsRect.size.width * getScaleX() < size.width)
         {
             CCNode::setPosition(ccp((_panBoundsRect.origin.x + _panBoundsRect.size.width) * getScaleX() * 0.5f, (_panBoundsRect.origin.y + _panBoundsRect.size.height) * getScaleY() * 0.5f));
         }
         else
         {
             bool changed = false;
             CCPoint newPosition = getPosition();
             float value = -_panBoundsRect.origin.x * getScaleX();
             
             if(newPosition.x > value)
             {
                 newPosition.x = value;
                 changed = true;
             }
             
             value = ((-_panBoundsRect.origin.x - _panBoundsRect.size.width) * getScaleX()) + size.width;
             
             if(newPosition.x < value)
             {
                 newPosition.x = value;
                 changed = true;
             }
             
             value = -_panBoundsRect.origin.y * getScaleY();
             
             if(newPosition.y > value)
             {
                 newPosition.y = value;
                 changed = true;
             }
             
             value = ((-_panBoundsRect.origin.y - _panBoundsRect.size.height) * getScaleY()) + size.height;
             
             if(newPosition.y < value)
             {
                 newPosition.y = value;
                 changed = true;
             }
             
             if(changed)
             {
                 CCNode::setPosition(newPosition);
             }
         }
     }
 }
void BaseContentWrapLayer::getBoarderPos(float& minX,float& minY,float& maxX,float& maxY)
{
	CCSize winsize = CCDirector::sharedDirector()->getWinSize();
	float x_offset = (winsize.width - 1024)/2.0f;

	maxX = (getContentSize().width * getScaleX() - winsize.width )/2;
	if (getScaleX() > 1.0f)
	{
		maxX -= x_offset;
	}
	minX = winsize.width/2 - getContentSize().width * getScaleX()/2 + x_offset;
	maxY = (getContentSize().height * getScaleY() - winsize.height )/2;
	minY = winsize.height/2 - getContentSize().height * getScaleY()/2;
}
static float convertDistanceFromPointToInch(const Vec2& dis)
{
    auto glview = Director::DirectorInstance->getOpenGLView();
    int dpi = Device::getDPI();
    float distance = Vec2(dis.x * glview->getScaleX() / dpi, dis.y * glview->getScaleY() / dpi).getLength();
    return distance;
}
Exemple #4
0
CoreElementBullet::CoreElementBullet(const std::string& armatureName, const std::string& effectArmatureName, float radian, float speed, const cocos2d::Vec2& position)
{
    _speedX = std::cos(radian) * speed;
    _speedY = -std::sin(radian) * speed;

    _armature = CoreElementGame::instance->factory.buildArmature(armatureName);
    _armatureDisplay = (dragonBones::CCArmatureDisplay*)_armature->getDisplay();
    _armatureDisplay->setPosition(position);
    _armatureDisplay->setRotation(radian * dragonBones::RADIAN_TO_ANGLE);
    _armature->getAnimation().play("idle");

    if (!effectArmatureName.empty())
    {
        _effect = CoreElementGame::instance->factory.buildArmature(effectArmatureName);
        const auto effectDisplay = (dragonBones::CCArmatureDisplay*)_effect->getDisplay();
        effectDisplay->setPosition(position);
        effectDisplay->setRotation(radian * dragonBones::RADIAN_TO_ANGLE);
        effectDisplay->setScaleX(cocos2d::random(1.f, 2.f));
        effectDisplay->setScaleY(cocos2d::random(1.f, 1.5f));
        if (cocos2d::random(0.f, 1.f) < 0.5f)
        {
            effectDisplay->setScaleY(effectDisplay->getScaleY());
        }

        _effect->getAnimation().play("idle");

        dragonBones::WorldClock::clock.add(_effect);
        CoreElementGame::instance->addChild(effectDisplay);
    }

    dragonBones::WorldClock::clock.add(_armature);
    CoreElementGame::instance->addChild(_armatureDisplay);
}
void UIWidget::adaptSize(float xProportion,float yProportion)
{
    m_fAdaptScaleX = xProportion;
    m_fAdaptScaleY = yProportion;
    setScaleX(m_fAdaptScaleX*getScaleX());
    setScaleY(m_fAdaptScaleY*getScaleY());
}
Exemple #6
0
CCRect CCSkeleton::boundingBox () {
	float minX = FLT_MAX, minY = FLT_MAX, maxX = FLT_MIN, maxY = FLT_MIN;
	float scaleX = getScaleX();
	float scaleY = getScaleY();
	float vertices[8];
	for (int i = 0; i < skeleton->slotCount; ++i) {
		Slot* slot = skeleton->slots[i];
		if (!slot->attachment || slot->attachment->type != ATTACHMENT_REGION) continue;
		RegionAttachment* attachment = (RegionAttachment*)slot->attachment;
		RegionAttachment_computeVertices(attachment, slot->skeleton->x, slot->skeleton->y, slot->bone, vertices);
		minX = min(minX, vertices[VERTEX_X1] * scaleX);
		minY = min(minY, vertices[VERTEX_Y1] * scaleY);
		maxX = max(maxX, vertices[VERTEX_X1] * scaleX);
		maxY = max(maxY, vertices[VERTEX_Y1] * scaleY);
		minX = min(minX, vertices[VERTEX_X4] * scaleX);
		minY = min(minY, vertices[VERTEX_Y4] * scaleY);
		maxX = max(maxX, vertices[VERTEX_X4] * scaleX);
		maxY = max(maxY, vertices[VERTEX_Y4] * scaleY);
		minX = min(minX, vertices[VERTEX_X2] * scaleX);
		minY = min(minY, vertices[VERTEX_Y2] * scaleY);
		maxX = max(maxX, vertices[VERTEX_X2] * scaleX);
		maxY = max(maxY, vertices[VERTEX_Y2] * scaleY);
		minX = min(minX, vertices[VERTEX_X3] * scaleX);
		minY = min(minY, vertices[VERTEX_Y3] * scaleY);
		maxX = max(maxX, vertices[VERTEX_X3] * scaleX);
		maxY = max(maxY, vertices[VERTEX_Y3] * scaleY);
	}
	CCPoint position = getPosition();
	return CCRectMake(position.x + minX, position.y + minY, maxX - minX, maxY - minY);
}
Rect SkeletonRenderer::getBoundingBox () const {
	float minX = FLT_MAX, minY = FLT_MAX, maxX = FLT_MIN, maxY = FLT_MIN;
	float scaleX = getScaleX(), scaleY = getScaleY();
	for (int i = 0; i < _skeleton->slotsCount; ++i) {
		spSlot* slot = _skeleton->slots[i];
		if (!slot->attachment) continue;
		int verticesCount;
		if (slot->attachment->type == SP_ATTACHMENT_REGION) {
			spRegionAttachment* attachment = (spRegionAttachment*)slot->attachment;
			spRegionAttachment_computeWorldVertices(attachment, slot->bone, _worldVertices);
			verticesCount = 8;
		} else if (slot->attachment->type == SP_ATTACHMENT_MESH) {
			spMeshAttachment* mesh = (spMeshAttachment*)slot->attachment;
			spMeshAttachment_computeWorldVertices(mesh, slot, _worldVertices);
			verticesCount = mesh->super.worldVerticesLength;
		} else
			continue;
		for (int ii = 0; ii < verticesCount; ii += 2) {
			float x = _worldVertices[ii] * scaleX, y = _worldVertices[ii + 1] * scaleY;
			minX = min(minX, x);
			minY = min(minY, y);
			maxX = max(maxX, x);
			maxY = max(maxY, y);
		}
	}
	Vec2 position = getPosition();
    if (minX == FLT_MAX) minX = minY = maxX = maxY = 0;    
	return Rect(position.x + minX, position.y + minY, maxX - minX, maxY - minY);
}
void alert(const std::string &text){
    
    auto title=Label::create(text,"fonts/hyz.ttf", 28);
    cocos2d::Size titleSize=title->getBoundingBox().size;
    title->setPosition((titleSize.width+40)/2, (titleSize.height+40)/2);

    auto box=Sprite::create();
    box->setTextureRect(cocos2d::Rect(0, 0, titleSize.width+40, titleSize.height+40));
    box->setPosition(WIDTH/2, HEIGHT/8*3+100);
    box->setColor(ccc3(0, 0, 0));
    box->addChild(title);

    title->setScaleX(1./box->getScaleX());
    title->setScaleY(1./box->getScaleY());

    auto scene = Director::getInstance()->getRunningScene();
    scene->addChild(box,100);

    auto fade = FadeIn::create(1);
    auto delay = DelayTime::create(2);
    auto fadeOut = FadeOut::create(1);
    auto seque = Sequence::create(fade,delay,fadeOut,NULL);

    auto fade2 = FadeIn::create(1);
    auto delay2 = DelayTime::create(2);
    auto fadeOut2 = FadeOut::create(1);
    auto seque2 = Sequence::create(fade2,delay2,fadeOut2,NULL);

    box->runAction(seque);
    title->runAction(seque2);
    
    
}
	void Button::drawtexture(D3DCOLOR color)
	{
		D3DXMATRIX mat;
		D3DXVECTOR2 trans((float)getX(),(float)getY());
		D3DXVECTOR2 scale((float)getScaleX(),(float)getScaleY());
		D3DXMatrixTransformation2D(&mat,NULL,0,&scale,NULL,0,&trans);
		g_engine->getSpriteHandler()->SetTransform(&mat);

		//calculate frame position and size
		int fx = (this->getFrameCurrent() % this->getFrameColumns()) * this->getImage()->tile_width;
		int fy = (this->getFrameCurrent() / this->getFrameColumns()) * this->getImage()->tile_height;
		fx += (this->getFrameCurrent() % this->getFrameColumns()) * this->getImage()->tile_offset_x;
		fy += (this->getFrameCurrent() / this->getFrameColumns()) * this->getImage()->tile_offset_y;

		RECT srcRect;
		srcRect.left = fx;
		srcRect.top = fy;
		
		if(this->getScaleX()==1)
			srcRect.right = fx + this->getWidth();
		else
			srcRect.right = fx + this->getImage()->getWidth();
		
		if(this->getScaleY()==1)
			srcRect.bottom = fy + this->getHeight();			
		else
			srcRect.bottom = fy + this->getImage()->getHeight();			
		
		g_engine->getSpriteHandler()->Draw(this->getImage()->GetTexture(),&srcRect,NULL,NULL,color);

	}
CCRect CCSkeleton::boundingBox () {
	float minX = FLT_MAX, minY = FLT_MAX, maxX = FLT_MIN, maxY = FLT_MIN;
	float scaleX = getScaleX();
	float scaleY = getScaleY();
	ccV3F_C4B_T2F_Quad quad;
	for (int i = 0; i < skeleton->slotCount; ++i) {
		Slot* slot = skeleton->slots[i];
		if (!slot->attachment || slot->attachment->type != ATTACHMENT_REGION) continue;
		RegionAttachment* attachment = (RegionAttachment*)slot->attachment;
		RegionAttachment_updateQuad(attachment, slot, &quad);
		minX = min(minX, quad.bl.vertices.x * scaleX);
		minY = min(minY, quad.bl.vertices.y * scaleY);
		maxX = max(maxX, quad.bl.vertices.x * scaleX);
		maxY = max(maxY, quad.bl.vertices.y * scaleY);
		minX = min(minX, quad.br.vertices.x * scaleX);
		minY = min(minY, quad.br.vertices.y * scaleY);
		maxX = max(maxX, quad.br.vertices.x * scaleX);
		maxY = max(maxY, quad.br.vertices.y * scaleY);
		minX = min(minX, quad.tl.vertices.x * scaleX);
		minY = min(minY, quad.tl.vertices.y * scaleY);
		maxX = max(maxX, quad.tl.vertices.x * scaleX);
		maxY = max(maxY, quad.tl.vertices.y * scaleY);
		minX = min(minX, quad.tr.vertices.x * scaleX);
		minY = min(minY, quad.tr.vertices.y * scaleY);
		maxX = max(maxX, quad.tr.vertices.x * scaleX);
		maxY = max(maxY, quad.tr.vertices.y * scaleY);
	}
	CCPoint position = getPosition();
	return CCRectMake(position.x + minX, position.y + minY, maxX - minX, maxY - minY);
}
CCRect UIWidget::getRelativeRect()
{
    CCNode* validNode = getValidNode();
    float width = 0.0f;
    float height = 0.0f;
    float anchorPointX = 0.0f;
    float anchorPointY = 0.0f;
    CCSize nodeSize = validNode->getContentSize();
    width = nodeSize.width*getScaleX();
    height = nodeSize.height*getScaleY();
    CCPoint nodeAnchorPoint = validNode->getAnchorPoint();
    anchorPointX = nodeAnchorPoint.x;
    anchorPointY = nodeAnchorPoint.y;
    switch (m_WidgetType)
    {
        case WidgetTypeWidget:
            m_relativeRect.origin.x = getPosition().x - width * anchorPointX;
            m_relativeRect.origin.y = getPosition().y - height * anchorPointY;
            break;
        case WidgetTypeContainer:
            m_relativeRect.origin.x = getPosition().x;
            m_relativeRect.origin.y = getPosition().y;
            break;
    }
    m_relativeRect.size.width = width;
    m_relativeRect.size.height = height;
    return m_relativeRect;
}
Exemple #12
0
    Rect Helper::convertBoundingBoxToScreen(Node* node)
    {
        auto director = Director::getInstance();
        auto glView = director->getOpenGLView();
        auto frameSize = glView->getFrameSize();

        auto winSize = director->getWinSize();
        auto leftBottom = node->convertToWorldSpace(Point::ZERO);

        auto contentSize = node->getContentSize();
        auto rightTop = node->convertToWorldSpace(Point(contentSize.width, contentSize.height));

        auto uiLeft = frameSize.width / 2 + (leftBottom.x - winSize.width / 2 ) * glView->getScaleX();
        auto uiTop = frameSize.height /2 - (rightTop.y - winSize.height / 2) * glView->getScaleY();

        return Rect(uiLeft,uiTop,
                    (rightTop.x - leftBottom.x) * glView->getScaleX(),
                    (rightTop.y - leftBottom.y) * glView->getScaleY());
    }
Exemple #13
0
void PlayCard::flipCard(float timeDelay)
{
    CCSize size = this->getContentSize();
    this->runAction(CCSequence::create(
                               CCDelayTime::create(timeDelay),
                               CCSpawn::create(
                                               CCScaleTo::create(FlippingTime/2, 0, getScaleY()),
                                               CCFadeTo::create(FlippingTime/2, 0.2),
                                               NULL
                                               ),
                               CCCallFunc::create(this, callfunc_selector(PlayCard::flipCard)),
                               CCSpawn::create(
                                               CCScaleTo::create(FlippingTime/2, getScaleY(), getScaleY()),
                                               CCFadeTo::create(FlippingTime/2, 1),
                                               NULL
                                               ),
                                NULL
                               ));
}
Exemple #14
0
void Label::onPressStateChangedToPressed()
{
    if (!_touchScaleChangeEnabled)
    {
        return;
    }
    _normalScaleValueX = getScaleX();
    _normalScaleValueY = getScaleY();
    clickScale(_normalScaleValueX + _onSelectedScaleOffset, _normalScaleValueY + _onSelectedScaleOffset);
}
void EditBoxImplAndroid::createNativeControl(const Rect& frame)
{
    auto director = cocos2d::Director::getInstance();
    auto glView = director->getOpenGLView();
    auto frameSize = glView->getFrameSize();
    
    auto winSize = director->getWinSize();
    auto leftBottom = _editBox->convertToWorldSpace(Point::ZERO);
    
    auto contentSize = frame.size;
    auto rightTop = _editBox->convertToWorldSpace(Point(contentSize.width, contentSize.height));
    
    auto uiLeft = frameSize.width / 2 + (leftBottom.x - winSize.width / 2 ) * glView->getScaleX();
    auto uiTop = frameSize.height /2 - (rightTop.y - winSize.height / 2) * glView->getScaleY();
    auto uiWidth = (rightTop.x - leftBottom.x) * glView->getScaleX();
    auto uiHeight = (rightTop.y - leftBottom.y) * glView->getScaleY();
    LOGD("scaleX = %f", glView->getScaleX());
    _editBoxIndex = addEditBoxJNI(uiLeft, uiTop, uiWidth, uiHeight, glView->getScaleX());
    s_allEditBoxes[_editBoxIndex] = this;
}
Exemple #16
0
NS_CC_EXT_BEGIN

#define SCROLL_DEACCEL_RATE  0.95f
#define SCROLL_DEACCEL_DIST  1.0f
#define BOUNCE_DURATION      0.15f
#define INSET_RATIO          0.2f
#define MOVE_INCH            7.0f/160.0f
#define BOUNCE_BACK_FACTOR   0.35f

static float convertDistanceFromPointToInch(float pointDis)
{
    auto glview = Director::getInstance()->getOpenGLView();
    float factor = ( glview->getScaleX() + glview->getScaleY() ) / 2;
    return pointDis * factor / Device::getDPI();
}
float UIWidget::getAbsoluteScaleY()
{
    if (m_bScaleYDirty)
    {
        float scaleY = getScaleY();
        UIWidget* parent = getWidgetParent();
        while (parent)
        {
            scaleY *= parent->getScaleY();
            parent = parent->getWidgetParent();
        }
        m_fAbsoluteScaleY = scaleY;
        m_bScaleYDirty = false;
    }
    return m_fAbsoluteScaleY;
}
Exemple #18
0
START_GAME_NS

// PATCH - sprite from csb file use content scale factor
void fixSpriteContentScale(Node* parentNode) {
    auto childrenNodes = parentNode->getChildren();
    for (auto it = childrenNodes.begin(); it != childrenNodes.end(); it++) {
        auto childNode = *it;
        if (dynamic_cast<Sprite*>(childNode) != NULL) {
            auto sprite = dynamic_cast<Sprite*>(childNode);
            sprite->setScale(sprite->getScaleX() * Director::getInstance()->getContentScaleFactor(),
                             sprite->getScaleY() * Director::getInstance()->getContentScaleFactor());
            
        }
        fixSpriteContentScale(childNode);
        
    }
}
Exemple #19
0
NS_CC_WIDGET_BEGIN

#define CSCORLLVIEW_RELOCATE_DURATION 0.2f
#define CSCROLLVIEW_DEACCELERATE_VA 2000.0f
#define CSCROLLVIEW_DEACCELERATE_MAX 400.0f
#define CSCROLLVIEW_DEACCELERATE_INTERVAL 0.245f
#define CSCROLLVIEW_DEACCELERATE_PERCENTAGE 0.955f
#define CSCROLLVIEW_MOVE_INCH 7.0f/160.0f
#define CSCROLLVIEW_MOVE_ACTION_TAG 1
#define CSCROLLVIEW_MOVE_EASEIN_RATE 0.5f

float ccScrollconvertPointToInch(float pointDis)
{
	auto glView = Director::getInstance()->getOpenGLView();
    float factor = ( glView->getScaleX() + glView->getScaleY() ) / 2;
	
    return pointDis * factor / Device::getDPI();
}
            void WebViewImpl::draw(cocos2d::Renderer *renderer, cocos2d::Mat4 const &transform, uint32_t flags) {
                if (flags & cocos2d::Node::FLAGS_TRANSFORM_DIRTY) {
                    auto directorInstance = cocos2d::Director::getInstance();
                    auto glView = directorInstance->getOpenGLView();
                    auto frameSize = glView->getFrameSize();

                    auto winSize = directorInstance->getWinSize();

                    auto leftBottom = this->_webView->convertToWorldSpace(cocos2d::Point::ZERO);
                    auto rightTop = this->_webView->convertToWorldSpace(cocos2d::Point(this->_webView->getContentSize().width,this->_webView->getContentSize().height));

                    auto uiLeft = frameSize.width / 2 + (leftBottom.x - winSize.width / 2 ) * glView->getScaleX();
                    auto uiTop = frameSize.height /2 - (rightTop.y - winSize.height / 2) * glView->getScaleY();

                    setWebViewRectJNI(_viewTag,uiLeft,uiTop,
                                      (rightTop.x - leftBottom.x) * glView->getScaleX(),
                                      (rightTop.y - leftBottom.y) * glView->getScaleY());
                }
            }
Exemple #21
0
void ClipNode::visit( Renderer *pRenderer, const Mat4& parentTransform, uint32_t parentFlags )
{
	glEnable( GL_SCISSOR_TEST );

	const float fScaleX = getScaleX();
	const float fScaleY = getScaleY();
	Point worldPosition = getPosition();
	if ( getParent() )
	{
		worldPosition = getParent()->convertToWorldSpace( worldPosition );
	}
	
	Director::getInstance()->getOpenGLView()->setScissorInPoints(
		worldPosition.x - _gg_ClipSize.width * fScaleX * _gg_ClipAnchor.x,
		worldPosition.y - _gg_ClipSize.height * fScaleY * _gg_ClipAnchor.y,
		_gg_ClipSize.width * fScaleX,
		_gg_ClipSize.height * fScaleY );
	
	Node::visit( pRenderer, parentTransform, parentFlags );

	glDisable( GL_SCISSOR_TEST );
}
            void WebViewImpl::draw(cocos2d::Renderer *renderer, cocos2d::Mat4 const &transform, int flags) {
                if (flags & cocos2d::Node::FLAGS_TRANSFORM_DIRTY) {
                    auto directorInstance = cocos2d::Director::getInstance();
                    auto glView = directorInstance->getOpenGLView();
                    auto frameSize = glView->getFrameSize();

                    auto winSize = directorInstance->getWinSize();

                    auto leftBottom = this->_webView->convertToWorldSpace(cocos2d::Point::ZERO);
                    auto rightTop = this->_webView->convertToWorldSpace(cocos2d::Point(this->_webView->getContentSize().width,this->_webView->getContentSize().height));

                    auto uiLeft = frameSize.width / 2 + (leftBottom.x - winSize.width / 2 ) * glView->getScaleX();
                    auto uiTop = frameSize.height /2 - (rightTop.y - winSize.height / 2) * glView->getScaleY();

                    Evas_Coord width = (rightTop.x - leftBottom.x) * glView->getScaleX();
                    Evas_Coord height = (rightTop.y - leftBottom.y) * glView->getScaleY();

                    evas_object_resize(_ewkView, width, height);
                    evas_object_move(_ewkView, uiLeft, uiTop);
                    evas_object_show(_ewkView);
                }
            }
float Sprite2d::getHeight() const{return (m_Sprite->getLocalBounds().height*getScaleY());}
void Sprite2d::setWidth(const float& w){
	setScale(w/m_Sprite->getLocalBounds().width , getScaleY());
}
Exemple #25
0
void UILabel::setTouchScaleChangeEnabled(bool enable)
{
    _touchScaleChangeEnabled = enable;
    _normalScaleValueX = getScaleX();
    _normalScaleValueY = getScaleY();
}
Exemple #26
0
void GameMap::updateView()
{
	Point posView = gHero->getPosition()+Point(0,85.f);

	Rect rect;

	Size viewSize = gDirector->getVisibleSize();
	Point viewOrigin = gDirector->getVisibleOrigin();
	Point offsetLD;
	Point offsetRU;
	rect.setRect(viewOrigin.x+m_viewPoint.x+offsetLD.x,viewOrigin.y+m_viewPoint.y+offsetLD.y,(viewSize.width+offsetRU.x)/getScaleX(),(viewSize.height+offsetRU.y)/getScaleY());

	Point posMin = Point(rect.getMaxX()-rect.getMidX(),rect.getMaxY()-rect.getMidY());
	Point posMax = Point(GetMaxViewX()+rect.getMaxX()-rect.getMidX(),GetMaxViewY()+rect.getMaxY()-rect.getMidY());
	// 限制地图出屏
	if( posView.x<posMin.x ) posView.x = posMin.x;
	if( posView.x>posMax.x ) posView.x = posMax.x;
	if( posView.y<posMin.y ) posView.y = posMin.y;
	if( posView.y>posMax.y ) posView.y = posMax.y;

	SetView(posView);
}
void EditBoxImplCommon::setContentSize(const Size& size)
{
    _contentSize = size;
    CCLOG("[Edit text] content size = (%f, %f)", size.width, size.height);
    placeInactiveLabels();
    
    auto director = cocos2d::Director::getInstance();
    auto glview = director->getOpenGLView();
    Size  controlSize = Size(size.width * glview->getScaleX() * _label->getNodeToWorldAffineTransform().a,size.height * glview->getScaleY() * _label->getNodeToWorldAffineTransform().a);
       
    this->setNativeContentSize(controlSize);

}
cocos2d::ui::Button* GameLayer::create_button(std::string text, BoolFuncNoArgs cb, bool start_disabled, ButtonState* btn_state)
{
    auto param = ui::LinearLayoutParameter::create();
    param->setGravity(ui::LinearLayoutParameter::LinearGravity::CENTER_HORIZONTAL);

    auto disable_button = [](ui::Button* button)
    {
        button->setTitleColor(Color3B::GRAY);
        button->setTouchEnabled(false);
        button->setPressedActionEnabled(false);
    };

    auto btn = ui::Button::create("main_UI_export_10_x4.png", "", "", ui::TextureResType::PLIST);

    btn->setTitleFontName(menu_font);
    btn->setTitleFontSize(menu_fontsize);
    btn->setTitleColor(Color3B::BLACK);
    btn->getTitleRenderer()->getTexture()->setAliasTexParameters();

    btn->setColor(Color3B(114, 160, 72));

    btn->getVirtualRenderer()->setScale(sx(1.0f));
    btn->setScaleX(sx(1.0f));
    btn->setScaleY(sy(1.0f));

    param->setMargin(ui::Margin(0, sy(15.0f)*btn->getScaleY(), 0, sy(15.0f)*btn->getScaleY()));

    btn->setLayoutParameter(param);
    btn->setTouchEnabled(true);
    btn->setPressedActionEnabled(true);

    if (start_disabled) 
    {
        disable_button(btn);
    };

    btn->setTitleText(text);
    if (btn_state)
    {
        //update the text
        btn_state->swap_state(btn, btn_state->current);
    };

    btn->addTouchEventListener(
        [btn_state, cb, btn, disable_button](Ref* ref, ui::Widget::TouchEventType event)
            {
                if (event == ui::Widget::TouchEventType::ENDED)
                {
                    if (!cb())
                    {
                        disable_button(btn);
                    };
                    if (btn_state)
                    {
                        btn_state->current = !btn_state->current;
                        btn_state->swap_state(btn, btn_state->current);
                    };
                }
            }
    );

    return btn;

};
void InteractiveBlock::updateDistanceFromPlayer()
{
    auto blockAsset = dynamic_cast<LHAsset*>(this->getParent());
    
    if (blockAsset)
    {
        b2Body* body = this->getBox2dBody();
        b2Vec2 playerBodyPosition = _player->getBox2dBody()->GetPosition();
        b2Vec2 blockBodyPosition = body->GetPosition();
        b2Vec2 distanceBodyVector = blockBodyPosition - playerBodyPosition;
        
        const float kPixelsPerMeter = PTM_RATIO;
        float widthFactor = ((_player->getContentSize().width * fabs(_player->getScaleX())) / 2) + ((blockAsset->getContentSize().width * fabs(blockAsset->getScaleX())) / 2);
        float heightFactor = ((_player->getContentSize().height * fabs(_player->getScaleY())) / 2) + ((blockAsset->getContentSize().height * fabs(blockAsset->getScaleY())) / 2);
        widthFactor /= kPixelsPerMeter;
        heightFactor /= kPixelsPerMeter;
        
        if ((fabs(distanceBodyVector.x) > (widthFactor + 0.1f + fabs(sin(body->GetAngle()))))
            || ((fabs(distanceBodyVector.y) > heightFactor) && fabs(sin(body->GetAngle())) < .1f ))
        {
            float horizontalVelocity = body->GetLinearVelocity().x;
            
            if (fabs(horizontalVelocity) > 0.1f)
            {
                Utility::setDensity(this, 1.0f);
                body->SetGravityScale(10.0f);
                
                if (_player->getIsPushingLeft())
                {
                    _player->setPushingSide(-1.0f, false);
                }
                else if (_player->getIsPushingRight())
                {
                    _player->setPushingSide(1.0, false);
                }
            }
        }
    }
}
Exemple #30
0
bool GallaryList::init()
{
    if (!Layer::init()) {
        return false;
    }
    visibleSize = Director::getInstance()->getVisibleSize();
    thumbWidth = visibleSize.width/4;
    thumbSpace = visibleSize.width/3.5;
    currentThumb = 0;
    isClick = false;
    
    GallaryLayer::setGallaryState(0, true);
    GallaryLayer::setGallaryState(1, true);
    GallaryLayer::setGallaryState(3, true);
    GallaryLayer::setGallaryState(4, true);
    GallaryLayer::setGallaryState(5, true);
    GallaryLayer::setGallaryState(9, true);

    for (int i = 0; i != picCount; ++i) {
        char name[30];
        sprintf(name, "gallary/gallary%d.png", i);
        
        auto listItem = Sprite::create(name);
        this->addChild(listItem);
        thumbs.push_back(listItem);
        listItem->setScale(thumbWidth/listItem->getContentSize().width, visibleSize.height/listItem->getContentSize().height/4);
        listItem->setPosition(Vec2(visibleSize.width/2+thumbSpace*i, 0));
        if (!GallaryLayer::getGallaryState(i)) {
            listItem->setOpacity(100);
        }
        auto itemFrame = Sprite::create("frame/Data-Pic.png"); // TODO: need to be change
        this->addChild(itemFrame, -1);
        itemFrame->setPosition(Vec2(visibleSize.width/2+thumbSpace*i, 0));
        itemFrame->setAnchorPoint(Point(0.5, 0.5));
        itemFrame->setScale(thumbWidth/itemFrame->getContentSize().width*1.03, visibleSize.height/itemFrame->getContentSize().height/4*1.05);
        
        touchListener = EventListenerTouchOneByOne::create();
        touchListener->setSwallowTouches(true);
        touchListener->onTouchBegan = [&, listItem](Touch *touch, Event *event) {
            isClick = true;
            event->getCurrentTarget()->stopActionByTag(tag_loadPic);
            startPoint = touch->getLocation();
            movePoint = startPoint;
            // touch on list
            auto locationInNode = listItem->convertToNodeSpace(touch->getLocation());
            auto rect = cocos2d::Rect(0, 0, listItem->getContentSize().width, listItem->getContentSize().height);
            if (rect.containsPoint(locationInNode)) {
                touchListener->setSwallowTouches(true);
                return true;
            }
            // touch on pic
            auto displayPic = static_cast<GallaryContent*>(this->getParent())->getDisplayPic();
            auto locationInNode2 = displayPic->convertToNodeSpace(touch->getLocation());
            auto rect2 = cocos2d::Rect(0, 0, displayPic->getContentSize().width*displayPic->getScaleX(), displayPic->getContentSize().height*displayPic->getScaleY());
            if (rect2.containsPoint(locationInNode2)) {
                touchListener->setSwallowTouches(true);
                return true;
            }

            return false;
        };
        touchListener ->onTouchMoved = [&](Touch *touch, Event *event) {
            auto currentPoint = touch->getLocation();
            this->setPositionX(this->getPositionX() + currentPoint.x - movePoint.x);
            if (currentPoint.x - movePoint.x > 50 || currentPoint.x - movePoint.x < 100) {
                isClick = false;
            }
            movePoint = currentPoint;
            return true;
        };
        touchListener->onTouchEnded = [&](Touch *touch, Event *event) {
            touchListener->setSwallowTouches(false);
            auto target = static_cast<GallaryList*>(event->getCurrentTarget());
            currentThumb = static_cast<int>((event->getCurrentTarget()->getPositionX()-thumbSpace/2)/thumbSpace);
//            log("posx: %d", currentThumb);
            if (-currentThumb >= picCount) {
                currentThumb = -picCount + 1;
            }
            if (isClick) {
                auto displayPic = static_cast<GallaryContent*>(this->getParent())->getDisplayPic();
                auto locationInNode = displayPic->convertToNodeSpace(touch->getLocation());
                auto rect = cocos2d::Rect(0, 0, displayPic->getContentSize().width*displayPic->getScaleX(), displayPic->getContentSize().height*displayPic->getScaleY());
                // open display mode
                if (rect.containsPoint(locationInNode) && GallaryLayer::getGallaryState(-currentThumb)) {
//                    target->onPicClick(-currentThumb);
                    this->onPicClick(-currentThumb);
                }
            } else {
                if (currentThumb >= 0) {
                    target->runAction(MoveTo::create(0.2, Vec2(0, target->getPositionY())));
                } else if (currentThumb < -picCount+1) {
                    target->runAction(MoveTo::create(0.2, Vec2(thumbSpace*(-picCount+1), target->getPositionY())));
                } else {
                    target->runAction(MoveTo::create(0.2, Vec2(thumbSpace*currentThumb, target->getPositionY())));
                }
//                target->thumbs.at(-currentThumb)->runAction();
                // change pic
                target->onPicChange(-currentThumb);
            }
            return true;
        };
        _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this);
    }
    
    return true;
}