cocos2d::Vec2 Tower::convertFromTowerSceneToTowerLayer(Vec2 mLoc) { Vec2 lLoc = _towerLayer->getPosition(); float angle = CC_RADIANS_TO_DEGREES(lLoc.getAngle()); if(angle >= 0 && angle <= 90) { return (mLoc - lLoc); } else if(angle > 90 && angle <= 180) { return (mLoc+Vec2(abs(lLoc.x), -lLoc.y)); } else if(angle >= -180 && angle <= -270) { return (mLoc + lLoc); } else if (angle > -270 && angle < 0) { return (mLoc - lLoc); } return Vec2::ZERO; }
bool Bullet::init(Vec2 velocity) { Node::init(); scheduleUpdate(); mVelocity = velocity; auto bullet = Sprite::create("Bullet.png"); bullet->setAnchorPoint(Vec2::ANCHOR_MIDDLE); bullet->setName("Bullet"); float radian = atan2f(mVelocity.x, mVelocity.y); // ラジアンから度へ変換 float angle = CC_RADIANS_TO_DEGREES(radian); // 0 ~ 360度に限定 angle += 360; while (angle >= 360) { angle -= 360; } setRotation(angle); addChild(bullet); return true; }
bool Radar::init() { if ( !Node::init() ) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); auto bg = Sprite::create("radar_1.png"); this->addChild(bg); auto zeye = Director::getInstance()->getZEye(); auto eyeDegrees = CC_RADIANS_TO_DEGREES(atan2f(visibleSize.width*0.5, zeye)*2); log("eyeAngle = %f", eyeDegrees); auto eyeBg = ProgressTimer::create(Sprite::create("radar_2.png")); this->addChild(eyeBg); eyeBg->setType(ProgressTimer::Type::RADIAL); eyeBg->setMidpoint(Vec2(0.5f, 0.5f)); eyeBg->setPercentage(eyeDegrees/3.6); eyeBg->setRotation(-eyeDegrees*0.5); auto scanSp = Sprite::create("radar_3.png"); this->addChild(scanSp); scanSp->runAction(RepeatForever::create(RotateBy::create(2.0, 360))); pDrawNode = DrawNode::create(); this->addChild(pDrawNode); // dNode->drawSolidCircle(Vec2(0, 0), 100, CC_DEGREES_TO_RADIANS(90), 8, Color4F(1, 0, 0, 1)); return true; }
void OptionLayer::onTouchesBegan(const std::vector<Touch*>& touches, Event *event) { Size winSize = Director::getInstance()->getWinSize(); for (auto touch : touches){ Point position = touch->getLocation(); this->activeJoystick(this->getLocation()); auto distance = position.getDistance(this->getLocation()); auto deltaAngle = this->getLocation() - position; auto angle = CC_RADIANS_TO_DEGREES(deltaAngle.getAngle()); if (distance <= this->getRadius()) { if ((angle > -180 && angle < -135) || (angle > 135 && angle <= 180)) { this->delegator->onWalk(Direction::DIRECTION_RIGHT); }else if(angle >= -135 && angle <= -45) { this->delegator->onWalk(Direction::DIRECTION_UP); }else if(angle > -45 && angle <= 45) { this->delegator->onWalk(Direction::DIRECTION_LEFT); }else if(angle > 45 && angle <= 135) { this->delegator->onWalk(Direction::DIRECTION_DOWN); } } else { // right } } }
void Unit::shootWeapon(float attackRatio) { if(this->target != nullptr){ Sprite* weapon = Sprite::create(this->weaponName); Point unitPosition = this->getPosition(); Point destination = this->target->getPosition(); Point diff = destination-unitPosition; float angle = CC_RADIANS_TO_DEGREES(-1*diff.getAngle()); weapon->setRotation(angle); weapon->setPosition(this->getPosition()); this->gameLayer->map->addChild(weapon,100); float time = unitPosition.getDistance(destination)/this->attackSpeed; auto moveAction = MoveTo::create(time,destination); auto damageAction = CallFunc::create(CC_CALLBACK_0(Unit::damageEnermy, this)); auto removeAction = CallFuncN::create(CC_CALLBACK_1(Unit::removeWeapon, this)); auto actionSequence = Sequence::create(damageAction, moveAction,removeAction, NULL); weapon->runAction(actionSequence); } }
void OrbitCamera::startWithTarget(Node *target) { ActionCamera::startWithTarget(target); float r, zenith, azimuth; this->sphericalRadius(&r, &zenith, &azimuth); if( isnan(_radius) ) _radius = r; if( isnan(_angleZ) ) _angleZ = (float)CC_RADIANS_TO_DEGREES(zenith); if( isnan(_angleX) ) _angleX = (float)CC_RADIANS_TO_DEGREES(azimuth); _radZ = (float)CC_DEGREES_TO_RADIANS(_angleZ); _radX = (float)CC_DEGREES_TO_RADIANS(_angleX); }
void BaseMageTower::shoot(float dt) { auto instance = GameManager::getInstance(); checkNearestMonster(); if(nearestMonster!=NULL && nearestMonster->getCurrHp() > 0) { auto currBullet = MageTowerBullet(); SoundManager::playMageTowerShot(); Point shootVector = nearestMonster->baseSprite->getPosition() - this->getParent()->getPosition(); auto position=currBullet->getPosition()-shootVector; auto rotation=atan2(position.y,position.x); float angleDegrees = CC_RADIANS_TO_DEGREES(rotation); currBullet->setRotation(180.0f-angleDegrees); towerBase->runAction(Animate::create(AnimationCache::getInstance()->getAnimation(String::createWithFormat("level%d_mage_shine",level)->getCString()))); if(shootVector.y>0){ shooter->runAction(Animate::create(AnimationCache::getInstance()->getAnimation("mage_shoot_up"))); }else{ shooter->runAction(Animate::create(AnimationCache::getInstance()->getAnimation("mage_shoot_down"))); } auto actionMove=MoveTo::create(0.25f,shootVector); auto action=Spawn::create(actionMove,NULL); currBullet->setBulletAction(action); currBullet->shoot(); currBullet = NULL; } }
void Bird::update( float dt ) { const float limited = 3.0f; this->setPosition(_body->GetPosition().x * PTM_RATIO, _body->GetPosition().y * PTM_RATIO); b2Vec2 vel = _body->GetLinearVelocity(); if (_awake && vel.x < limited) _body->SetLinearVelocity(b2Vec2(limited + 1, 0)); limitVelocity(); CCLOG("Position: %f", this->getPositionX()); //CCLOG("Angle: %f | %f", vel.x, vel.y); b2Vec2 weightedVel = vel; const int NUM_PREV_VELS = 5; queue<b2Vec2> quue; for(int i = 0; i < _prevVels.size(); ++i) { weightedVel += _prevVels[i]; } weightedVel = b2Vec2(weightedVel.x/NUM_PREV_VELS, weightedVel.y/NUM_PREV_VELS); _prevVels.push_back(vel); if (_prevVels.size() >= NUM_PREV_VELS) _prevVels.clear(); vel = weightedVel; if (vel.x < 0) { vel.x = - vel.x; vel.y = - vel.y; } float angle = -1 * CC_RADIANS_TO_DEGREES(ccpToAngle(ccp(vel.x, vel.y))); angle = MIN(90, angle); angle = MAX(-90, angle); if (_awake) this->setRotation(angle); }
void MainLayer::ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent) { CCSetIterator it = pTouches->begin(); CCTouch* touch = (CCTouch*)(*it); CCPoint location = touch->locationInView( touch->view() ); CCPoint convertedLocation = CCDirector::sharedDirector()->convertToGL(location); CCNode* s = getChildByTag(kTagSprite); s->stopAllActions(); s->runAction( CCMoveTo::actionWithDuration(1, CCPointMake(convertedLocation.x, convertedLocation.y) ) ); float o = convertedLocation.x - s->getPosition().x; float a = convertedLocation.y - s->getPosition().y; float at = (float) CC_RADIANS_TO_DEGREES( atanf( o/a) ); if( a < 0 ) { if( o < 0 ) at = 180 + fabs(at); else at = 180 - fabs(at); } s->runAction( CCRotateTo::actionWithDuration(1, at) ); }
void PhySprite::update(float delta) { if (b2PhyBody) { this->setPosition(ccp(b2c(b2PhyBody->GetPosition().x), b2c(b2PhyBody->GetPosition().y))); this->setRotation(-1 * CC_RADIANS_TO_DEGREES(b2PhyBody->GetAngle())); } }
void LightTest::update( float delta ) { static float angleDelta = 0.0; if (_directionalLight) { _directionalLight->setRotation3D(Vec3(-45.0, -CC_RADIANS_TO_DEGREES(angleDelta), 0.0f)); } if (_pointLight) { _pointLight->setPositionX(100.0f * cosf(angleDelta + 2.0 * delta)); _pointLight->setPositionY(100.0f); _pointLight->setPositionZ(100.0f * sinf(angleDelta + 2.0 * delta)); } if (_spotLight) { _spotLight->setPositionX(100.0f * cosf(angleDelta + 4.0 * delta)); _spotLight->setPositionY(100.0f); _spotLight->setPositionZ(100.0f * sinf(angleDelta + 4.0 * delta)); _spotLight->setDirection(-Vec3(cosf(angleDelta + 4.0 * delta), 1.0, sinf(angleDelta + 4.0 * delta))); } angleDelta += delta; TestCase::update(delta); }
bool Flame::init(Item& item) { bool result; if (ItemModel::init(item)) { switch (_type) { case Flame_Blue: setTexture(IMAGE_FLAME_BLUE); break; case Flame_Orange: setTexture(IMAGE_FLAME_ORANGE); break; case Flame_Violet: setTexture(IMAGE_FLAME_VIOLET); break; case Flame_White: setTexture(IMAGE_FLAME_WHITE); break; default: return false; } setRotation(CC_RADIANS_TO_DEGREES(item.angle)); setScale(item.scale); result = true; }else{ result = false; } return result; }
float PhotoLayer::getRotateAngle(Point startPos1, Point startPos2, Point endPos1, Point endPos2){ float angle = 0.0f; //两个向量 Point *sp = new Point(startPos2.x - startPos1.x, startPos2.y - startPos1.y); Point *ep = new Point(endPos2.x - endPos1.x, endPos2.y - endPos1.y); // cos(A) = (x1 * x2 + y1 * y2) / (sqrt(x1 * x1 + y1 * y1) * sqrt(x2 * x2 + y2 * y2)) double n = sp->x * ep->x + sp->y * ep->y; double m = sqrt(sp->x * sp->x + sp->y * sp->y) * sqrt(ep->x * ep->x + ep->y * ep->y); double cosmn = n / m; if (m!=0 && (cosmn>=1.000001 || cosmn <= 0.999999)) { angle = CC_RADIANS_TO_DEGREES(acos(cosmn)); //log("n=%f,m=%f,n/m=%f,cos=%f,angle=%f",n,m,n/m,acos(cosmn),angle); } //sin(A) = (x1 * y2 - y1 * x2 ) / (sqrt(x1 * x1 + y1 * y1) * sqrt(x2 * x2 + y2 * y2)) //sin(A) 小于0 则顺时针, 大于0则逆时针 double n1 = sp->x * ep->y - sp->y * ep->x; if (m !=0 && n1/m > 0) { angle = -1 * angle; } //log("return angle=%f",angle); return angle; }
float MathUtils::angleFromVector(cocos2d::Point p0, cocos2d::Point p1) { cocos2d::Point direction = p1 - p0; float rad = CC_RADIANS_TO_DEGREES(-direction.getAngle()); return fmod(rad, 360.0f); // keep angle in the 360 range }
bool Stage01::onTouchBegan(Touch* touch, Event *event) { log("onTouchBegan-----------------------------"); auto location = touch->getLocation(); auto s = getChildByTag(1); mFootPrint = Sprite::create("footprint.png"); float spritex = (location.x + s->getPosition().x) / 2; float spritey = (location.y + s->getPosition().y) / 2; mFootPrint->setPosition(spritex, spritey); float dis = sqrt((s->getPositionX() - location.x)*(s->getPositionX() - location.x) + (s->getPositionY() - location.y)*(s->getPositionY() - location.y)); mFootPrint->setScale(dis / 50, 1.0); mFootPrint->setOpacity(100); //mFootPrint->setPosition(s->getPosition()); float o = location.x - s->getPosition().x; float a = location.y - s->getPosition().y; float at = (float) CC_RADIANS_TO_DEGREES( atanf( o/a) ); if( a < 0 ) { if( o < 0 ) at = 180 + fabs(at); else at = 180 - fabs(at); } //mFootPrint->runAction( RotateTo::create(0.0001, at + 90) ); mFootPrint->setRotation(at + 90); this->addChild(mFootPrint); return true; }
void LiquidFunScene::update(float dt) { static const int k_velocityIterations = 8; static const int k_positionIterations = 3; static const float k_stepTime = 1.0f/60.0f; // Instruct the world to perform a single step of simulation. It is // generally best to keep the time step and iterations fixed. m_world->Step(k_stepTime, k_velocityIterations, k_positionIterations); // Iterate over the bodies in the physics world and synchronize the position // of sprites with the bodies that have them present. // NOTE: This will break if a body's user data does *not* point to a sprite. for (b2Body* b = m_world->GetBodyList(); b; b = b->GetNext()) { if (b->GetUserData() != NULL) { // Synchronize the AtlasSprites position and rotation with the // corresponding body CCSprite* myActor = (CCSprite*)b->GetUserData(); myActor->setPosition(ConvertWorldToScreenPosition(b->GetPosition())); myActor->setRotation(-1 * CC_RADIANS_TO_DEGREES(b->GetAngle())); } } // Step the emitters and kill fields. for (FaucetEmitterList::iterator it = m_emitters.begin(); it != m_emitters.end(); ++it) { (*it)->Step(k_stepTime, b2_waterParticle | b2_colorMixingParticle); } for (ParticleKillFieldList::iterator it = m_killFields.begin(); it != m_killFields.end(); ++it) { (*it)->Step(); } }
void Stage01::onTouchEnded(Touch* touch, Event *event) { log("onTouchEnded"); Sprite* getObstacle = NULL; mFootPrint = NULL; auto location = touch->getLocation(); auto s = getChildByTag(1); float dis = sqrt((s->getPositionX() - location.x)*(s->getPositionX() - location.x) + (s->getPositionY() - location.y)*(s->getPositionY() - location.y)); float time = dis / 100; s->stopAllActions(); s->runAction( MoveTo::create(time, Point(location.x, location.y) ) ); float o = location.x - s->getPosition().x; float a = location.y - s->getPosition().y; float at = (float) CC_RADIANS_TO_DEGREES( atanf( o/a) ); if( a < 0 ) { if( o < 0 ) at = 180 + fabs(at); else at = 180 - fabs(at); } s->runAction( RotateTo::create(0.2, at) ); }
bool HelloWorld::init() { if ( !Layer::init() ) { return false; } initPhysics(); this->schedule([this](float){ for (b2Body* b = world->GetBodyList(); b; b = b->GetNext()) { float timeStep = 0.03f; int32 velocityIterations = 8; int32 positionIterations = 1; world->Step(timeStep, velocityIterations, positionIterations); if (b->GetUserData() != nullptr) { Sprite* sprite = (Sprite*)b->GetUserData(); sprite->setPosition( Vec2( b->GetPosition().x * PTM_RATIO, b->GetPosition().y * PTM_RATIO) ); sprite->setRotation( -1 * CC_RADIANS_TO_DEGREES(b->GetAngle()) ); } } },0.0f,"Update"); this->schedule([this](float){ addOneSprite(); },1.0f,"addSprite"); return true; }
void Missile::shoot(BaseMonster* monster,Point mechaPosition) { monsterToBeDrilled = monster; float startAngle = sprite->getRotation(); float endAngle = 0; if(monster->getHpBar()->getPercentage()<20.0f){ auto instance = GameManager::getInstance(); auto monsterVector = instance->monsterVector; for (int j = 0; j < monsterVector.size(); j++) { if(monster!=NULL && monsterVector.at(j)->getHpBar()->getPercentage()>20.0f && (monster->getAttackBySoldier()||monster->getAttackByTower())){ monster = monsterVector.at(j); break; } } } auto shootVector = monster->baseSprite->getPosition() - this->getParent()->getPosition() - mechaPosition; auto pVectr = this->getPosition()-shootVector; float angleRadians=atan(pVectr.y/pVectr.x); float angleDegrees = CC_RADIANS_TO_DEGREES(angleRadians); if(shootVector.x<0) angleDegrees = 180 + angleDegrees; sprite->setRotation(-angleDegrees); sprite->runAction(Sequence::create( MoveTo::create(1.0f,Point(shootVector)), CallFuncN::create(CC_CALLBACK_0(Missile::removeBullet, this,monster)) ,NULL)); }
void Bullet::update(float delta) { if (_target != nullptr) { if (!_target->isDead()) _targetPosition = _target->getPosition(); else _target = nullptr; } auto diff = _targetPosition - getPosition(); float reachRadius = 10 + _sprite->getContentSize().width / 2.f; if (diff.length() <= reachRadius) { if (_target != nullptr) { _target->deal(_damage); } removeFromParent(); } else { auto velocity = diff; velocity.normalize(); velocity = velocity * BULLET_MAX_VEL; // Adapt rotation auto angle = CC_RADIANS_TO_DEGREES(velocity.getAngle()); _sprite->setRotation(-angle); // Move the bullet setPosition(getPosition() + velocity * delta); } }
void HelloWorld::update(float dt) { float timeStep = 0.03f; int32 velocityIterations = 8; int32 positionIterations = 1; world->Step(timeStep, velocityIterations, positionIterations); for(b2Body*b = world->GetBodyList(); b; b= b->GetNext()) { //let line move with worm line->setPosition(Vec2(320, worm->getPositionY()+590)); //destroy birds passed by if (b->GetUserData()!= nullptr) { Sprite* sprite = (Sprite*) b->GetUserData(); sprite->setPosition(Vec2(b->GetPosition().x * PTM_RATIO, b->GetPosition().y * PTM_RATIO)); sprite->setRotation(-1* CC_RADIANS_TO_DEGREES(b->GetAngle())); } Sprite* s; if (b->GetPosition().x + 200 < 0 || b->GetPosition().x > 700) { s = (Sprite*)b->GetUserData(); if (s!=NULL) { s->removeFromParent(); } world->DestroyBody(b); log("%d", birdNumber); } } //reset moon status, when worm moves up, moon screams, when move down, moon laugh b2Vec2 vel = wormBody->GetLinearVelocity(); if (vel.y<=0 && isContact == false) { moon->setSpriteFrame("MoonLaugh.png"); moon_status = LAUGH; } else if (vel.y > 0 && isContact == false) { moon->setSpriteFrame("MoonScream.png"); moon_status = SCREAM; } }
bool GearButton::init(Item &item) { if (ItemModel::init(item)) { setTexture("GearButton_Pedestal.png"); _subject = Sprite::create("GearButton_Subject.png"); _subject->setPosition(getBoundingBox().size.width/2,getBoundingBox().size.height/2); addChild(_subject,-1); _lamp = Sprite::create("GearButton_BlueLamp.png"); _lamp->setPosition(getBoundingBox().size.width/2,getBoundingBox().size.height/2); _subject->addChild(_lamp); // setRotation(CC_RADIANS_TO_DEGREES(item.angle)); setScale(item.scale); bindID = kDefaultGearButtonBindID; sinkSpeed = kDefaultGearButtonSinkSpeed; if(item.features){ bindID = ((Features_GearButton*)item.features)->bindID; sinkSpeed = ((Features_GearButton*)item.features)->sinkSpeed; } createCollisionAnimation(); return true; } return false; }
void Box2DTestLayer::tick(ccTime dt) { //It is recommended that a fixed time step is used with Box2D for stability //of the simulation, however, we are using a variable time step here. //You need to make an informed choice, the following URL is useful //http://gafferongames.com/game-physics/fix-your-timestep/ int velocityIterations = 8; int positionIterations = 1; // Instruct the world to perform a single step of simulation. It is // generally best to keep the time step and iterations fixed. world->Step(dt, velocityIterations, positionIterations); //Iterate over the bodies in the physics world for (b2Body* b = world->GetBodyList(); b; b = b->GetNext()) { if (b->GetUserData() != NULL) { //Synchronize the AtlasSprites position and rotation with the corresponding body CCSprite* myActor = (CCSprite*)b->GetUserData(); myActor->setPosition( CCPointMake( b->GetPosition().x * PTM_RATIO, b->GetPosition().y * PTM_RATIO) ); myActor->setRotation( -1 * CC_RADIANS_TO_DEGREES(b->GetAngle()) ); } } }
void HelloWorld::tick(float t) { // 물리적 위치를 이영해 그래픽 위치를 갱신한다. // velocityIterations : body들을 정상적으로 이동시키기 위해 필요한 충돌들을 반복적으로 계산 // positionIterations ; 조인트 분리와 겹침 현상을 줄이기 위해 바디의 위치를 반복적으로 적용 // 값이 클수록 정확한 연산이 가능하지만 성능이 떨어진다 // 프로젝트 생성 시 기본값 int velocityIterations = 8; int positionIterations = 3; // Step : 물리 세계를 시뮬레이션한다 _world->Step(t, velocityIterations, positionIterations); // 모든 물리 객체들은 linkedList에 저장되어 참조해 볼 수 있게 구현돼 있다. // 만들어진 객체 만큼 루프를 돌리면서 바다에 붙인 스프라이트를 여기서 제어한다. for (b2Body *b = _world->GetBodyList(); b; b = b->GetNext()) { if (b->GetUserData() != NULL) { Sprite* spriteData = (Sprite*)b->GetUserData(); spriteData->setPosition(Vec2(b->GetPosition().x * PTM_RATIO, b->GetPosition().y * PTM_RATIO)); spriteData->setRotation(-1 * CC_RADIANS_TO_DEGREES(b->GetAngle())); } } }
void BlockHouse::setTarget(cocos2d::Vec2 target) { this->target = target; float angle = target.getAngle(); angle = -CC_RADIANS_TO_DEGREES(angle); this->setRotation(angle); }
void Bullet::flyTo(CCPoint targetInWorldSpace) { //子弹开始起飞点 CCPoint startInNodeSpace = CCPointZero; //把节点坐标转换到屏幕坐标中 CCPoint startInWorldSpace = this->getParent()->convertToWorldSpace(startInNodeSpace); CCPoint targetInNodeSpace = this->getParent()->convertToNodeSpace(targetInWorldSpace); //coordinate n. 坐标; radian,n. [数] 弧度;rotation ,n. 旋转. float angle = ccpAngleSigned(ccpSub(targetInWorldSpace,startInWorldSpace),CCPointMake(0,1)); this->setRotation(CC_RADIANS_TO_DEGREES(angle)); //设置旋转角度 this->setPosition(startInNodeSpace);//确定子弹初始位置 this->setVisible(true);//让子弹可见 float speed = ccpDistance(startInNodeSpace,targetInNodeSpace)/300.0f; CCMoveTo* moveTo = CCMoveTo::create(speed,targetInNodeSpace); //以speed速度沿着任务路径飞行 //callfunc_selector创建一个回调函数【**回调函数只需要有一个函数名即可,不需要括号】 CCCallFunc* callFunc = CCCallFunc::create(this,callfunc_selector(Bullet::end)); CCFiniteTimeAction* seq = CCSequence::create(moveTo, callFunc, NULL); //子弹飞行持续一个有限的时间 seq->setTag(k_Bullet_Action); //设置子弹状态 this->runAction(seq);// 子弹飞起来 }
///@brief 根据位置,获取角度值 ///@param[in/out] ///@return ///@author DionysosLai,[email protected] ///@retval ///@post ///@version 1.0 ///@data 2014-7-18 16:27 float getAngle( const cocos2d::CCPoint& posBegin, const cocos2d::CCPoint& posCen ) { CCPoint deltaPoint = posBegin - posCen; float angleRadians = atanf(deltaPoint.y / deltaPoint.x); float angleDegrees = CC_RADIANS_TO_DEGREES(angleRadians); float cocosAngle = angleDegrees; if (deltaPoint.x >= 0 && deltaPoint.y >= 0) ///< 第一象限 { cocosAngle = cocosAngle; } if (deltaPoint.x < 0 && deltaPoint.y >= 0) ///< 第二象限 { cocosAngle = 180.f + cocosAngle; } if (deltaPoint.x < 0 && deltaPoint.y < 0) ///< 第三象限 { cocosAngle = 180.f + cocosAngle; } if (deltaPoint.x >= 0 && deltaPoint.y < 0) ///< 第四象限 { cocosAngle = 360.f + cocosAngle; } // CCLOG("%f", cocosAngle); return cocosAngle; }
void Bullet::flyTo(cocos2d::Vec2 targetInWorldSpace) { this->setVisible(true); //设置方向 Vec2 startInNodeSpace = Vec2::ZERO; Vec2 startInWorldSpace = this->getParent()->convertToWorldSpace(startInNodeSpace); Vec2 targetInNodeSpace = this->getParent()->convertToNodeSpace(targetInWorldSpace); Vec2 normal = targetInWorldSpace-startInWorldSpace; float angle = normal.getNormalized().getAngle(Vec2(0,1)); this->setRotation(CC_RADIANS_TO_DEGREES(angle)); this->setPosition(startInNodeSpace); this->setVisible(true); float speed = STATIC_DATA_FLOAT(GameConfig::BULLET_SPEED_NORMAL); float duration = startInNodeSpace.getDistance(targetInNodeSpace)/speed; MoveTo * pMove = MoveTo::create(duration,targetInNodeSpace); FiniteTimeAction * pSeq = Sequence::create(pMove,CallFunc::create(CC_CALLBACK_0(Bullet::end,this)),nullptr); pSeq->setTag(BULLET_ANCTION::k_Action_1); this->runAction(pSeq); }
void b2Sprite::update(float dt){ if (_body && isVisible()) { setPositionX(_body->GetPosition().x * PTM_RATIO); setPositionY(_body->GetPosition().y * PTM_RATIO); setRotation(CC_RADIANS_TO_DEGREES(-1 * _body->GetAngle())); } }
void Box2dUtil::updateBox2dWorldInLevelHelp(b2World *b2World, LevelHelperLoader *levelHelp, float dt) { static double UPDATE_INTERVAL = 1.0f/60.0f; static double MAX_CYCLES_PER_FRAME = 5; static double timeAccumulator = 0; timeAccumulator += dt; if (timeAccumulator > (MAX_CYCLES_PER_FRAME * UPDATE_INTERVAL)) { timeAccumulator = UPDATE_INTERVAL; } int velocityIterations = 1; int positionIterations = 1; while (timeAccumulator >= UPDATE_INTERVAL) { timeAccumulator -= UPDATE_INTERVAL; b2World->Step(UPDATE_INTERVAL, velocityIterations, positionIterations); for (b2Body* body = b2World->GetBodyList(); body; body = body->GetNext()) { if (body->GetUserData() != NULL) { CCSprite* sprite = (CCSprite*) body->GetUserData(); sprite->setPosition(levelHelp->metersToPoints(body->GetPosition())); sprite->setRotation( -1 * CC_RADIANS_TO_DEGREES(body->GetAngle())); } } } }