void CAScrollView::closeToPoint(float delay)
{
    CCSize size = this->getContentSize();
    CCPoint point = m_pContainer->getFrameOrigin();
    CCPoint resilience = ccpSub(m_tCloseToPoint, point);
    
    if (resilience.getLength() <= 0.5f)
    {
        m_pContainer->setFrameOrigin(m_tCloseToPoint);
        CAScheduler::unschedule(schedule_selector(CAScrollView::closeToPoint), this);
        m_tCloseToPoint = CCPoint(-1, -1);
        this->hideIndicator();
    }
    else
    {
        resilience.x /= size.width;
        resilience.y /= size.height;
        resilience = ccpMult(resilience, maxBouncesSpeed(delay));
        resilience = ccpAdd(resilience, point);
        m_pContainer->setFrameOrigin(resilience);
    }
}
bool CAIndicator::initWithFrame(const CCRect& rect, CAIndicatorType type)
{
    if (!CAView::init())
    {
        return false;
    }
    this->setFrame(rect);
    
    m_eType = type;
    
    CAImage* image = CAImage::create("indicator.png");
    
    CCRect r;
    r.origin = ccpSub(ccpMult(image->getContentSize(), 0.5f), CCPoint(0.5f, 0.5f));
    r.size = CCSize(1.0f, 1.0f);
    
    m_pIndicator = CAScale9ImageView::createWithImage(r, image);
    this->addSubview(m_pIndicator);
    this->setOpacity(0);
    
    return true;
}
void JoystickController::update(ccTime dt)
{

	if (mListener)
	{
		CCPoint scaledV = ccpMult(mJoystick->getVelocity(), 320);
		
		mListener->UpdatePosition(dt, scaledV.x, scaledV.y);

		if (mButton->getIsActive())
		{
			if (!mButtonDown)
			{
				mButtonDown = true;
				mListener->FirePrimary();
			}
		}
		else
			mButtonDown = false;

	}

}
void CCLayerParent::ccTouchEnded(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent)
{
	CCPoint touchPoint = this->convertTouchToNodeSpace(pTouch);
    
	CCArray* movers = _humanPlayer->getAllEntitiesOnTeam(_humanPlayer->team()->team,"SelectionComponent");
	for(UINT i=0;i<movers->count();i++){ 
		Entity* entity =(Entity* ) movers->objectAtIndex(i);
		SelectionComponent* select = entity->select();
		if(select->selected)
		{
			MoveComponent* move = entity->move();
			RenderComponent* render = entity->render();
			move->moveTarget = touchPoint;
			GunComponent* gun = entity->gun();
			if (gun) {
				CCPoint vector = ccpNormalize(ccpSub(render->node->getPosition(), touchPoint));
				move->moveTarget = ccpAdd(touchPoint, ccpMult(vector, gun->deck->fight.Range / 2));
			}
			//CCLog("Destination %d %f,%f",entity->_eid,touchPoint.x,touchPoint.y);
		}
	}

}
void Canon ::shoot(MyObject* m_enemy, float dt)
{
	CCPoint totarget =  ccpSub(m_enemy->m_pos, this->m_pos);
	float a = ccpDot(m_enemy->m_velocity,m_enemy->m_velocity) - (m_maxVelocity *m_maxVelocity);
	float b = 2 * ccpDot(m_enemy->m_velocity, totarget);
	float c = ccpDot(totarget,totarget);

	float p = -b / (2 * a);
	float q = (float)sqrt((b * b) - 4 * a * c) / (2 * a);

	float t1 = p - q;
	float t2 = p + q;
	float t;

	if (t1 > t2 && t2 > 0)
	{
		t = t2;
	}
	else
	{
		t = t1;
	}

	CCPoint aimSpot = ccpAdd(m_enemy->m_pos ,ccpMult(m_enemy->m_velocity,t)); //position of target in future after t seconds
	CCPoint BoomPath = ccpSub (aimSpot , m_pos );
	float timeToImpact = ccpLength(BoomPath) / m_maxVelocity/60; //speed must be in units per second


	m_BoomManager->addBoom(new Boom(layer, m_pos,timeToImpact,m_maxVelocity));

	for (int i =0; i < m_BoomManager->getListBoom().size(); i++)
	{
		m_BoomManager->getBoom(i)->setTarget(aimSpot);
		m_BoomManager->getBoom(i)->m_Active = true;
	}

}
Exemple #6
0
    void CameraObserver::OnNotifyChange(INotifier *notify, const INotifyEvent *event)
    {
        if (NULL == event)
        {
            return;
        }
        switch (event->GetNotifyEventType())
        {
            case ENCameraEvent::enPosChanged:
                {
                    const CameraPosChanged *posChangedEvent = reinterpret_cast<const CameraPosChanged*>(event);
                    //setPosition(cocos2d::ccpNeg(posChangedEvent->GetCameraPosition()));
					cocos2d::CCPoint newPos = cocos2d::ccpNeg(posChangedEvent->GetCameraPosition());
					cocos2d::CCPoint dis = cocos2d::ccpSub(newPos, m_lastPos);
					if ( m_pChildren && m_pChildren->count() > 0 )
					{
						CCObject* child;
						CCARRAY_FOREACH(m_pChildren, child)
						{
							CCNode* pNode = (CCNode*)child;
							if (pNode)
							{
								MoveScale::iterator it = m_moveScale.find(pNode);
								if (m_moveScale.end() == it)
								{
									pNode->setPosition(newPos);
								}
								else
								{
									pNode->setPosition(ccpAdd(pNode->getPosition(), ccpMult(dis, it->second)));
								}
							}
						}
					}
					m_lastPos = cocos2d::ccpNeg(posChangedEvent->GetCameraPosition());
                }
Exemple #7
0
void CAIndicator::ccTouchMoved(CATouch *pTouch, CAEvent *pEvent)
{
    DPoint point = m_pIndicator->getCenterOrigin();
    DPoint p_off = ccpSub(this->convertToNodeSpace(pTouch->getLocation()),
                           this->convertToNodeSpace(pTouch->getPreviousLocation()));
    
    DSize size = m_pIndicator->getFrame().size;
    
    if (m_eType == CAIndicatorTypeHorizontal)
    {
        point.x += p_off.x;
        point.x = MAX(point.x, size.width/2);
        point.x = MIN(point.x, m_obContentSize.width - size.width/2);
    }
    else
    {
        point.y += p_off.y;
        point.y = MAX(point.y, size.height/2);
        point.y = MIN(point.y, m_obContentSize.height - size.height/2);
    }
    m_pIndicator->setCenterOrigin(point);
    
    DSize indictor_size = ccpSub(m_obContentSize, size);
    DPoint indictor_point = ccpSub(point, ccpMult(size, 0.5f));
    DSize view_size = ccpSub(m_pMyScrollView->getViewSize(), m_pMyScrollView->getBounds().size);
    DPoint view_offset = m_pMyScrollView->getContentOffset();
    if (m_eType == CAIndicatorTypeHorizontal)
    {
        view_offset.x = indictor_point.x / indictor_size.width * view_size.width;
    }
    else
    {
        view_offset.y = indictor_point.y / indictor_size.height * view_size.height;
    }
    m_pMyScrollView->setContentOffset(view_offset, false);
}
Exemple #8
0
void HFViewport::intervalMove(float dt)
{
    if (limitSpeedX > 0 && fabsf(m_tScrollDistance.x) > limitSpeedX) {
        m_tScrollDistance.x = m_tScrollDistance.x > 0 ? limitSpeedX:-limitSpeedX;
    }
    if (limitSpeedY > 0 && fabsf(m_tScrollDistance.y) > limitSpeedY) {
        m_tScrollDistance.y = m_tScrollDistance.y > 0 ? limitSpeedY:-limitSpeedY;;
    }
    applyPos(m_tScrollDistance);
    m_tScrollDistance = ccpMult(m_tScrollDistance, SCROLL_DEACCEL_RATE);
    
    if (fabsf(m_tScrollDistance.x) <= SCROLL_DEACCEL_DIST &&
        fabsf(m_tScrollDistance.y) <= SCROLL_DEACCEL_DIST)
    {
        this->unschedule(schedule_selector(HFViewport::intervalMove));
        this->mTouchMode = TouchMode_None;
        if (mTouchDelegate) {
            mTouchDelegate->autoMoveEnd();
        }
        if(isChangeFPS) {
            Director::getInstance()->setAnimationInterval(g_LOW_FPS);
        }
    }
}
	bool CCFollow::initWithTarget(CCNode *pFollowedNode, const CCRect& rect)
	{
		CCAssert(pFollowedNode != NULL, "");
		pFollowedNode->retain();
		m_pobFollowedNode = pFollowedNode;
		m_bBoundarySet = true;
		m_bBoundaryFullyCovered = false;

		CCSize winSize = CCDirector::sharedDirector()->getWinSize();
		m_obFullScreenSize = CCPointMake(winSize.width, winSize.height);
		m_obHalfScreenSize = ccpMult(m_obFullScreenSize, 0.5f);

		m_fLeftBoundary = -((rect.origin.x+rect.size.width) - m_obFullScreenSize.x);
		m_fRightBoundary = -rect.origin.x ;
		m_fTopBoundary = -rect.origin.y;
		m_fBottomBoundary = -((rect.origin.y+rect.size.height) - m_obFullScreenSize.y);

		if (m_fRightBoundary < m_fLeftBoundary)
		{
			// screen width is larger than world's boundary width
			//set both in the middle of the world
			m_fRightBoundary = m_fLeftBoundary = (m_fLeftBoundary + m_fRightBoundary) / 2;
		}
		if (m_fTopBoundary < m_fBottomBoundary)
		{
			// screen width is larger than world's boundary width
			//set both in the middle of the world
			m_fTopBoundary = m_fBottomBoundary = (m_fTopBoundary + m_fBottomBoundary) / 2;
		}

		if ((m_fTopBoundary == m_fBottomBoundary) && (m_fLeftBoundary == m_fRightBoundary))
		{
			m_bBoundaryFullyCovered = true;
		}
		return true;
	}
Exemple #10
0
void UIDragPanel::moveByUpdate(float t)
{
    float easeRate = 0.0f;
    switch (m_eMoveType)
    {
        case DRAGPANEL_MOVE_TYPE_AUTOMOVE:
            easeRate = m_fAutoMoveEaseRate;
            break;
            
        case DRAGPANEL_MOVE_TYPE_BOUNCE:
            easeRate = m_fBounceEaseRate;
            break;
            
        default:
            break;
    }
    t = powf(t, 1 / easeRate);
    
    CCPoint currentPos = m_pActionWidget->getPosition();
    CCPoint diff = ccpSub(currentPos, m_previousPosition);
    m_startPosition = ccpAdd( m_startPosition, diff);
    
    CCPoint newPos = ccpAdd( m_startPosition, ccpMult(m_positionDelta, t) );
    m_pActionWidget->setPosition(newPos);
    m_previousPosition = newPos;
    
    switch (m_eMoveType)
    {
        case DRAGPANEL_MOVE_TYPE_AUTOMOVE:
            autoMove();
            break;
            
        default:
            break;
    }
}
Exemple #11
0
bool HFViewport::boundPos(cocos2d::CCPoint& pos)
{
    auto winsize = CCDirector::sharedDirector()->getWinSize();
    float scale = m_TargetNode->getScale();
    mCurZoomScale = scale;
    
    //Correct for anchor
    cocos2d::CCPoint anchor = ccp(m_TargetNode->getContentSize().width * m_TargetNode->getAnchorPoint().x,
                                  m_TargetNode->getContentSize().height * m_TargetNode->getAnchorPoint().y);
    
    anchor = ccpMult(anchor, (1.0f - scale));
    
    CCPoint visibleTopRight(winsize.width, winsize.height);
    CCPoint visibleBottomLeft = CCPointZero;
    visibleTopRight = ccpAdd(visibleTopRight, visibleBottomLeft);
    
    auto size = CCDirector::sharedDirector()->getWinSize();
    float fixW = size.width;
    float fixH = size.height;

    if (isForDiamond) {
        auto fixSize = mWorldBound.size + CCSize(fixW / 2,fixH / 2);
        auto fixOrigin = mWorldBound.origin + ccp(fixW / 2, fixH / 2);
        topRight = ccpAdd(ccpSub(ccpMult(fixSize, scale), visibleTopRight), anchor);
        bottomLeft = ccpSub(ccpAdd(ccpMult(fixOrigin, scale), visibleBottomLeft), anchor);
        
    } else {
        topRight = ccpAdd(ccpSub(ccpMult(this->mWorldBound.size, scale), visibleTopRight), anchor);
        bottomLeft = ccpSub(ccpAdd(ccpMult(this->mWorldBound.origin, scale), visibleBottomLeft), anchor);
    }
    
    
    if (bottomLeft.x < pos.x ) 
    {
        pos.x = bottomLeft.x;
    }
    else if (pos.x < -topRight.x)
    {
        pos.x = -topRight.x;
    }
    
    if (bottomLeft.y < pos.y )
    {
        pos.y = bottomLeft.y;
    }
    else if(pos.y < -topRight.y)
    {
        pos.y = -topRight.y;
    }
    
    if (isForDiamond) {
        auto isNeedToAdjust = [](const CCPoint &p1, const CCPoint &p2){
            int dx = (p2.x - p1.x);
            int dy = (p2.y - p1.y);
            dx = abs(dx);
            dy = abs(dy);
            if(dx > 2 * dy){
                return true;
            }
            return false;
        };
        
        auto adjust = [](CCPoint &p1, CCPoint &p2, bool isTop){
            int dx = (p2.x - p1.x);
            dx = abs(dx);

            if(isTop){
                p1.y = p2.y + dx / 2;
            }else{
                p1.y = p2.y - dx / 2;
            }
        };
        auto ptDown = ccp(-bottomLeft.x + mWorldBound.size.width / 2 * scale, -bottomLeft.y) * -1;
        auto ptUp = ccp(-bottomLeft.x + mWorldBound.size.width / 2 * scale, -bottomLeft.y + mWorldBound.size.height * scale) * -1;
        auto centerPt = (ptDown + ptUp) / 2;
        if(pos.y > centerPt.y){//left_up and left_down
            if(isNeedToAdjust(pos, ptDown)){
                adjust(pos, ptDown, false);
            }
        }else{
            if(isNeedToAdjust(pos, ptUp)){
                adjust(pos, ptUp, true);
            }
        }
        
        
//        auto pInside = [](const CCPoint& p1,const CCPoint& p2,const CCPoint& p3){
//            // (x1-x3)*(y2-y3)-(y1-y3)*(x2-x3)
//            // p3 is at left side to p1p2,then return true
//            return (p1.x-p3.x)*(p2.y-p3.y)-(p1.y-p3.y)*(p2.x-p3.x) < 0 ? false : true;
//        };
//        
//        float halfWidth = (topRight.x - bottomLeft.x)/2;
//        float halfHeight = (topRight.y - bottomLeft.y)/2;
//        
//        // caution: bottomLeft and topRight is reverse
//        // and pos is also reverse
//        // so when pos in the top left zone,it means the bottom right zone
//        auto centerPoint = -(bottomLeft + topRight)/2;
//        auto reversePos = centerPoint*2 - pos;
//        
////        float wh = halfWidth/halfHeight;
//        float hw = halfHeight/halfWidth;
//        auto pLeft = ccp(-topRight.x,-topRight.y+halfHeight);
//        auto pBottom = ccp(-topRight.x+halfWidth,-topRight.y);
//        auto pRight = ccp(-topRight.x+2*halfWidth, -topRight.y+halfHeight);
//        auto pTop = ccp(-topRight.x+halfWidth, -topRight.y+2*halfHeight);
//        
//        if (pos.x < centerPoint.x && pos.y < centerPoint.y) {
//            // top right corner
//            if (pInside(pTop,pRight,reversePos)) {
////                if (m_tScrollDistance.x == 0 || m_tScrollDistance.y/m_tScrollDistance.x > wh) {
////                    pos.x = -wh*(pos.y-pLeft.y)+pLeft.x;
////                } else {
//                    pos.y = -hw*(pos.x-pLeft.x)+pLeft.y;
////                }
//            }
//            
//        } else if (pos.x < centerPoint.x && pos.y > centerPoint.y) {
//            // bottom right corner
//            if (pInside(pRight,pBottom,reversePos)) {
////                if (m_tScrollDistance.x == 0 || -m_tScrollDistance.y/m_tScrollDistance.x > wh) {
////                    pos.x = wh*(pos.y-pTop.y)+pTop.x;
////                } else {
//                    pos.y = hw*(pos.x-pTop.x)+pTop.y;
////                }
//            }
//            
//        } else if (pos.x > centerPoint.x && pos.y > centerPoint.y) {
//            // bottom left corner
//            if (pInside(pBottom,pLeft,reversePos)) {
////                if (m_tScrollDistance.x == 0 || m_tScrollDistance.y/m_tScrollDistance.x > wh) {
////                    pos.x = -wh*(pos.y-pRight.y)+pRight.x;
////                } else {
//                    pos.y = -hw*(pos.x-pRight.x)+pRight.y;
////                }
//            }
//            
//        } else if (pos.x > centerPoint.x && pos.y < centerPoint.y) {
//            // top left corner
//            if (pInside(pLeft,pTop,reversePos)) {
////                if (m_tScrollDistance.x == 0 || -m_tScrollDistance.y/m_tScrollDistance.x > wh) {
////                    pos.x = wh*(pos.y-pBottom.y)+pBottom.x;
////                } else {
//                    pos.y = hw*(pos.x-pBottom.x)+pBottom.y;
////                }
//            }
//        }
    }
    
    return true;
}
Exemple #12
0
CCPoint CAScrollView::maxBouncesLenght()
{
    return ccpMult(m_obContentSize, 0.5f);
}
Exemple #13
0
void CAScrollView::deaccelerateScrolling(float delay)
{
    if (m_tInertia.getLength() > maxSpeedCache(delay))
    {
        m_tInertia = ccpMult(m_tInertia, maxSpeedCache(delay) / m_tInertia.getLength());
    }
    
    CCPoint speed;
    if (m_tInertia.getLength() > maxSpeed(delay))
    {
        speed = ccpMult(m_tInertia, maxSpeed(delay) / m_tInertia.getLength());
    }
    else
    {
        speed = m_tInertia;
    }
    
    m_tInertia = ccpMult(m_tInertia, 1 - decelerationRatio(delay));
    
    CCPoint point = m_pContainer->getCenterOrigin();

    if (m_bBounces)
    {
        CCSize size = this->getContentSize();
        CCSize cSize = m_pContainer->getFrame().size;
        cSize.width = MAX(cSize.width, size.width);
        cSize.height = MAX(cSize.height, size.height);
        
        CCPoint resilience = CCPointZero;
        
        if (point.x - cSize.width / 2 > 0)
        {
            resilience.x = (point.x - cSize.width / 2) / size.width;
        }
        
        if (point.y - cSize.height / 2 > 0)
        {
            resilience.y = (point.y - cSize.height / 2) / size.height;
        }
        
        if ((point.x + cSize.width / 2 - size.width) < 0)
        {
            resilience.x = (point.x + cSize.width / 2 - size.width) / size.width;
        }
        
        if ((point.y + cSize.height / 2 - size.height) < 0)
        {
            resilience.y = (point.y + cSize.height / 2 - size.height) / size.height;
        }
        
        resilience = ccpMult(resilience, maxBouncesSpeed(delay));

        if (speed.getLength() < resilience.getLength())
        {
            speed = ccpSub(speed, resilience);
            m_tInertia = CCPointZero;
        }
    }
    
    point = ccpAdd(point, speed);
    
    if (this->isScrollWindowNotMaxOutSide())
    {
        m_tInertia = CCPointZero;
    }
    
    if (m_bBounces == false)
    {
        point = this->getScrollWindowNotOutPoint(point);
    }
    else
    {
        if (m_bBounceHorizontal == false)
        {
            point.x = this->getScrollWindowNotOutHorizontal(point.x);
        }
        
        if (m_bBounceVertical == false)
        {
            point.y = this->getScrollWindowNotOutVertical(point.y);
        }
    }
    
    if (m_pScrollViewDelegate && point.equals(m_pContainer->getCenter().origin) == false)
    {
        m_pScrollViewDelegate->scrollViewDidScroll(this);
    }
    
    
    m_bDecelerating = true;
    
    if (speed.getLength() <= 0.5f)
    {
        point = this->getScrollWindowNotOutPoint(point);
        m_bDecelerating = false;
        CCDirector::sharedDirector()->getScheduler()->unscheduleSelector(schedule_selector(CAScrollView::deaccelerateScrolling), this);
    }
    
    m_pContainer->setCenterOrigin(point);
    
}
Exemple #14
0
void CAButton::setControlState(const CAControlState& var)
{
    CAControl::setControlState(var);

    CC_RETURN_IF(var == CAControlStateAll);
    
    for (int i=0; i<CAControlStateAll; i++)
    {
        this->removeSubview(m_pBackGroundView[i]);
    }
    
    m_eControlState = var;
    
    if (m_bControlStateLocked)
    {
        m_eControlState = CAControlStateNormal;
    }
    
    if (m_pBackGroundView[m_eControlState] && m_eControlState != CAControlStateNormal)
    {
        m_pBackGroundView[m_eControlState]->setFrame(this->getBounds());
        this->insertSubview(m_pBackGroundView[m_eControlState], -1);
    }
    else if (m_pBackGroundView[CAControlStateNormal])
    {
        m_pBackGroundView[CAControlStateNormal]->setFrame(this->getBounds());
        this->insertSubview(m_pBackGroundView[CAControlStateNormal], -1);
    }
    
    if (m_eControlState == CAControlStateSelected)
    {
        m_bSelected = true;
    }
    else if(m_eControlState != CAControlStateHighlighted)
    {
        m_bSelected = false;
    }
    
    CAImage* image = NULL;
    std::string title = "";
    CCRect imageViewCenter = CCRectZero;
    CCRect rect = CCRectZero;
    CCRect labelCenter = this->getBounds();
    float labelSize = 0;
    
    image = m_pImage[m_eControlState];
    title = m_sTitle[m_eControlState];
    
    if (image == NULL)
    {
        image = this->isSelected() ? m_pImage[CAControlStateSelected] : m_pImage[CAControlStateNormal];
    }
    
    if (strcmp(title.c_str(), "") == 0)
    {
        title = this->isSelected() ? m_sTitle[CAControlStateSelected] : m_sTitle[CAControlStateNormal];
    }
    
    if (image && title.compare("") == 0)
    {
        CCSize size = this->getBounds().size;
        CCSize iSize = image->getContentSize();
        float scaleX = size.width / iSize.width * 0.75f;
        float scaleY = size.height / iSize.height * 0.75f;
        float scale = MIN(scaleX, scaleY);
        scale = MIN(scale, 1.0f);
        iSize = ccpMult(iSize, scale);
        
        imageViewCenter.origin = size / 2;
        imageViewCenter.size = iSize;
    }
    else if (image == NULL && title.compare("") != 0)
    {
        labelSize = this->getBounds().size.height * 0.4f;
        labelCenter.origin = this->getBounds().size / 2 ;
    }
    else if (image && title.compare("") != 0)
    {
        CCSize size = this->getBounds().size;
        CCSize iSize = image->getContentSize();
        float scaleX = size.width / iSize.width * 0.5f;
        float scaleY = size.height / iSize.height * 0.45f;
        float scale = MIN(scaleX, scaleY);
        scale = MIN(scale, 1.0f);
        iSize = ccpMult(iSize, scale);
        
        imageViewCenter.size = iSize;
        imageViewCenter.origin.x = size.width / 2;
        imageViewCenter.origin.y = size.height * 0.35f;
        
        labelSize = size.height * 0.2f;
        labelCenter.origin.x = size.width / 2;
        labelCenter.origin.y = size.height * 0.75f;
    }

    m_pImageView->setColor(m_sImageColor[m_eControlState]);
    m_pImageView->setCenter(imageViewCenter);
    
    if (image != m_pImageView->getImage())
    {
        m_pImageView->setImage(image);
    }
    
    m_pLabel->setColor(m_sTitleColor[m_eControlState]);
    m_pLabel->setCenter(labelCenter);
    
    if (!title.empty())
    {
        m_pLabel->setFontSize(labelSize);
    }
    
    if (strcmp(title.c_str(), m_pLabel->getText().c_str()))
    {
        m_pLabel->setText(title.c_str());
    }
}
void CCParticleSystem::initParticle(tCCParticle* particle)
{
	// timeToLive
	// no negative life. prevent division by 0
	particle->timeToLive = MAX(0, m_fLife + m_fLifeVar * CCRANDOM_MINUS1_1() );

	// position
	particle->pos.x = m_tSourcePosition.x + m_tPosVar.x * CCRANDOM_MINUS1_1();
    particle->pos.x *= CC_CONTENT_SCALE_FACTOR();
	particle->pos.y = m_tSourcePosition.y + m_tPosVar.y * CCRANDOM_MINUS1_1();
    particle->pos.y *= CC_CONTENT_SCALE_FACTOR();

	// Color
	ccColor4F start;
	start.r = MIN(1, MAX(0, m_tStartColor.r + m_tStartColorVar.r * CCRANDOM_MINUS1_1() ) );
	start.g = MIN(1, MAX(0, m_tStartColor.g + m_tStartColorVar.g * CCRANDOM_MINUS1_1() ) );
	start.b = MIN(1, MAX(0, m_tStartColor.b + m_tStartColorVar.b * CCRANDOM_MINUS1_1() ) );
	start.a = MIN(1, MAX(0, m_tStartColor.a + m_tStartColorVar.a * CCRANDOM_MINUS1_1() ) );

	ccColor4F end;
	end.r = MIN(1, MAX(0, m_tEndColor.r + m_tEndColorVar.r * CCRANDOM_MINUS1_1() ) );
	end.g = MIN(1, MAX(0, m_tEndColor.g + m_tEndColorVar.g * CCRANDOM_MINUS1_1() ) );
	end.b = MIN(1, MAX(0, m_tEndColor.b + m_tEndColorVar.b * CCRANDOM_MINUS1_1() ) );
	end.a = MIN(1, MAX(0, m_tEndColor.a + m_tEndColorVar.a * CCRANDOM_MINUS1_1() ) );

	particle->color = start;
	particle->deltaColor.r = (end.r - start.r) / particle->timeToLive;
	particle->deltaColor.g = (end.g - start.g) / particle->timeToLive;
	particle->deltaColor.b = (end.b - start.b) / particle->timeToLive;
	particle->deltaColor.a = (end.a - start.a) / particle->timeToLive;

	// size
	float startS = MAX(0, m_fStartSize + m_fStartSizeVar * CCRANDOM_MINUS1_1() ); // no negative size
    startS *= CC_CONTENT_SCALE_FACTOR();

	particle->size = startS;

	if( m_fEndSize == kCCParticleStartSizeEqualToEndSize )
	{
		particle->deltaSize = 0;
	}
	else
	{
		float endS = m_fEndSize + m_fEndSizeVar * CCRANDOM_MINUS1_1();
		endS = MAX(0, endS);
        endS *= CC_CONTENT_SCALE_FACTOR();
		particle->deltaSize = (endS - startS) / particle->timeToLive;
	}

	// rotation
	float startA = m_fStartSpin + m_fStartSpinVar * CCRANDOM_MINUS1_1();
	float endA = m_fEndSpin + m_fEndSpinVar * CCRANDOM_MINUS1_1();
	particle->rotation = startA;
	particle->deltaRotation = (endA - startA) / particle->timeToLive;

	// position
	if( m_ePositionType == kCCPositionTypeFree )
	{
        CGPoint p = this->convertToWorldSpace(CGPointZero);
		particle->startPos = ccpMult( p, CC_CONTENT_SCALE_FACTOR() );
	}
    else if ( m_ePositionType == kCCPositionTypeRelative )
    {
        particle->startPos = ccpMult( m_tPosition, CC_CONTENT_SCALE_FACTOR() );
    }

	// direction
	float a = CC_DEGREES_TO_RADIANS( m_fAngle + m_fAngleVar * CCRANDOM_MINUS1_1() );	

	// Mode Gravity: A
	if( m_nEmitterMode == kCCParticleModeGravity ) 
	{
		CGPoint v(cosf( a ), sinf( a ));
		float s = modeA.speed + modeA.speedVar * CCRANDOM_MINUS1_1();
        s *= CC_CONTENT_SCALE_FACTOR();

		// direction
		particle->modeA.dir = ccpMult( v, s );

		// radial accel
		particle->modeA.radialAccel = modeA.radialAccel + modeA.radialAccelVar * CCRANDOM_MINUS1_1();
        particle->modeA.radialAccel *= CC_CONTENT_SCALE_FACTOR();

		// tangential accel
		particle->modeA.tangentialAccel = modeA.tangentialAccel + modeA.tangentialAccelVar * CCRANDOM_MINUS1_1();
        particle->modeA.tangentialAccel *= CC_CONTENT_SCALE_FACTOR();
    }

	// Mode Radius: B
	else {
		// Set the default diameter of the particle from the source position
		float startRadius = modeB.startRadius + modeB.startRadiusVar * CCRANDOM_MINUS1_1();
		float endRadius = modeB.endRadius + modeB.endRadiusVar * CCRANDOM_MINUS1_1();
        startRadius *= CC_CONTENT_SCALE_FACTOR();
        endRadius *= CC_CONTENT_SCALE_FACTOR();

		particle->modeB.radius = startRadius;

		if( modeB.endRadius == kCCParticleStartRadiusEqualToEndRadius )
			particle->modeB.deltaRadius = 0;
		else
			particle->modeB.deltaRadius = (endRadius - startRadius) / particle->timeToLive;

		particle->modeB.angle = a;
		particle->modeB.degreesPerSecond = CC_DEGREES_TO_RADIANS(modeB.rotatePerSecond + modeB.rotatePerSecondVar * CCRANDOM_MINUS1_1());
	}	
}
Exemple #16
0
///
//    Update does the work of mapping the texture onto the triangles for the bar
//    It now doesn't occur the cost of free/alloc data every update cycle.
//    It also only changes the percentage point but no other points if they have not
//    been modified.
//    
//    It now deals with flipped texture. If you run into this problem, just use the
//    sprite property and enable the methods flipX, flipY.
///
void CCProgressTimer::updateBar()
{
    if (!m_pSprite) {
        return;
    }
    float alpha = m_fPercentage / 100.0f;
    CCPoint alphaOffset = ccpMult(ccp(1.0f * (1.0f - m_tBarChangeRate.x) + alpha * m_tBarChangeRate.x, 1.0f * (1.0f - m_tBarChangeRate.y) + alpha * m_tBarChangeRate.y), 0.5f);
    CCPoint min = ccpSub(m_tMidpoint, alphaOffset);
    CCPoint max = ccpAdd(m_tMidpoint, alphaOffset);

    if (min.x < 0.f) {
        max.x += -min.x;
        min.x = 0.f;
    }

    if (max.x > 1.f) {
        min.x -= max.x - 1.f;
        max.x = 1.f;
    }

    if (min.y < 0.f) {
        max.y += -min.y;
        min.y = 0.f;
    }

    if (max.y > 1.f) {
        min.y -= max.y - 1.f;
        max.y = 1.f;
    }


    if (!m_bReverseDirection) {
        if(!m_pVertexData) {
            m_nVertexDataCount = 4;
            m_pVertexData = (ccV2F_C4B_T2F*)malloc(m_nVertexDataCount * sizeof(ccV2F_C4B_T2F));
            CCAssert( m_pVertexData, "CCProgressTimer. Not enough memory");
        }
        //    TOPLEFT
        m_pVertexData[0].texCoords = textureCoordFromAlphaPoint(ccp(min.x,max.y));
        m_pVertexData[0].vertices = vertexFromAlphaPoint(ccp(min.x,max.y));

        //    BOTLEFT
        m_pVertexData[1].texCoords = textureCoordFromAlphaPoint(ccp(min.x,min.y));
        m_pVertexData[1].vertices = vertexFromAlphaPoint(ccp(min.x,min.y));

        //    TOPRIGHT
        m_pVertexData[2].texCoords = textureCoordFromAlphaPoint(ccp(max.x,max.y));
        m_pVertexData[2].vertices = vertexFromAlphaPoint(ccp(max.x,max.y));

        //    BOTRIGHT
        m_pVertexData[3].texCoords = textureCoordFromAlphaPoint(ccp(max.x,min.y));
        m_pVertexData[3].vertices = vertexFromAlphaPoint(ccp(max.x,min.y));
    } else {
        if(!m_pVertexData) {
            m_nVertexDataCount = 8;
            m_pVertexData = (ccV2F_C4B_T2F*)malloc(m_nVertexDataCount * sizeof(ccV2F_C4B_T2F));
            CCAssert( m_pVertexData, "CCProgressTimer. Not enough memory");
            //    TOPLEFT 1
            m_pVertexData[0].texCoords = textureCoordFromAlphaPoint(ccp(0,1));
            m_pVertexData[0].vertices = vertexFromAlphaPoint(ccp(0,1));

            //    BOTLEFT 1
            m_pVertexData[1].texCoords = textureCoordFromAlphaPoint(ccp(0,0));
            m_pVertexData[1].vertices = vertexFromAlphaPoint(ccp(0,0));

            //    TOPRIGHT 2
            m_pVertexData[6].texCoords = textureCoordFromAlphaPoint(ccp(1,1));
            m_pVertexData[6].vertices = vertexFromAlphaPoint(ccp(1,1));

            //    BOTRIGHT 2
            m_pVertexData[7].texCoords = textureCoordFromAlphaPoint(ccp(1,0));
            m_pVertexData[7].vertices = vertexFromAlphaPoint(ccp(1,0));
        }

        //    TOPRIGHT 1
        m_pVertexData[2].texCoords = textureCoordFromAlphaPoint(ccp(min.x,max.y));
        m_pVertexData[2].vertices = vertexFromAlphaPoint(ccp(min.x,max.y));

        //    BOTRIGHT 1
        m_pVertexData[3].texCoords = textureCoordFromAlphaPoint(ccp(min.x,min.y));
        m_pVertexData[3].vertices = vertexFromAlphaPoint(ccp(min.x,min.y));

        //    TOPLEFT 2
        m_pVertexData[4].texCoords = textureCoordFromAlphaPoint(ccp(max.x,max.y));
        m_pVertexData[4].vertices = vertexFromAlphaPoint(ccp(max.x,max.y));

        //    BOTLEFT 2
        m_pVertexData[5].texCoords = textureCoordFromAlphaPoint(ccp(max.x,min.y));
        m_pVertexData[5].vertices = vertexFromAlphaPoint(ccp(max.x,min.y));
    }
    updateColor();
}
CCPoint ccpLerp(CCPoint a, CCPoint b, float alpha)
{
	return ccpAdd(ccpMult(a, 1.f - alpha), ccpMult(b, alpha));
}
CCPoint
ccpNormalize(const CCPoint v)
{
	return ccpMult(v, 1.0f/ccpLength(v));
}
Exemple #19
0
CCPoint ccpLerp(const CCPoint& a, const CCPoint& b, float alpha)
{
    return ccpAdd(ccpMult(a, 1.f - alpha), ccpMult(b, alpha));
}
void CCParticleSystemFrameQuad::update(float dt)
{
    CC_PROFILER_START_CATEGORY(kCCProfilerCategoryParticles , "CCParticleSystemFrameQuad - update");

    if (m_bIsActive && m_fEmissionRate)
    {
        float rate = 1.0f / m_fEmissionRate;
        //issue #1201, prevent bursts of particles, due to too high emitCounter
        if (m_uParticleCount < m_uTotalParticles)
        {
            m_fEmitCounter += dt;
        }
        
        while (m_uParticleCount < m_uTotalParticles && m_fEmitCounter > rate) 
        {
            this->addParticle();
            m_fEmitCounter -= rate;
        }

        m_fElapsed += dt;
        if (m_fDuration != -1 && m_fDuration < m_fElapsed)
        {
            this->stopSystem();
        }
    }

    m_uParticleIdx = 0;

    CCPoint currentPosition = CCPointZero;
    if (m_ePositionType == kCCPositionTypeFree)
    {
        currentPosition = this->convertToWorldSpace(CCPointZero);
    }
    else if (m_ePositionType == kCCPositionTypeRelative)
    {
        currentPosition = m_obPosition;
    }

    if (m_bVisible)
    {
        while (m_uParticleIdx < m_uParticleCount)
        {
            tCCParticle *p = &m_pParticles[m_uParticleIdx];

            // life
            p->timeToLive -= dt;

            if (p->timeToLive > 0) 
            {
                // Mode A: gravity, direction, tangential accel & radial accel
                if (m_nEmitterMode == kCCParticleModeGravity) 
                {
                    CCPoint tmp, radial, tangential;

                    radial = CCPointZero;
                    // radial acceleration
                    if (p->pos.x || p->pos.y)
                    {
                        radial = ccpNormalize(p->pos);
                    }
                    tangential = radial;
                    radial = ccpMult(radial, p->modeA.radialAccel);

                    // tangential acceleration
                    float newy = tangential.x;
                    tangential.x = -tangential.y;
                    tangential.y = newy;
                    tangential = ccpMult(tangential, p->modeA.tangentialAccel);

                    // (gravity + radial + tangential) * dt
                    tmp = ccpAdd( ccpAdd( radial, tangential), modeA.gravity);
                    tmp = ccpMult( tmp, dt);
                    p->modeA.dir = ccpAdd( p->modeA.dir, tmp);
                    tmp = ccpMult(p->modeA.dir, dt);
                    p->pos = ccpAdd( p->pos, tmp );
                }

                // Mode B: radius movement
                else 
                {                
                    // Update the angle and radius of the particle.
                    p->modeB.angle += p->modeB.degreesPerSecond * dt;
                    p->modeB.radius += p->modeB.deltaRadius * dt;

                    p->pos.x = - cosf(p->modeB.angle) * p->modeB.radius;
                    p->pos.y = - sinf(p->modeB.angle) * p->modeB.radius;
                }

                // color
                p->color.r += (p->deltaColor.r * dt);
                p->color.g += (p->deltaColor.g * dt);
                p->color.b += (p->deltaColor.b * dt);
                p->color.a += (p->deltaColor.a * dt);

                // size
                p->size += (p->deltaSize * dt);
                p->size = MAX( 0, p->size );

                // angle
                p->rotation += (p->deltaRotation * dt);

                //
                // update values in quad
                //

                CCPoint    newPos;

                if (m_ePositionType == kCCPositionTypeFree || m_ePositionType == kCCPositionTypeRelative) 
                {
                    CCPoint diff = ccpSub( currentPosition, p->startPos );
                    newPos = ccpSub(p->pos, diff);
                } 
                else
                {
                    newPos = p->pos;
                }

                // translate newPos to correct position, since matrix transform isn't performed in batchnode
                // don't update the particle with the new position information, it will interfere with the radius and tangential calculations
                if (m_pBatchNode)
                {
                    newPos.x+=m_obPosition.x;
                    newPos.y+=m_obPosition.y;
                }

                updateQuadWithParticle(p, newPos);
                //updateParticleImp(self, updateParticleSel, p, newPos);

                // update particle counter
                ++m_uParticleIdx;
            } 
            else 
            {
                // life < 0
                int currentIndex = p->atlasIndex;
                if( m_uParticleIdx != m_uParticleCount-1 )
                {
                    m_pParticles[m_uParticleIdx] = m_pParticles[m_uParticleCount-1];
                }
                if (m_pBatchNode)
                {
                    //disable the switched particle
                    m_pBatchNode->disableParticle(m_uAtlasIndex+currentIndex);

                    //switch indexes
                    m_pParticles[m_uParticleCount-1].atlasIndex = currentIndex;
                }
				else if( m_uParticleIdx != m_uParticleCount-1 )
				{
					//switch quads texCoords
					ccV3F_C4B_T2F_Quad temp = m_pQuads[m_uParticleIdx];
					m_pQuads[m_uParticleIdx] = m_pQuads[m_uParticleCount-1];
					m_pQuads[m_uParticleCount-1] = temp;
				}


                --m_uParticleCount;

                if( m_uParticleCount == 0 && m_bIsAutoRemoveOnFinish )
                {
                    this->unscheduleUpdate();
                    m_pParent->removeChild(this, true);
                    return;
                }
            }
        } //while
        m_bTransformSystemDirty = false;
    }
    if (! m_pBatchNode)
    {
        postStep();
    }

    CC_PROFILER_STOP_CATEGORY(kCCProfilerCategoryParticles , "CCParticleSystemFrameQuad - update");
}
Exemple #21
0
void MapObject::modifyPoint(ContactPoint *point, const cocos2d::CCPoint offset, const float radius)
{
	point->offset = ccpMult(offset, kPointFactor);
	point->radius = radius * kPointFactor;
	point->position = ccpAdd(this->getPosition(), point->offset);
}
Exemple #22
0
bool RigSimilar(const Rig& compare, const Rig& index, float& similarity)
{
    // Calculate the difference between the two rigs being compared in size.
    int difference = abs(compare.size() - index.size());
    
    // Threshold of comparison = the bigger one.
    int del = MAX(compare.size(), index.size());

    float percentage = (float)difference / (float)del;
    
    // The below is basically found through trial and error, when there are over 25% difference in the number of vertexes it seems displeasing to the eye.
    if( percentage > 0.25 ) return false;

    // Ignore the BADLY NAMED variables below - the smaller/bigger rig has nothing to do with the results.
    Rig smallerRig = compare;
    Rig biggerRig = index;
    
    /*
    // This code has been commented out as I've updated the function so that it doesn't need to know which rig is smaller/bigger.
     
    for(Rig::iterator curPos = biggerRig.begin();
        curPos != biggerRig.end();)
    {
        Rig::iterator nextPos = curPos + 1;
        if(nextPos == biggerRig.end()) nextPos = biggerRig.begin();
        
        CCPoint curPoint = (*curPos);
        CCPoint nextPoint = (*nextPos);
        
        if(ccpDistance(curPoint, nextPoint) < tolerance)
        {
            curPos = biggerRig.erase(nextPos);
        }
        else
        {
            curPos++;
        }
    }
     */
    
    // Calculate the center of mass for the smaller rig.
    // RigCenter basically returns the coordinate of all points added divided by the number of vertexes.
    // Normalize the points to the center.
    const CCPoint smallerMid = RigCenter(smallerRig);
    for(int i = 0; i < smallerRig.size(); i++)
    {
        smallerRig[i] = ccpSub(smallerRig[i], smallerMid);
    }
    
    const CCPoint biggerMid = RigCenter(biggerRig);
    for(int i = 0; i < biggerRig.size(); i++)
    {
        biggerRig[i] = ccpSub(biggerRig[i], biggerMid);
    }
    
    // Rig area does some matrix magic to calculate the area of the rig.
    float smallerArea = RigArea(smallerRig);
    float biggerArea = RigArea(biggerRig);
    
    // Scale the rig so that there wouldn't be big differences in overlaps when comparing similar points.
    float scale = sqrtf(biggerArea/smallerArea);
    for(int i = 0; i < smallerRig.size(); i++)
    {
        smallerRig[i] = ccpMult(smallerRig[i], scale);
    }
    
    // FIXFIX:: The problem right now is that the Rig's centers are focus around the origin (0,0). That is retarded - fix this so that they will be focused around the centroid.
    int nearPoints = 0;
    for(int i = 0; i < smallerRig.size(); i++)
    {
        CCPoint curPoint = smallerRig[i];
        
        for(int v = 0; v < biggerRig.size(); v++)
        {
            if(PointToleranceEquals(biggerRig[v], curPoint))
            {
                nearPoints++;
                break;
            }
        }
    }
    
    // Double iteration to find the closest points
    Rig combination = biggerRig;
    for(int i = 0; i < smallerRig.size(); i++)
    {
        CCPoint curPoint = smallerRig[i];
        bool skip = false;
        
        for(int v = 0; v < combination.size(); v++)
        {
            // The function below is a very simple function that gives a bit of tolerence for equality when comparing nearby points. This accounts for humans not having perfect eyesight.
            if(PointToleranceEquals(combination[v], curPoint))
            {
                skip = true;
            }
        }
        
        if(!skip) combination.push_back(curPoint);
    }
    
    //Notice how I'm using smaller size instead of bigger rig's.
    //This is because rig2 is the goal polygon - (lol refactor this so it has better naming.)
    //return nearPoints == compare.size();
    
    similarity = (float)nearPoints / combination.size();
    
    // If the similarity is over 1, it means that the goal polygon is smaller than the comparing polygon.
    return similarity >= 0.75f && similarity <= 1.f;
}
Exemple #23
0
///
//    Update does the work of mapping the texture onto the triangles
//    It now doesn't occur the cost of free/alloc data every update cycle.
//    It also only changes the percentage point but no other points if they have not
//    been modified.
//    
//    It now deals with flipped texture. If you run into this problem, just use the
//    sprite property and enable the methods flipX, flipY.
///
void CCProgressTimer::updateRadial()
{
    if (!m_pSprite) {
        return;
    }
    float alpha = m_fPercentage / 100.f;

    float angle = 2.f*((float)M_PI) * ( m_bReverseDirection ? alpha : 1.0f - alpha);

    //    We find the vector to do a hit detection based on the percentage
    //    We know the first vector is the one @ 12 o'clock (top,mid) so we rotate
    //    from that by the progress angle around the m_tMidpoint pivot
    CCPoint topMid = ccp(m_tMidpoint.x, 1.f);
    CCPoint percentagePt = ccpRotateByAngle(topMid, m_tMidpoint, angle);


    int index = 0;
    CCPoint hit = CCPoint::zero;

    if (alpha == 0.f) {
        //    More efficient since we don't always need to check intersection
        //    If the alpha is zero then the hit point is top mid and the index is 0.
        hit = topMid;
        index = 0;
    } else if (alpha == 1.f) {
        //    More efficient since we don't always need to check intersection
        //    If the alpha is one then the hit point is top mid and the index is 4.
        hit = topMid;
        index = 4;
    } else {
        //    We run a for loop checking the edges of the texture to find the
        //    intersection point
        //    We loop through five points since the top is split in half

        float min_t = FLT_MAX;

        for (int i = 0; i <= kProgressTextureCoordsCount; ++i) {
            int pIndex = (i + (kProgressTextureCoordsCount - 1))%kProgressTextureCoordsCount;

            CCPoint edgePtA = boundaryTexCoord(i % kProgressTextureCoordsCount);
            CCPoint edgePtB = boundaryTexCoord(pIndex);

            //    Remember that the top edge is split in half for the 12 o'clock position
            //    Let's deal with that here by finding the correct endpoints
            if(i == 0){
                edgePtB = ccpLerp(edgePtA, edgePtB, 1-m_tMidpoint.x);
            } else if(i == 4){
                edgePtA = ccpLerp(edgePtA, edgePtB, 1-m_tMidpoint.x);
            }

            //    s and t are returned by ccpLineIntersect
            float s = 0, t = 0;
            if(ccpLineIntersect(edgePtA, edgePtB, m_tMidpoint, percentagePt, &s, &t))
            {

                //    Since our hit test is on rays we have to deal with the top edge
                //    being in split in half so we have to test as a segment
                if ((i == 0 || i == 4)) {
                    //    s represents the point between edgePtA--edgePtB
                    if (!(0.f <= s && s <= 1.f)) {
                        continue;
                    }
                }
                //    As long as our t isn't negative we are at least finding a
                //    correct hitpoint from m_tMidpoint to percentagePt.
                if (t >= 0.f) {
                    //    Because the percentage line and all the texture edges are
                    //    rays we should only account for the shortest intersection
                    if (t < min_t) {
                        min_t = t;
                        index = i;
                    }
                }
            }
        }

        //    Now that we have the minimum magnitude we can use that to find our intersection
        hit = ccpAdd(m_tMidpoint, ccpMult(ccpSub(percentagePt, m_tMidpoint),min_t));

    }


    //    The size of the vertex data is the index from the hitpoint
    //    the 3 is for the m_tMidpoint, 12 o'clock point and hitpoint position.

    bool sameIndexCount = true;
    if(m_nVertexDataCount != index + 3){
        sameIndexCount = false;
        CC_SAFE_FREE(m_pVertexData);
        m_nVertexDataCount = 0;
    }


    if(!m_pVertexData) {
        m_nVertexDataCount = index + 3;
        m_pVertexData = (ccV2F_C4B_T2F*)malloc(m_nVertexDataCount * sizeof(ccV2F_C4B_T2F));
        CCAssert( m_pVertexData, "CCProgressTimer. Not enough memory");
    }
    updateColor();

    if (!sameIndexCount) {

        //    First we populate the array with the m_tMidpoint, then all
        //    vertices/texcoords/colors of the 12 'o clock start and edges and the hitpoint
        m_pVertexData[0].texCoords = textureCoordFromAlphaPoint(m_tMidpoint);
        m_pVertexData[0].vertices = vertexFromAlphaPoint(m_tMidpoint);

        m_pVertexData[1].texCoords = textureCoordFromAlphaPoint(topMid);
        m_pVertexData[1].vertices = vertexFromAlphaPoint(topMid);

        for(int i = 0; i < index; ++i){
            CCPoint alphaPoint = boundaryTexCoord(i);
            m_pVertexData[i+2].texCoords = textureCoordFromAlphaPoint(alphaPoint);
            m_pVertexData[i+2].vertices = vertexFromAlphaPoint(alphaPoint);
        }
    }

    //    hitpoint will go last
    m_pVertexData[m_nVertexDataCount - 1].texCoords = textureCoordFromAlphaPoint(hit);
    m_pVertexData[m_nVertexDataCount - 1].vertices = vertexFromAlphaPoint(hit);

}
void PaintLayer::drawLines(CCArray *linePoints, ccColor4F color)
{
    unsigned int numberOfVertices = (linePoints->count() - 1) * 18;
    LineVertex *vertices = (LineVertex *)calloc(sizeof(LineVertex), numberOfVertices);

    CCPoint prevPoint =  ((LinePoint *)linePoints->objectAtIndex(0))->pos;
    float prevValue = ((LinePoint *)linePoints->objectAtIndex(0))->width;
    float curValue;
    int index = 0;
    for (int i = 1; i < linePoints->count(); ++i)
    {
        LinePoint *pointValue = (LinePoint *)linePoints->objectAtIndex(i);
        CCPoint curPoint = pointValue->pos;
        curValue = pointValue->width;

        //! equal points, skip them
        if (ccpFuzzyEqual(curPoint, prevPoint, 0.0001f))
        {
            continue;
        }

        CCPoint dir = ccpSub(curPoint, prevPoint);
        CCPoint perpendicular = ccpNormalize(ccpPerp(dir));
        CCPoint A = ccpAdd(prevPoint, ccpMult(perpendicular, prevValue / 2));
        CCPoint B = ccpSub(prevPoint, ccpMult(perpendicular, prevValue / 2));
        CCPoint C = ccpAdd(curPoint, ccpMult(perpendicular, curValue / 2));
        CCPoint D = ccpSub(curPoint, ccpMult(perpendicular, curValue / 2));

        //! continuing line
        if (connectingLine || index > 0)
        {
            A = prevC;
            B = prevD;
        }
        else if (index == 0)
        {
            //! circle at start of line, revert direction
            circlesPoints->addObject(pointValue);
            circlesPoints->addObject(linePoints->objectAtIndex(i-1));
        }

        ADD_TRIANGLE(A, B, C, 1.0f);
        ADD_TRIANGLE(B, C, D, 1.0f);

        prevD = D;
        prevC = C;
        if (finishingLine && (i == linePoints->count() - 1))
        {
            circlesPoints->addObject(linePoints->objectAtIndex(i-1));
            circlesPoints->addObject(pointValue);
            finishingLine = false;
        }
        prevPoint = curPoint;
        prevValue = curValue;

        //! Add overdraw
        CCPoint F = ccpAdd(A, ccpMult(perpendicular, overdraw));
        CCPoint G = ccpAdd(C, ccpMult(perpendicular, overdraw));
        CCPoint H = ccpSub(B, ccpMult(perpendicular, overdraw));
        CCPoint I = ccpSub(D, ccpMult(perpendicular, overdraw));

        //! end vertices of last line are the start of this one, also for the overdraw
        if (connectingLine || index > 6)
        {
            F = prevG;
            H = prevI;
        }

        prevG = G;
        prevI = I;

        ADD_TRIANGLE(F, A, G, 2.0f);
        ADD_TRIANGLE(A, G, C, 2.0f);
        ADD_TRIANGLE(B, H, D, 2.0f);
        ADD_TRIANGLE(H, D, I, 2.0f);
    }

    this->fillLineTriangles(vertices, index, color);

    if (index > 0)
    {
        connectingLine = true;
    }

    free(vertices);
}
Exemple #25
0
NS_CC_BEGIN

void ccVertexLineToPolygon(DPoint *points, float stroke, ccVertex2F *vertices, unsigned int offset, unsigned int nuPoints)
{
    nuPoints += offset;
    if(nuPoints<=1) return;

    stroke *= 0.5f;

    unsigned int idx;
    unsigned int nuPointsMinus = nuPoints-1;

    for(unsigned int i = offset; i<nuPoints; i++)
    {
        idx = i*2;
        DPoint p1 = points[i];
        DPoint perpVector;

        if(i == 0)
            perpVector = ccpPerp(ccpNormalize(ccpSub(p1, points[i+1])));
        else if(i == nuPointsMinus)
            perpVector = ccpPerp(ccpNormalize(ccpSub(points[i-1], p1)));
        else
        {
            DPoint p2 = points[i+1];
            DPoint p0 = points[i-1];

            DPoint p2p1 = ccpNormalize(ccpSub(p2, p1));
            DPoint p0p1 = ccpNormalize(ccpSub(p0, p1));

            // Calculate angle between vectors
            float angle = acosf(ccpDot(p2p1, p0p1));

            if(angle < CC_DEGREES_TO_RADIANS(70))
                perpVector = ccpPerp(ccpNormalize(ccpMidpoint(p2p1, p0p1)));
            else if(angle < CC_DEGREES_TO_RADIANS(170))
                perpVector = ccpNormalize(ccpMidpoint(p2p1, p0p1));
            else
                perpVector = ccpPerp(ccpNormalize(ccpSub(p2, p0)));
        }
        perpVector = ccpMult(perpVector, stroke);

        vertices[idx] = vertex2(p1.x+perpVector.x, p1.y+perpVector.y);
        vertices[idx+1] = vertex2(p1.x-perpVector.x, p1.y-perpVector.y);

    }

    // Validate vertexes
    offset = (offset==0) ? 0 : offset-1;
    for(unsigned int i = offset; i<nuPointsMinus; i++)
    {
        idx = i*2;
        const unsigned int idx1 = idx+2;

        ccVertex2F p1 = vertices[idx];
        ccVertex2F p2 = vertices[idx+1];
        ccVertex2F p3 = vertices[idx1];
        ccVertex2F p4 = vertices[idx1+1];

        float s;
        //BOOL fixVertex = !ccpLineIntersect(DPoint(p1.x, p1.y), DPoint(p4.x, p4.y), DPoint(p2.x, p2.y), DPoint(p3.x, p3.y), &s, &t);
        bool fixVertex = !ccVertexLineIntersect(p1.x, p1.y, p4.x, p4.y, p2.x, p2.y, p3.x, p3.y, &s);
        if(!fixVertex)
            if (s<0.0f || s>1.0f)
                fixVertex = true;

        if(fixVertex)
        {
            vertices[idx1] = p4;
            vertices[idx1+1] = p3;
        }
    }
}
Exemple #26
0
CCPoint CAScrollView::getContentOffset()
{
    return ccpMult(m_pContainer->getFrameOrigin(), -1);
}
// ParticleSystem - MainLoop
void CCParticleSystem::update(ccTime dt)
{
	if( m_bIsActive && m_fEmissionRate )
	{
		float rate = 1.0f / m_fEmissionRate;
		m_fEmitCounter += dt;
		while( m_nParticleCount < m_nTotalParticles && m_fEmitCounter > rate ) 
		{
			this->addParticle();
			m_fEmitCounter -= rate;
		}

		m_fElapsed += dt;
		if(m_fDuration != -1 && m_fDuration < m_fElapsed)
		{
			this->stopSystem();
		}
	}

	m_nParticleIdx = 0;


#if CC_ENABLE_PROFILERS
	/// @todo CCProfilingBeginTimingBlock(_profilingTimer);
#endif


	CGPoint currentPosition = CGPointZero;
	if( m_ePositionType == kCCPositionTypeFree )
	{
		currentPosition = this->convertToWorldSpace(CGPointZero);
        currentPosition.x *= CC_CONTENT_SCALE_FACTOR();
        currentPosition.y *= CC_CONTENT_SCALE_FACTOR();
	}
    else if ( m_ePositionType == kCCPositionTypeRelative )
    {
        currentPosition = m_tPosition;
        currentPosition.x *= CC_CONTENT_SCALE_FACTOR();
        currentPosition.y *= CC_CONTENT_SCALE_FACTOR();
    }

	while( m_nParticleIdx < m_nParticleCount )
	{
		tCCParticle *p = &m_pParticles[m_nParticleIdx];

		// life
		p->timeToLive -= dt;

		if( p->timeToLive > 0 ) 
		{
			// Mode A: gravity, direction, tangential accel & radial accel
			if( m_nEmitterMode == kCCParticleModeGravity ) 
			{
				CGPoint tmp, radial, tangential;

				radial = CGPointZero;
				// radial acceleration
				if(p->pos.x || p->pos.y)
					radial = ccpNormalize(p->pos);
				tangential = radial;
				radial = ccpMult(radial, p->modeA.radialAccel);

				// tangential acceleration
				float newy = tangential.x;
				tangential.x = -tangential.y;
				tangential.y = newy;
				tangential = ccpMult(tangential, p->modeA.tangentialAccel);

				// (gravity + radial + tangential) * dt
				tmp = ccpAdd( ccpAdd( radial, tangential), modeA.gravity);
				tmp = ccpMult( tmp, dt);
				p->modeA.dir = ccpAdd( p->modeA.dir, tmp);
				tmp = ccpMult(p->modeA.dir, dt);
				p->pos = ccpAdd( p->pos, tmp );
			}

			// Mode B: radius movement
			else {				
				// Update the angle and radius of the particle.
				p->modeB.angle += p->modeB.degreesPerSecond * dt;
				p->modeB.radius += p->modeB.deltaRadius * dt;

				p->pos.x = - cosf(p->modeB.angle) * p->modeB.radius;
				p->pos.y = - sinf(p->modeB.angle) * p->modeB.radius;
			}

			// color
			p->color.r += (p->deltaColor.r * dt);
			p->color.g += (p->deltaColor.g * dt);
			p->color.b += (p->deltaColor.b * dt);
			p->color.a += (p->deltaColor.a * dt);

			// size
			p->size += (p->deltaSize * dt);
			p->size = MAX( 0, p->size );

			// angle
			p->rotation += (p->deltaRotation * dt);

			//
			// update values in quad
			//

			CGPoint	newPos;

			if( m_ePositionType == kCCPositionTypeFree || m_ePositionType == kCCPositionTypeRelative ) 
			{
				CGPoint diff = ccpSub( currentPosition, p->startPos );
				newPos = ccpSub(p->pos, diff);
			} 
			else
			{
				newPos = p->pos;
			}

			updateQuadWithParticle(p, newPos);
			//updateParticleImp(self, updateParticleSel, p, newPos);

			// update particle counter
			++m_nParticleIdx;

		} 
		else 
		{
			// life < 0
			if( m_nParticleIdx != m_nParticleCount-1 )
			{
				m_pParticles[m_nParticleIdx] = m_pParticles[m_nParticleCount-1];
			}
			--m_nParticleCount;

			if( m_nParticleCount == 0 && m_bIsAutoRemoveOnFinish )
			{
				this->unscheduleUpdate();
				m_pParent->removeChild(this, true);
				return;
			}
		}
	}

#if CC_ENABLE_PROFILERS
	/// @todo CCProfilingEndTimingBlock(_profilingTimer);
#endif

//#ifdef CC_USES_VBO
	this->postStep();
//#endif
}
Exemple #28
0
void CATabBar::showItems()
{
    do
    {
        CC_BREAK_IF(m_pViews.empty() == false);
        
        unsigned int count = MIN(m_nMaxShowCount, m_pItems.size());
        
        float width = m_obContentSize.width / count;
        float height = m_obContentSize.height;
        m_cItemSize = CCSize(width, height);
        
        for (unsigned int i=0; i<count; i++)
        {
            CAView* view = CAView::createWithFrame(CCRect(i * width, 0, width, height), ccc4(0, 0, 0, 0));
            this->insertSubview(view, 3);
            view->setDisplayRange(false);
            m_pViews.push_back(view);
            
            CAImageView* imageView = NULL;
            CCLabelTTF* title = NULL;
            
            if (m_pItems.at(i)->getImage())
            {
                imageView = CAImageView::createWithImage(m_pItems.at(i)->getImage());
                imageView->setTag(0xffff);
                view->addSubview(imageView);
            }
            
            
            if (m_pItems.at(i)->getTitle().compare("") != 0)
            {
                int fontSize = this->getContentSize().height / 5.0f;
                title = CCLabelTTF::create(m_pItems.at(i)->getTitle().c_str(), "Arial", fontSize);
                title->setTag(0xfffe);
                view->addSubview(title);
            }
            
            
            if (imageView && title == NULL)
            {
                CCSize imageViewSize = imageView->getBounds().size;
                float scaleX = width / imageViewSize.width * 2/3.0f;
                float scaleY = height / imageViewSize.height * 2/3.0f;
                float scale = MIN(scaleX, scaleY);
                scale = MIN(scale, 1.0f);
                imageViewSize = ccpMult(imageViewSize, scale);
                
                CCRect rect;
                rect.origin = view->getBounds().size/2;
                rect.size = imageViewSize;
                
                imageView->setCenter(rect);
    
            }
            else if (title && imageView == NULL)
            {
                int fontSize = this->getContentSize().height / 2.0f;
                title->setFontSize(fontSize);
                
                CCSize titleSize = title->getBounds().size;
                float titleScale = height / titleSize.height * 1/2.0f;
                titleSize = ccpMult(titleSize, titleScale);
                
                CCRect rect;
                rect.origin = view->getBounds().size/2;
                rect.size = titleSize;
                
                title->setCenter(rect);
            }
            else if (title && imageView)
            {

                CCSize imageViewSize = imageView->getBounds().size;
                float scaleX = width / imageViewSize.width * 1/2.0f;
                float scaleY = height / imageViewSize.height * 1/2.0f;
                float scale = MIN(scaleX, scaleY);
                scale = MIN(scale, 1.0f);
                imageViewSize = ccpMult(imageViewSize, scale);
 
                CCRect rect;
                rect.size = imageViewSize;
                rect.origin = view->getBounds().size;
                rect.origin.x *= 1/2.0f;
                rect.origin.y *= 7/20.0f;
                imageView->setCenter(rect);

                CCSize titleSize = title->getBounds().size;
                float titleScale = height / titleSize.height * 3/10;
                titleSize = ccpMult(titleSize, titleScale);
                
                CCRect rect2;
                rect2.size = titleSize;
                rect2.origin = view->getBounds().size;
                rect2.origin.x *= 1/2.0f;
                rect2.origin.y *= 15/20.0f;
                title->setCenter(rect2);
                
            }
        }
    }
    while (0);
}
void JoyStickLayer::update(float t)
{

    if(INSTANCE(FightManager)->enoughAnger()){
        skillBtn->setEnabled(true);
        skillPro->setPercentage(100);
    }else{
        skillBtn->setEnabled(false);
        skillPro->setPercentage(INSTANCE(FightManager)->getAnger() * 100);
    }
    
    if(INSTANCE(GuideManager)->getIsGuiding()){
        GuideStep step = INSTANCE(GuideManager)->getCurrentStep();
        if(step == GuideStep_10007){
            skillBtn->setEnabled(true);
        }
        
        if(step == GuideStep_10003 || step == GuideStep_10004 ||step == GuideStep_10006 || step == GuideStep_10007 || step == GuideStep_10003){
            if(!attackBtn->isEnabled()){
                attackBtn->setEnabled(true);
            }
        }else{
            if(attackBtn->isEnabled()){
                attackBtn->setEnabled(false);
            }
        }
    }else{
        if(!attackBtn->isEnabled()){
            attackBtn->setEnabled(true);
        }
        
    }
    
    
    if(attackBtn->isHighlighted()) {
        CCNotificationCenter::sharedNotificationCenter()->postNotification(JoyStick_status,CCStringMake(JoyStick_attack));
        return;
    }
    
    if(skillBtn->isHighlighted()){
        CCNotificationCenter::sharedNotificationCenter()->postNotification(JoyStick_status,CCStringMake(JoyStick_skill));
        return;
    }
    
    
    CCPoint poi = ccpMult(joystick->getVelocity(), 50);
    
    if(poi.x == 0 && poi.y == 0){
        if(lastPoi.x !=0 || lastPoi.y != 0){
            CCNotificationCenter::sharedNotificationCenter()->postNotification(JoyStick_status,CCStringMake(JoyStick_none));
            lastPoi = poi;
        }
        return;
    }
    
    lastPoi = poi;
    
    float degree = atan2(poi.y, poi.x)*180/atan2(0.0, -1.0);
    
    if(degree <0){
        degree += 360;
    }
    if(degree >= 22.5 && degree < 67.5){
        //右上
        CCNotificationCenter::sharedNotificationCenter()->postNotification(JoyStick_status,CCStringMake(JoyStick_right_up));
    }else if(degree >= 67.5 && degree < 112.5){
        //上
        CCNotificationCenter::sharedNotificationCenter()->postNotification(JoyStick_status,CCStringMake(JoyStick_up));
    }else if(degree >= 112.5 && degree < 157.5){
        //左上
        CCNotificationCenter::sharedNotificationCenter()->postNotification(JoyStick_status,CCStringMake(JoyStick_left_up));
    }else if(degree >= 157.5 && degree < 202.5){
        //左
        CCNotificationCenter::sharedNotificationCenter()->postNotification(JoyStick_status,CCStringMake(JoyStick_left));
    }else if(degree >= 202.5 && degree < 247.5){
        //左下
        CCNotificationCenter::sharedNotificationCenter()->postNotification(JoyStick_status,CCStringMake(JoyStick_left_down));
    }else if(degree >= 247.5 && degree < 292.5){
        //下
        CCNotificationCenter::sharedNotificationCenter()->postNotification(JoyStick_status,CCStringMake(JoyStick_down));
    }else if(degree >= 292.5 && degree < 337.5){
        //右下
        CCNotificationCenter::sharedNotificationCenter()->postNotification(JoyStick_status,CCStringMake(JoyStick_right_down));
    }else{
        //右
        CCNotificationCenter::sharedNotificationCenter()->postNotification(JoyStick_status,CCStringMake(JoyStick_right));
    }
}
Exemple #30
0
void CATableView::ccTouchEnded(CATouch *pTouch, CAEvent *pEvent)
{
    CAScrollView::ccTouchEnded(pTouch, pEvent);
    
    if (m_pHighlightedTableCells)
    {
        m_pContainer->stopAllActions();
        
        CAIndexPath2E deselectedIndexPath = CAIndexPath2EZero;
        CAIndexPath2E selectedIndexPath = CAIndexPath2E(m_pHighlightedTableCells->getSection(), m_pHighlightedTableCells->getRow());
        m_pHighlightedTableCells = NULL;
        
        if (m_pSelectedTableCells.count(selectedIndexPath) > 0 && m_bAllowsMultipleSelection)
        {
            deselectedIndexPath = selectedIndexPath;
            selectedIndexPath = CAIndexPath2EZero;
            m_pSelectedTableCells.erase(deselectedIndexPath);
        }
        else
        {
            if (!m_pSelectedTableCells.empty() && m_bAllowsMultipleSelection == false)
            {
                deselectedIndexPath = *m_pSelectedTableCells.begin();
                m_pSelectedTableCells.clear();
                
            }
            m_pSelectedTableCells.insert(selectedIndexPath);
            
        }

        if (deselectedIndexPath != CAIndexPath2EZero)
        {
            if (CATableViewCell* cell = m_pUsedTableCells[deselectedIndexPath])
            {
                cell->setControlStateNormal();
            }
            if (m_pTableViewDelegate)
            {
                m_pTableViewDelegate->tableViewDidDeselectRowAtIndexPath(this,
                                                                         deselectedIndexPath.section,
                                                                         deselectedIndexPath.row);
            }
        }
        
        if (selectedIndexPath != CAIndexPath2EZero)
        {
            if (CATableViewCell* cell = m_pUsedTableCells[selectedIndexPath])
            {
                cell->setControlStateSelected();
            }
            if (m_pTableViewDelegate)
            {
                m_pTableViewDelegate->tableViewDidSelectRowAtIndexPath(this,
                                                                       selectedIndexPath.section,
                                                                       selectedIndexPath.row);
            }
        }
    }
    
    if (m_pTableViewDelegate && m_nTablePullViewHeight > 0)
    {
        CCPoint point  = m_pContainer->getFrameOrigin();
        
        if (m_pTablePullDownView
            && point.y
            >= m_nTablePullViewHeight)
        {
            m_bToUpdate     =   CATableViewToUpdatePullDown;
            
            point.y         =   m_nTablePullViewHeight;
            
            this->setContentOffset(ccpMult(point, -1), true);
        }
        
        if (m_pTablePullUpView
            && point.y
            <= this->getBounds().size.height
                - m_pContainer->getFrame().size.height
                - m_nTablePullViewHeight)
        {
            m_bToUpdate     =   CATableViewToUpdatePullUp;
            
            point.y         =   this->getBounds().size.height
                                - m_pContainer->getFrame().size.height
                                - m_nTablePullViewHeight;
            
            this->setContentOffset(ccpMult(point, -1), true);
        }
    }
}