void CommonFunction::VectorTruncate(CCPoint &v,float maxLen) { if (v.getLengthSq()>maxLen*maxLen) { v=v.normalize()*maxLen; } }
bool RigSegmentCollides(const Rig& targetRig, const CCPoint& newVertex, const CCPoint& oldVertex) { if(targetRig.size() < 3) { return false; } for(int v = 0; v < targetRig.size(); v++) { CCPoint edgeStart = targetRig[v]; CCPoint edgeEnd = targetRig[ (v+1) % targetRig.size() ]; if(edgeStart.equals(oldVertex) || edgeEnd.equals(oldVertex)) { continue; } if(ccpSegmentIntersect(edgeStart, edgeEnd, newVertex, oldVertex)) { return true; } } return false; }
static void projectRange(const CCPoint& axis,const Range& range,float* min,float* max) { float project=axis.dot(range.tl); *min=project; *max=project; project=axis.dot(range.tr); if (project<(*min)) { *min=project; }else if(project>(*max)){ *max=project; } project=axis.dot(range.br); if (project<(*min)) { *min=project; }else if(project>(*max)){ *max=project; } project=axis.dot(range.bl); if (project<(*min)) { *min=project; }else if(project>(*max)){ *max=project; } }
//For pathfinding, the difference from the Red is that it calculate the next step of the player and predict his movement void BluEnemy::CalculatePath() { GameLevelMap* pLevelMap = PathPlanner::GetInstance()->GetLevelMap(); //Get the source and destination Points CCPoint sourceTileCoords = pLevelMap->tileCoordForPosition(mEntitySprite->getPosition()); CCPoint destTileCoords = pLevelMap->tileCoordForPosition(PathPlanner::GetInstance()->GetPlayerPosition()); /*** Predict the player movement, calculate the destination target using the player direction */ CCPoint tmpDestTileCoords = ccp(destTileCoords.x + PathPlanner::GetInstance()->GetPlayerDirection().x, destTileCoords.y - PathPlanner::GetInstance()->GetPlayerDirection().y); if(pLevelMap->isValidAndNotWallTile(tmpDestTileCoords)) { //if the next position of the player is valid, set as destination destTileCoords = tmpDestTileCoords; } this->mShortestPath = NULL; //check that there is a path if(sourceTileCoords.equals(destTileCoords)) return; //check if the touch is in a wall if(PathPlanner::GetInstance()->GetLevelMap()->IsWallAtTileCoords(destTileCoords)) return; mShortestPathArray = PathPlanner::GetInstance()->Start_A_Star(sourceTileCoords, destTileCoords); }
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); CCDirector::sharedDirector()->getScheduler()->unscheduleSelector(schedule_selector(CAScrollView::closeToPoint), this); m_tCloseToPoint = CCPoint(-1, -1); } else { resilience.x /= size.width; resilience.y /= size.height; resilience = ccpMult(resilience, maxBouncesSpeed(delay)); resilience = ccpAdd(resilience, point); m_pContainer->setFrameOrigin(resilience); } }
void T27ActionMore::ccTouchEnded(CCTouch* t, CCEvent*) { CCPoint ptStart = t->getStartLocation(); CCPoint ptEnd = t->getLocation(); if (ptStart.getDistanceSq(ptEnd) <= 25) { // click // 点中了哪个子窗口 // 转换ptStart为ScrollView中的Container的坐标 // 再判断被点击的LayerColor CCPoint ptInContainer = _c->convertToNodeSpace(ptStart); CCArray* arr = _c->getChildren(); // 所有的layercolor for (int i = 0; i < sizeof(_actionName) / sizeof(*_actionName); i++) { CCLayerColor* layer = (CCLayerColor*)arr->objectAtIndex(i); if (layer->boundingBox().containsPoint(ptInContainer)) { testAction(i, layer); break; } } } }
void Arrow::updateMove2(float fDeltaTime) { m_fSpeed -= ACCELERATION_2 * (fDeltaTime / FRAME_DURATION); if (m_fSpeed < MIN_SPEED) { // Sets acceleration m_fAcceleration = ACCELERATION_3; // Updates move setCurrentState(Move); } else { CCPoint deltaPos = m_dir * m_fSpeed * fDeltaTime; float fLength = deltaPos.getLength(); if (fLength < m_fRemainLength) { m_fRemainLength -= fLength; setPosition(m_obPosition + deltaPos); } else { m_fRemainLength = 0.0f; setPosition(m_endPos); // Disappear disappear(); } } }
void CGridView::onDraggingScrollEnded() { if( m_uCellsCount == 0 ) return; if( m_bAutoRelocate ) { CCPoint tOffset = getContentOffset(); unsigned int uRow = cellBeginRowFromOffset(tOffset); CCPoint tAPoint = cellPositionFromIndex(cellFirstIndexFromRow(uRow)); CCPoint tBPoint = CCPoint(0, tAPoint.y - m_tCellsSize.height); CCPoint tContentPoint = CCPoint(0, m_obContentSize.height); tOffset = tOffset - tContentPoint; tAPoint.x = 0; float fADistance = tOffset.getDistance(-tAPoint); float fBDistance = tOffset.getDistance(-tBPoint); if( fADistance < fBDistance ) { float fDuration = fabs(fADistance) / CGRIDVIEW_AUTO_RELOCATE_SPPED; setContentOffsetInDuration(-tAPoint + tContentPoint, fDuration); } else { float fDuration = fabs(fBDistance) / CGRIDVIEW_AUTO_RELOCATE_SPPED; setContentOffsetInDuration(-tBPoint + tContentPoint, fDuration); } } }
void CCCurl::startWithTarget(CCNode* pTarget) { CCActionInterval::startWithTarget(pTarget); // get start radius CCPoint v = ccpSub(pTarget->getPosition(), m_center); m_fromRadius = ccpLength(v); m_initAngle = v.getAngle(); }
/* @brief 設定した座標に向かって移動 */ void MyShipInterface::movePosition( const CCPoint& in_rPos ) { MyShipObj* pObj = (MyShipObj*)getChildByTag( eTAG_CHILD_OBJ ); CCPoint pos = pObj->getPosition(); CCPoint vec = in_rPos - pos; moveDirection( vec.normalize() ); }
void Player::HandleKeyboardInput() { CCPoint playerOffset = CCPointZero; // FIXME: WIN32 specific, no multiplatform keyboard support // Vertical moving if ((0x80 & GetKeyState('W')) || (0x80 & GetKeyState(VK_UP))) { playerOffset.y += m_MoveStep; } else if ((0x80 & GetKeyState('S')) || (0x80 & GetKeyState(VK_DOWN))) { playerOffset.y -= m_MoveStep; } // Horizontal moving if ((0x80 & GetKeyState('A')) || (0x80 & GetKeyState(VK_LEFT))) { playerOffset.x -= m_MoveStep; } else if ((0x80 & GetKeyState('D')) || (0x80 & GetKeyState(VK_RIGHT))) { playerOffset.x += m_MoveStep; } // Fire if ((0x80 & GetKeyState(VK_LBUTTON)) || (0x80 & GetKeyState(VK_RCONTROL))) { g_Map->ShootGround((CCPoint *)NULL); } // early exit? if (0 == playerOffset.getLengthSq()) { // no moving at all return; } const CCPoint newPlayerPos = ccpAdd(getPosition(), playerOffset); const CCSize mapSize = g_Map->getContentSize(); // Keep player in map (horizontal border) if ((fabsf(newPlayerPos.x) < (0.5f * mapSize.width))) { setPositionX(newPlayerPos.x); } // Keep player in map (vertical border) if ((fabsf(newPlayerPos.y) < (0.5f * mapSize.height))) { setPositionY(newPlayerPos.y); } g_Map->OnPlayerMoved(); }
// 衝突更新 void MyShipInterface::_updateCollision( const CCPoint& in_rVec ) { MyShipObj* pObj = (MyShipObj*)getChildByTag( eTAG_CHILD_OBJ ); CCPoint pos = pObj->getPosition(); // 画面範囲内に収まるように補正する。 CrollCollision2DLine::SEGMENT seg1; { // 線分との交差判定でチェック seg1.x = pos.x; seg1.y = pos.y; seg1.vecX = in_rVec.x; seg1.vecY = in_rVec.y; } // 画面4点の交差チェック { CCSize objSize = pObj->getSize(); CCPoint crossPos = CCPointZero; CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin(); CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize(); static CrollCollision2DLine::SEGMENT upperLine(origin.x, origin.y + objSize.height, visibleSize.width, 0); static CrollCollision2DLine::SEGMENT underLine(origin.x, origin.y + visibleSize.height - objSize.height, visibleSize.width, 0); static CrollCollision2DLine::SEGMENT leftLine(origin.x + objSize.width, origin.y, 0, visibleSize.height); static CrollCollision2DLine::SEGMENT rightLine(origin.x + visibleSize.width - objSize.width, origin.y, 0, visibleSize.height); // X軸方向の衝突処理 if( in_rVec.x < 0 ) { CrollCollision2DLine::Check(seg1, leftLine, &crossPos.x, &crossPos.y); } else if( 0 < in_rVec.x ) { CrollCollision2DLine::Check(seg1, rightLine, &crossPos.x, &crossPos.y); } // Y軸方向の衝突処理 if( in_rVec.y < 0 ) { CrollCollision2DLine::Check(seg1, upperLine, &crossPos.x, &crossPos.y); } else if( 0 < in_rVec.y ) { CrollCollision2DLine::Check(seg1, underLine, &crossPos.x, &crossPos.y); } // 交差位置に設定 if( crossPos.equals(CCPointZero) == false ) { pos = crossPos; } else { pos = pos + in_rVec; } pObj->setPosition(pos); } }
//-------------------------------------------------------------------- void FKCW_Action_Curl::startWithTarget(CCNode* pTarget) { CCActionInterval::startWithTarget(pTarget); // 获取起始半径和角度 CCPoint v = ccpSub(pTarget->getPosition(), m_center); m_fromRadius = ccpLength(v); m_initAngle = v.getAngle(); }
void CCPointArray::replaceControlPoint(cocos2d::CCPoint &controlPoint, unsigned int index) { // should create a new object: CCPoint // because developers are accustomed to using // replaceControlPoint(ccp(x, y)) // which assumes controlPoint is a temporary struct // but CCArray::insertObject() will retain the passed object, so temp // should be an object created in the heap. CCPoint *temp = new CCPoint(controlPoint.x, controlPoint.y); m_pControlPoints->replaceObjectAtIndex(index, temp); temp->release(); }
void CCPointArray::addControlPoint(CCPoint controlPoint) { // should create a new object: CCPoint // because developers are accustomed to using // addControlPoint(ccp(x, y)) // which assumes controlPoint is a temporary struct // but CCArray::addObject() will retain the passed object, so temp // should be an object created in the heap. CCPoint *temp = new CCPoint(controlPoint.x, controlPoint.y); m_pControlPoints->addObject(temp); temp->release(); }
bool NDUIButton::processDragEnd( const CCPoint& kPrePos,const CCPoint& kEndPos ) { if (!NDUINode::processDragEnd(kPrePos,kEndPos)) { return false; } m_bIsDragingNow = false; CCPoint kPoint = ccp(kEndPos.x - kPrePos.x,kEndPos.y - kPrePos.y); CCSize kSize = CCDirector::sharedDirector()->getWinSize(); CCPoint kVector = ccp(kSize.width,kSize.height); float fDragDistance = kVector.getDistance() * 0.08f; float fDistance = kPoint.getDistance(); float fAngle = 0.0f; if (fDistance < fDragDistance) { return false; } kPoint = ccpNormalize(kPoint); fAngle = ccpToAngle(kPoint); float fLeftUp = ccpToAngle(ccp(-1.0f,-1.0f)); float fRightUp = ccpToAngle(ccp(1.0f,-1.0f)); float fRightBottom = ccpToAngle(ccp(1.0f,1.0f)); float fLeftBottom = ccpToAngle(ccp(-1.0f,1.0f)); TARGET_EVENT eDirEvent = TE_NONE; if (fAngle >= fLeftUp && fAngle < fRightUp) { eDirEvent = TE_TOUCH_BTN_DRAG_UP; } else if (fAngle >= fRightUp && fAngle < fRightBottom) { eDirEvent = TE_TOUCH_BTN_DRAG_RIGHT; } else if (fAngle >= fRightBottom && fAngle < fLeftBottom) { eDirEvent = TE_TOUCH_BTN_DRAG_DOWN; } else { eDirEvent = TE_TOUCH_BTN_DRAG_LEFT; } OnScriptUiEvent( eDirEvent ); OnScriptUiEvent(TE_TOUCH_BTN_END); }
void HSPlayCard::draw() { // Draw components. CCNodeRGBA::draw(); // Update image. CCSprite *img = (CCSprite *) getChildByTag(TAG_USERIMG); if (img) { int rotation = (int) this->getRotationY() % 360; img->setVisible(0 < rotation && rotation < 180); } // Update view. if (m_isUpdated) { CCLabelTTF *text = (CCLabelTTF *) getChildByTag(TAG_MSG); if (text) { text->setString(m_model->getMessage()); } CCSprite *img = (CCSprite *) getChildByTag(TAG_USERIMG); if (!img) { img = HS_CREATE_SPRITE(m_model->getImageFilePath().c_str()); img->setTag(TAG_USERIMG); CCSize texSize = img->getContentSize(); float size = fminf(texSize.width, texSize.height); CCPoint offset = CCPointZero; if (texSize.width / texSize.height > 1.0f) { offset.setPoint((texSize.width - size) * 0.5f, 0.0f); } else { offset.setPoint(0.0f, (texSize.height - size) * 0.5f); } img->setTextureRect(CCRectMake(offset.x, offset.y, size, size)); CCSprite *frame = (CCSprite *) getChildByTag(TAG_FRAME); if (frame) { img->setScale(frame->getContentSize().width / size); } else { img->setScale(100.0f / size); } img->setVisible(false); img->setRotationY(180); this->addChild(img); } m_isUpdated = false; } }
static bool checkEdge(const CCPoint& edgePointA,const CCPoint& edgePointB,const Range& one,const Range& other) { //check top CCPoint edge = ccp(edgePointB.x-edgePointA.x,edgePointB.y-edgePointA.y); CCPoint prep=edge.getPerp(); float selfMin=0,selfMax=0,otherMin=0,otherMax=0; projectRange(prep, one, &selfMin, &selfMax); projectRange(prep, other, &otherMin, &otherMax); return isOverlap(selfMin,selfMax,otherMin,otherMax); }
void MainroleAttack::execute(Mainrole* stateOwner, double dt) { if(!stateOwner->getTargetSprite() || stateOwner->getTargetSprite()->getDead()) { // 如果敌人已经死亡 return stateOwner->getStateMachine()->changeState(MainroleStand::instance()); } stateOwner->detectEnemyOval(stateOwner->getTargetSprite()); // 检测敌人是否在攻击范围 if(stateOwner->getIsRoleInAttack()) { // 如果敌人还在攻击范围 CCPoint toTarget = stateOwner->getTargetSprite()->getPosition() - stateOwner->getPosition(); stateOwner->setDirect(stateOwner->getClosestDirect(toTarget.normalize())); stateOwner->runActionFight(dt); } else { // 如果敌人不在攻击范围 return stateOwner->getStateMachine()->changeState(MainrolePursuit::instance()); } }
void Number_Chat_inGame7u::runAction(float dt) { int dem0 = 0; int dem1 = 0; int dem2 = 0; int dem3 = 0; int dem4 = 0; int dem5 = 0; int dem6 = 0; for (int i = 0; i < arrPos.size(); i++) { int pos = arrPos.at(i); string numberString = arrNumberString.at(i); Number *number = new Number(numberString); number->setScale(0.6); CCPoint point; switch (pos) { case kuser0: point.setPoint(WIDTH_DESIGN/2-number->getSize().width/2+60,80); dem0++; break; case kuser1: point.setPoint(10,130); dem1++; break; case kuser2: point.setPoint(10, 280); dem2++; break; case kuser3: point.setPoint(210, 360); dem3++; break; case kuser4: point.setPoint(450, 360); dem4++; break; case kuser5: point.setPoint(650, 280); dem5++; break; case kuser6: point.setPoint(650,110); dem6++; break; } number->setPositionStart(point); this->addChild(number); } arrPos.clear(); arrNumberString.clear(); this->isRunning = false; //this->scheduleOnce(schedule_selector(LayerNumberInGame::callbackShowNumber), 3); }
bool PopStar::isInitFinish() { Star* star = stars[ROW_NUM-1][COL_NUM-1]; if (star) { CCPoint pos = star->getPosition(); CCPoint destPos = star->getDestPos(); if ( pos.equals(destPos) ) { return true; } } return false; }
bool Common::Screen2Plate(const CCPoint& ptSceen, int& row, int& col) { // 遍历所有象棋坐标点,计算棋盘格子中心坐标点到点击的店的距离,如果小于半径,那么就对了 int distance = Stone::_d*Stone::_d / 4; for (row = 0; row <= 9; ++row) for (col = 0; col <= 8; ++col) { CCPoint ptCenter = Plate2Screen(row, col); if (ptCenter.getDistanceSq(ptSceen) < distance) { return true; } } return false; }
void HelloWorld::enemyAnimate() { //Set the Enemy move postion to current Enemy Y and Player X CCPoint enemyPosition = ccp(_player->getPositionX(),_enemy->getPositionY()); //If the new Enemy position is outside the visible width of the screen //Set the position to max left or max right if (enemyPosition.x + _enemy->getContentSize().width/2 * _enemy->getScaleX() > _winWidth) { enemyPosition.setPoint(_winWidth - _enemy->getScaleX() * _enemy->getContentSize().width/2,enemyPosition.y); } else if (enemyPosition.x - _enemy->getContentSize().width/2 * _enemy->getScaleX() < _origin.x) { enemyPosition.setPoint(_origin.x + _enemy->getScaleX() * _enemy->getContentSize().width/2,enemyPosition.y); } _enemy->runAction(CCSequence::create(CCMoveTo::create(0.4f,enemyPosition),CCCallFuncN::create(this,callfuncN_selector(HelloWorld::enemyMoveFinished)),NULL)); //Shooting Delay float delay = 1.0f; //Distance between the Enemy laser projectiles relative to the Enemy sprite width float widthAdjustment = 4.0f; //Launch four projectiles with two sets of delays and X-coordinates based on the Enemy Spaceship width for (int i = 0; i < 2; ++i) { _enemyProjectiles[_enemyProjectileCount]->stopAllActions(); _enemyProjectiles[_enemyProjectileCount]->setPosition(ccp(_enemy->getPositionX()-_enemy->getScaleX()*_enemy->getContentSize().width/widthAdjustment,_enemy->getPositionY())); _enemyProjectiles[_enemyProjectileCount]->setVisible(true); _enemyProjectiles[_enemyProjectileCount]->runAction(CCSequence::create(CCMoveTo::create(delay, ccp(_enemy->getPositionX()-_enemy->getScaleX()*_enemy->getContentSize().width/widthAdjustment,_winHeight)),CCCallFuncN::create(this,callfuncN_selector(HelloWorld::spriteMoveFinished)),NULL)); ++_enemyProjectileCount; _enemyProjectiles[_enemyProjectileCount]->stopAllActions(); _enemyProjectiles[_enemyProjectileCount]->setPosition(ccp(_enemy->getPositionX()+_enemy->getScaleX()*_enemy->getContentSize().width/widthAdjustment,_enemy->getPositionY())); _enemyProjectiles[_enemyProjectileCount]->setVisible(true); _enemyProjectiles[_enemyProjectileCount]->runAction(CCSequence::create(CCMoveTo::create(delay, ccp(_enemy->getPositionX()+_enemy->getScaleX()*_enemy->getContentSize().width/widthAdjustment,_winHeight)),CCCallFuncN::create(this,callfuncN_selector(HelloWorld::spriteMoveFinished)),NULL)); ++_enemyProjectileCount; //For next two projectiles //Double the delay to make inner lasers moving slower delay += 0.5f; //Make the width closer to the center of the Enemy spaceship widthAdjustment *= 3.0f; } //If reached the maximum number of sprites reset the the count to recycle the sprites if (_enemyProjectileCount>=MAX_ENEMY_PROJECTILES) { _enemyProjectileCount = 0; } }
bool AnimatedRain::CreatePath(CCPoint from, CCPoint to) { if (from.equals(to)) { isMoving = false; return false; } PathFinder *p = new PathFinder(); p->setDestination(to); p->setSource(from); if (path != NULL) { if (path->count() > 0) { path->removeAllObjects(); path->release(); path = NULL; } } path = p->makeRainPath(&from, &to); path->retain(); delete p; return true; }
float LotteryRotateView::getAngleByTouchPoint(CCPoint touchPoint){ CCPoint zeroPoint = ccp(0,0); float angleA = touchPoint.getAngle(zeroPoint); angleA = (angleA/M_PI) * 180; return angleA; }
直线与线段是否相交.cpp ///@brief 判断线段与直线是否相交 /// /// ///@param[in] p0,p1--线段两个端点, q0,q1--直线两个点值 ///@pre ///@return true---在线段上, false---不在线段上 ///@retval ///@post bool LineMenu::straightLineIsIntersect(const CCPoint p0, const CCPoint p1, const CCPoint q0, const CCPoint q1) { /// 先判断q0与q1能否组成一条直线 if (!q0.equals(q1)) { /// 当q0 == p0 q1 == p1时,结果为0。 只需要判断线段是否跨立直线即可。 if (0 <= determinant(p0.x-q0.x, p0.y-q0.y, q1.x-q0.x, q1.y-q0.y) * determinant(q1.x-q0.x, q1.y-q0.y, p1.x-q0.x, p1.y-q0.y)) { CCLOG("straight line and segment line is intesect!"); return false; } CCLOG("straight line and segment line isn't intesect!"); return false; } CCLOG("straigth line cannnot be make up of q0 and q1!"); return false; }
void SpellDiagramNode::ccTouchesEnded(CCSet* touches, CCEvent* event) { float slotRadius = 25.0f; for(CCSetIterator it = touches->begin(); it != touches->end(); it++) { CCTouch* touch = dynamic_cast<CCTouch*>(*it); if(touch == NULL) break; if( m_slotEquipMenu == NULL ) { CCPoint p = touch->getLocation(); p.x -= getPositionX(); p.y -= getPositionY(); for(int i=0; i< m_effectSlots.size(); i++) { CCPoint sp = m_effectSlots[i]->getPosition(); if( p.getDistance(sp) <= slotRadius ) { CCLog("touched effect %d", i); m_slotEquipMenu = RadialLayer::create(); createEffSlotMenu(m_slotEquipMenu, sp, i); return; } } for(int i=0; i< m_modSlots.size(); i++) { CCPoint sp = m_modSlots[i]->getPosition(); if( p.getDistance(sp) <= slotRadius ) { CCLog("touched mod %d", i); m_slotEquipMenu = RadialLayer::create(); createModSlotMenu(m_slotEquipMenu, sp, i); return; } } } } }
void CCLens3D::setPosition(const CCPoint& pos) { if( !pos.equals(m_position)) { m_position = pos; m_bDirty = true; } }
float CCPoint::getAngle(const CCPoint& other) const { CCPoint a2 = normalize(); CCPoint b2 = other.normalize(); float angle = atan2f(a2.cross(b2), a2.dot(b2)); if( fabs(angle) < __FLT_EPSILON__ ) return 0.f; return angle; }
void CCNode::setAnchorPoint(const CCPoint& point) { if( ! point.equals(m_obAnchorPoint)) { m_obAnchorPoint = point; m_obAnchorPointInPoints = ccp(m_obContentSize.width * m_obAnchorPoint.x, m_obContentSize.height * m_obAnchorPoint.y ); } }