Esempio n. 1
0
void PlaneProtect::ContactEff( Node* node, float radius, const Vec2& pos, float s, const Vec2& offset )
{
	Vec2 randPos = Vec2(pos.x + rand_minus1_1() * 80, pos.y + rand_minus1_1() * 80);

	//两点之间的连线,计算碰撞特效需要旋转的角度
	Vec2 mypos = node->convertToWorldSpaceAR(Vec2::ZERO);
	Vec2 newVec = randPos - mypos;
	float angle = newVec.getAngle() * Pi2Angle;

	newVec.normalize();
	newVec *= radius;

	auto size = node->getContentSize();

	auto endPos =Vec2( size.width*0.5 + newVec.x, size.height*0.5 + newVec.y);
	endPos += offset;

	auto sp = Sprite::create("Effect/contactEff/contactEff.png");
	sp->setPosition(endPos);
	sp->setRotation(90 - angle);
	node->addChild(sp);

	auto parti1 = EffectsManager::addParticle("particla/SpeedUpContact/SpeedUpContact.plist",node,endPos);
	if (parti1)
	{
		parti1->setScale(s);
	}

	ActionInterval* scale = ScaleTo::create(0.1f,(7.0 + rand_0_1()) * s,(2.0f + rand_0_1())*s);
	CallFuncN* func = CallFuncN::create(nullptr,callfuncN_selector(PlaneProtect::removeEff));
	ActionInterval* seq = Sequence::create(scale, func, nullptr);
	sp->runAction(seq);
}
Esempio n. 2
0
void TestScene::lightn()
{
    Vec2 p = {static_cast<float>(random(-300, 300)),static_cast<float>(random(-500, 500))};
    int N = random(1, 5);
    for (int i = 0; i < N; i++) {
        Vec4 color = {rand_0_1(),rand_0_1(),rand_0_1(),1.0};
        _lightningInter->configLightning({0,0}, p, 0.1f, color);
    }
}
Esempio n. 3
0
Color ColorSampler::getSample() {
    float r, g, b;

    // random pastel colors
    r = (rand_0_1() * 128) + 100;
    g = (rand_0_1() * 128) + 100;
    b = (rand_0_1() * 128) + 100;

    Color c(r, g, b);

    return c / 255.0;
}
Esempio n. 4
0
void AcceEffectSpace::fillVertexData()
{
    const Vec3 bbl = {-_BONE_THIN, -_BONE_THIN, -0.5f * _BONE_LENGTH};
    const Vec3 bbr = {_BONE_THIN, -_BONE_THIN, -0.5f * _BONE_LENGTH};
    const Vec3 btl = {-_BONE_THIN, _BONE_THIN, -0.5f * _BONE_LENGTH};
    const Vec3 btr = {_BONE_THIN, _BONE_THIN, -0.5f * _BONE_LENGTH};

    const Vec3 fbl = {-_BONE_THIN, -_BONE_THIN, 0.5f * _BONE_LENGTH};
    const Vec3 fbr = {_BONE_THIN, -_BONE_THIN, 0.5f * _BONE_LENGTH};
    const Vec3 ftl = {-_BONE_THIN, _BONE_THIN, 0.5f * _BONE_LENGTH};
    const Vec3 ftr = {_BONE_THIN, _BONE_THIN, 0.5f * _BONE_LENGTH};

    int dataIndex = 0;
    for (int i = 0; i < _N; i++) {
        Vec3 center = {(rand_0_1()-0.5f)*_width, (rand_0_1()-0.5f)*_height, (rand_0_1()-0.5f)*_length};
        Tex2F tex = {i*1.0f/_N, rand_0_1()};

        _data[dataIndex++] = {center+btr, tex};
        _data[dataIndex++] = {center+btl, tex};
        _data[dataIndex++] = {center+ftl, tex};

        _data[dataIndex++] = {center+btr, tex};
        _data[dataIndex++] = {center+ftl, tex};
        _data[dataIndex++] = {center+ftr, tex};

        _data[dataIndex++] = {center+btl, tex};
        _data[dataIndex++] = {center+bbl, tex};
        _data[dataIndex++] = {center+fbl, tex};

        _data[dataIndex++] = {center+btl, tex};
        _data[dataIndex++] = {center+fbl, tex};
        _data[dataIndex++] = {center+ftl, tex};

        _data[dataIndex++] = {center+bbr, tex};
        _data[dataIndex++] = {center+btr, tex};
        _data[dataIndex++] = {center+ftr, tex};

        _data[dataIndex++] = {center+bbr, tex};
        _data[dataIndex++] = {center+ftr, tex};
        _data[dataIndex++] = {center+fbr, tex};

        _data[dataIndex++] = {center+bbl, tex};
        _data[dataIndex++] = {center+bbr, tex};
        _data[dataIndex++] = {center+fbr, tex};

        _data[dataIndex++] = {center+bbl, tex};
        _data[dataIndex++] = {center+fbr, tex};
        _data[dataIndex++] = {center+fbl, tex};
    }
}
Esempio n. 5
0
void ExplisonScreen::AddParticle()
{
	auto layer = UIController::getInstance()->getEffectsLayer();

	Vec2 pos = Vec2(m_WinSize.width * rand_0_1(), m_WinSize.height * rand_0_1());

	EffectsManager::addParticle("particla/FullScreenExpl/Exp1.plist",layer,pos);
	//EffectsManager::addParticle("particla/FullScreenExpl/Exp2.plist",layer,pos);
	//EffectsManager::addParticle("particla/FullScreenExpl/Exp3.plist",layer,pos);

	ActionInterval* delay = DelayTime::create(0.005);
	CallFunc* func = CallFunc::create(this,callfunc_selector(ExplisonScreen::AddParticle));
	ActionInterval* seq = Sequence::create(delay, func, nullptr);
	runAction(seq);
}
Esempio n. 6
0
void ExplisonScreen::StartExpMusic()
{
	ActionInterval* delay = DelayTime::create(0.05 + rand_0_1() * 0.05);
	CallFunc* func = CallFunc::create(this,callfunc_selector(ExplisonScreen::PlayExpMusic));
	ActionInterval* seq = Sequence::create(delay, func, nullptr);
	runAction(seq);
}
Esempio n. 7
0
inline std::pair<bool, AgentPos> help_findAroundDirection(const std::unordered_map<AgentPos, bool>& versionMap, bool iscover, const AgentPos& mypos)
{
    AgentPos around[4] = {{mypos.x+1, mypos.y},{mypos.x-1, mypos.y},{mypos.x, mypos.y+1},{mypos.x, mypos.y-1}};
    std::vector<AgentPos> founds;
    AgentPos notInThree;
    for (auto pos : around) {
        if (iscover) {
            if (versionMap.at(pos) == false) founds.push_back(pos);
            else notInThree = pos;
        } else {
            if (versionMap.at(pos) == true) founds.push_back(pos);
            else notInThree = pos;
        }
    }
    if (founds.size() == 4) {
        return {false, {0,0}};
    } else if (founds.size() > 0 && founds.size() == 3) {
        int x = mypos.x == notInThree.x ? mypos.x : notInThree.x < mypos.x ? mypos.x+1: mypos.x -1;
        int y = mypos.y == notInThree.y ? mypos.y : notInThree.y < mypos.y ? mypos.y +1:mypos.y -1;
        return {true, {x,y}};
    } else if (founds.size() > 0) {
        return {true, founds[static_cast<int>(rand_0_1()*100)%founds.size()]};
    } else {
        return {false, {0,0}};
    }
}
Esempio n. 8
0
bool boolWithOdds(float odds)
{
    if(rand_0_1() < odds)
        return true;
    else
        return false;
}
MouseAction MouseController::getMouseAction(float IQ, ItemType itemtype, Vec2 dis, Vec2 speed, float range) {
	if (rand_0_1() * maxIQ > IQ) {
		return RUN;
	}
	Vec2 _time((speed.x != 0 ? dis.x / speed.x : 99999), (speed.y != 0 ? dis.y / speed.y : 99999));
	switch (itemtype) {
	case HOLE:
		return JUMP;
		break;
	case DENGEROUS_CUCRBIT:
		if (cmpFloat(_time.x, _time.y, range) == 0) {
			if (dis.x > Mouse::mouseWidth)
				return SLOWDOWN;
			return SPEEDUP;
		}

		break;
	case BENEFICATE_CUCRBIT:
		if (cmpFloat(_time.x, _time.y, range) == 1) {
			return SPEEDUP;
		}
		else if (cmpFloat(_time.x, _time.y, range) == -1) {
			return SLOWDOWN;
		}
		break;
	case SCOOTER:
		return JUMP;
		break;
	default: break;
	}
	return RUN;
}
Esempio n. 10
0
void GameScene::trashAttack()
{
	Trash* t = Trash::create();
	t->trashAttack((rand_0_1()*0.8+0.1)*visibleSize.height);
	t->setSpeed(trashSpeed);
	this->addChild(t);
	trashs.pushBack(t);
}
Esempio n. 11
0
void Player::PlayerHitByBall(Game_Scene* game, Ball* ball)
{
	if (!_invincible)
	{
		//get hit
		_timeSinceHit = 0.0f;
		//daze only if not dazed too recently
		if (_stunLockTimer >= Settings::playerDazeInvincibilityTime)
		{
			_stunLockTimer = 0;
			if (ball->getType() == OilBall::type)
			{
				_sprite->setColor(_oilColour);
				Daze(true);
			}
			else if (ball->getType() == BombBall::type || ball->getType() == BombOther::type)
			{
				Daze(true);
			}
			else if (game->GetBallHitter(ball)->HasDoubleAttack())
			{
				Daze(true);
			}
			else
			{
				Daze(false);
			}
		}
		if (ball->getType() == BombOther::type)
		{
			((Game_Scene*)(this->getParent()->getParent()))->SeeSaw(this, -4);

			Explosion* boomImage;
			boomImage = Explosion::create();
			ball->getParent()->addChild(boomImage);

			boomImage->setPosition(ball->getParent()->convertToWorldSpace(ball->getPosition()));
			((Game_Scene*)(ball->getParent()->getParent()))->DestroyAndDropBall(ball);

			AudioHelper::Play("bombball");
		}
		else if (ball->getType() == BombBall::type)
		{

			AudioHelper::Play("selfexplode");
		}
		else if (ball->getType() == OilBall::type)
		{
			AudioHelper::PlayRandom("Oilball", 3);
		}
		else if (ball->getType() == RocketBall::type)
		{
			AudioHelper::Play("missilehit");
		}
		AudioHelper::PlayRandom("Au", 4, (0.5 + rand_0_1() * 1.5));
	}
}
Esempio n. 12
0
void Animal::escape()
{
    _state = AnimalState::Escape;
    auto target = WorldManager::getInstance()->getOutRandomPlace();
    float delay = rand_0_1() * 0.5;
    runAction(Sequence::create(
                  DelayTime::create(delay),
                  JumpTo::create(0.5f, target, 100, 1),
                  RemoveSelf::create(),
                  NULL
              ));
}
Esempio n. 13
0
void WealthEffect::createEffect(const char* spriteFrameName,int count,float scale,Vec2 startPoint,Vec2 stopPoint)
{
    auto findIter=_animateMap.find(spriteFrameName);
    if (findIter==_animateMap.end())
        return;

    auto runningScene=Director::getInstance()->getRunningScene();
    Animate* animate=findIter->second;
    ExplosionData* explosionData;
    Sprite* effectSprite;
    Vec2 position;
    float radian;
    Vec2 direction;
    for (int i=0; i<count; ++i)
    {
        effectSprite=Sprite::create();
        effectSprite->setScale(scale);
        
        position.x=startPoint.x+rand_minus1_1()*20;
        position.y=startPoint.y+rand_minus1_1()*20;
        effectSprite->setPosition(position);
        runningScene->addChild(effectSprite,_localZOrder);
        
        explosionData=new ExplosionData;
        explosionData->_explosionSprite=effectSprite;
        explosionData->delayTime=0.3*rand_0_1();
        explosionData->stage=0;
        explosionData->_animate=animate;
        explosionData->_stopPoint=stopPoint;
        
        radian=6.28*rand_0_1();
        direction=Vec2(cos(radian),sin(radian));
        explosionData->_speed=(500+400*rand_0_1())*direction;
        explosionData->_acceleration=-2300*direction;
        
        _explosionDataVector.push_back(explosionData);
    }
    startEffect();
}
Esempio n. 14
0
// generate a random number from a normal distribution
// with mean 'mean' and standard deviation 'std';
// Remark: the function can generate pairs of numbers
//         (y1 and y2), but we only used y1 now
// Code based on the polar form of the Box-Muller transformation,
// according to a webpage of Dr. Everett (Skip) F. Carter Jr.
double randn(double mean, double stdev)
{
    float x1, x2, w, y1;//, y2;

    do
    {
        // we could use drand48 instead of rand_0_1...
        // or R250 instead of rand()
        x1 = 2.0 * rand_0_1() - 1.0;
        x2 = 2.0 * rand_0_1() - 1.0;
        w = x1 * x1 + x2 * x2;
    }
    while(w >= 1.0);

    w = sqrt((-2.0 * log(w))/w);
    y1 = x1 * w;

    // this function computes pairs of values, but the
    // second available value is currently not used
    //y2 = x2 * w;

    return (mean + stdev * y1);
}
Esempio n. 15
0
void Player::HitBall()
	{
		for (size_t i = 0; i < _ballManager->GetNumberOfBalls(); i++)
		{
			Ball& ball = *_ballManager->GetBallAtIndex(i);

			// don't test if ball belongs to other player
			// not enough balls to justify it.
			if (!ball.IsContained())
			{
				Vec2 ppos = this->convertToWorldSpace(Vec2());
				Vec2 bpos = ball.getParent()->convertToWorldSpace(ball.getPosition());
				Vec2 toBall = bpos - ppos;
				float r = 100;
				if (toBall.length() < r)
				{
					if (ball.getType() == BombBall::type)
					{	
						Vec2 emptySpace; //Basically a placeholder because this will only be used in case of bomb balls, but hit requires a vec2 even if one is not used.
						ball.Hit(emptySpace);
						PlayerHitByBall(nullptr, &ball);
						((Game_Scene*)(this->getParent()->getParent()))->SeeSaw(this, -4);
					}
					else if (ball.getType() == WalletBall::type)
					{
						Vec2 emptySpace; //Basically a placeholder because this will only be used in case of bomb balls, but hit requires a vec2 even if one is not used.
						ball.Hit(emptySpace);
						((Game_Scene*)(this->getParent()->getParent()))->SeeSaw(this, 4);
						AudioHelper::PlayRandom("Moneyball", 2);
					}
					else
					{ 
						float difficulty = 0.1f; // 0=easy, 1=hard
						float dy = toBall.y / r; // -1 -> 1
					
						dy = (dy > 0 ? 1 : -1) * pow(abs(cbrtf(dy)), (1.0f - difficulty)); // cubic curve, harder to get y just right
						dy = (dy + 1) / 2.0f; // 0 -> 1 for lerp
						Vec2 hitDir = ccpLerp(Vec2(Settings::horizontalSpeed, -250), Vec2(Settings::horizontalSpeed, 550), dy); // lerp between mim/max hit strength
						ball.Hit(hitDir);
					}
					AudioHelper::PlayRandom("bathitting", 3, 0.75 + rand_0_1() * 0.5);
				}
			}
		}
	}
Esempio n. 16
0
void AcceEffectSpace::config(bool onOff, const cocos2d::Vec3& speed)
{
    constexpr float PI = 3.1415926;
    if (_lastState != onOff) {
        _zRandomRotateQua = rotation2quaternion({0,0, rand_0_1()*360});
    }
    if (this->isVisible() != onOff) this->setVisible(onOff);
    if (onOff) {
        float xSin = speed.x / speed.length();
        float xAngel = std::asin(xSin);
        float ySin = speed.y /speed.length();
        float yAngel = std::asin(ySin);

        auto speedRot = rotation2quaternion(Vec3{yAngel/PI * 180, xAngel/PI * 180, 0});
        speedRot.multiply(_zRandomRotateQua);
        this->setRotationQuat(speedRot);
    }
    setPercent(speed.length()/67);
    _lastState = onOff;
}
CEffect* EffectManager::createHitEffect(CWeapon* weapon, int parentID, int targetID)
{
	CEffectSet* effect = new CEffectSet();

	//¼ÆË㱩»÷¼Ó³É
	bool isCritical = false;
	float mul = 1;
	if (rand_0_1() < weapon->criticalChance)
	{
		mul = weapon->criticalMultiplier;
		isCritical = true;
	}

	//ÊÇ·ñ·¶Î§¹¥»÷
	if (weapon->BoomRange == 0)
	{
		//effect->addEffect(new CEffectDamage(weapon->MinDamage*mul, weapon->MaxDamage*mul, weapon->DamageType, weapon->attack_Animate, parentID, targetID));
		effect->addEffect(new CEffectDamage(weapon->Damage.Min, weapon->Damage.Max*mul, weapon->DamageType, weapon->attack_Animate, parentID, targetID));
		if (!string(weapon->attack_Effect).empty())
			effect->addEffect(createCEffect(weapon->attack_Effect, parentID, targetID));
		if (isCritical && !string(weapon->critical_Effect).empty())
			effect->addEffect(createCEffect(weapon->critical_Effect, parentID, targetID));

	}
	else
	{
		CEffectSet* set = new CEffectSet();
		//set->addEffect(new CEffectDamage(weapon->MinDamage*mul, weapon->MaxDamage*mul, weapon->DamageType, weapon->attack_Animate, parentID, targetID));
		set->addEffect(new CEffectDamage(weapon->Damage.Min, weapon->Damage.Max*mul, weapon->DamageType, weapon->attack_Animate, parentID, targetID));
		
		if (!string(weapon->attack_Effect).empty())
			set->addEffect(createCEffect(weapon->attack_Effect, parentID, targetID));
		if (isCritical && !string(weapon->critical_Effect).empty())
			set->addEffect(createCEffect(weapon->critical_Effect, parentID, targetID));
		effect->addEffect(new CEffectEnumArea(weapon->Filter, weapon->BoomRange, "", set, parentID));
	}
	return effect;
}
Esempio n. 18
0
BeatNode BeatQuestScene::genRandomNode()
{
    BeatNode node;
    float ran = rand_0_1();
    if (ran < 0.8) {
        node.type = TestBeatType::SWORD;
        node.level = 0;
        node.value = 0;
    } else if (ran < 0.9) {
        node.type = TestBeatType::BLOOD;
        node.level = 0;
        node.value = random(1,3);
    } else {
        node.type = TestBeatType::SHIELD;
        node.level = 0;
        node.value = 0;
    }
    node.beatSpeed = -random(1.f/0.8f, 1.f/1.9f);
    node.beatPos = {random(0.1f,0.9f), 1.f};
    node.beatAccerate = 0;
    node.gen(_defaultLayer);

    return node;
}
Esempio n. 19
0
void TestScene::rect()
{
    _rectEffectNode->configRectEffect({rand_0_1(),rand_0_1(),rand_0_1(),1.f}, 500*Vec2{rand_0_1()-0.5f, rand_0_1()-0.5f}, rand_0_1()*300, rand_0_1()*1, 0.3f);
}
Esempio n. 20
0
void HuntingMonsterManage::update(float dt)
{

    static bool _needTellWave = true;
    _timeLeft -= dt;
    if (_timeLeft <= 0) {

        if ( _needTellWave ) {
            _needTellWave = false;
            _topIconsProtocal->op_addWave();
        }

        // 主类别
        HuntingMonsterGeneralType gt;
        float ran = rand_0_1();
        if (ran < (0.05 + _currentWave/50.f*0.3f)) {
            gt = HuntingMonsterGeneralType::GIANT;
        } else if (ran < (0.05 + _currentWave/50.f*0.3f + 0.1f)) {
            gt = HuntingMonsterGeneralType::BIG;
        } else {
            gt = HuntingMonsterGeneralType::NORMAL;
        }

        if (_currentWave > 15) {
            float newR = rand_0_1();
            if (newR < 0.05f) {
                gt = HuntingMonsterGeneralType::SUPER;
            }
        }
        
        if (_currentWave > 25) {
            float newR = rand_0_1();
            if (newR < 0.09f) {
                gt = HuntingMonsterGeneralType::SUPER;
            } else if (newR < 0.04f) {
                gt = HuntingMonsterGeneralType::TITAN;
            }
        }

        //盾
        bool hasShiled = false;
        int shieldCount = 0;
        if (_currentWave > 10) {
            hasShiled = rand_0_1() < std::min(0.5f, 0.1f+0.5f*_currentWave/50.f);
            shieldCount = hasShiled ? (1 + _currentWave/15) : 0;
        }

        //特殊类别
        HuntingMonsterSpecialType st = HuntingMonsterSpecialType::NONE;
        if (gt == HuntingMonsterGeneralType::NORMAL ||
            gt == HuntingMonsterGeneralType::BIG)
        {

            float rcfg = 0.03f + 0.1f * _currentWave/30.f;
            if (rand_0_1() < rcfg) {
                st = HuntingMonsterSpecialType::ACCE;
            } else if (_currentWave > 13 && rand_0_1() < rcfg) {
                st = HuntingMonsterSpecialType::ATKFIRE;
            }
        }


        //等级
        int level = _currentWave;
        float ran2 = rand_0_1();
        if (ran2 < 0.1) {
            level += 3;
        } else if (ran2 < 0.2) {
            level += 2;
        } else if (ran2 < 0.3) {
            level += 1;
        }
        level += 7;//去掉开始的不好看的敌人
        level = std::min(40, level);
        addMonster(gt, st, hasShiled, level, shieldCount);
        _currentWaveMonsterCnt--;
        if (_currentWaveMonsterCnt == 0) {
            _currentWave++;
            _needTellWave = true;
            _currentWaveMonsterCnt = random(8, 15);
            _timeLeft = random(15, 30);

            //龙卷风
            bool t0 = ((_currentWave == 3 || _currentWave == 10 || _currentWave == 15 )|| (_currentWave > 3 && rand_0_1() < (0.2f + 0.3*(_currentWave/40.f))));
            bool t1 = (_currentWave > 15 && rand_0_1() < (0.1f + 0.25*(_currentWave/40.f)));

            _tornadoManageProtocal->op_configTornado(t0, random(-60, 50), t1, random(20, 100));

            //风
            if (_currentWave > 5) {
                _windBarProtocal->op_configWind(random(0, 5));
            } else {
                _windBarProtocal->op_configWind(random(0, 2));
            }
//            ACSoundManage::s()->play(ACSoundManage::SN_WIND_CHANGE);


        } else {
            _timeLeft =
            gt == HuntingMonsterGeneralType::TITAN ? random(15, 20) :
            gt == HuntingMonsterGeneralType::SUPER ? random(13, 18) :
            gt == HuntingMonsterGeneralType::GIANT ? random(10, 15) :
            gt == HuntingMonsterGeneralType::BIG? random(8, 10): random(5,8);
            _timeLeft = _timeLeft*0.6;
            if (rand_0_1() < 0.2) {
                _timeLeft = _timeLeft*3;//有一定几率拉开一定距离
            }
        }
    }

    for (auto sp : _monsters) {
        sp->update(dt);
    }


    for (auto iter = _monsters.begin(); iter != _monsters.end(); ) {
        if ((*iter)->isDead() ){
            iter = _monsters.erase(iter);
        } else {
            iter++;
        }
    }

}
Esempio n. 21
0
void PixelNode::configBatch(const std::vector<PixelBatchTuple>& data)
{
    _count = 0;
    int totalSize = 0;
    for (auto& p : data) {
        totalSize += p.pixels->size();
    }

    auto _vertexData = (PixelVertexPormat*)malloc(sizeof(PixelVertexPormat)*36*totalSize);

    // 8 point
    const float half_step = 0.5f;

    cocos2d::Vec3 cornors[8] = {{1,1,1}, {-1,1,1}, {-1,-1,1}, {1,-1,1}, {1,1,-1}, {-1,1,-1}, {-1,-1,-1}, {1,-1,-1}};

    auto genface = [this, &cornors, half_step, &_vertexData](int a, int b, int c, int d, const Color4B& color, const cocos2d::Vec3& relativePos, const Vec3& normal2, float scale, float seed){
        _vertexData[_count].position = cornors[a] * half_step * scale + relativePos;
        _vertexData[_count].normal = normal2;
        _vertexData[_count].seed = seed;
        _vertexData[_count++].color = {color.r/255.f, color.g/255.f, color.b/255.f, color.a/255.f};

        _vertexData[_count].position = cornors[b] * half_step * scale+ relativePos;
        _vertexData[_count].normal = normal2;
        _vertexData[_count].seed = seed;
        _vertexData[_count++].color = {color.r/255.f, color.g/255.f, color.b/255.f, color.a/255.f};

        _vertexData[_count].position = cornors[c]  * half_step * scale + relativePos;
        _vertexData[_count].normal = normal2;
        _vertexData[_count].seed = seed;
        _vertexData[_count++].color = {color.r/255.f, color.g/255.f, color.b/255.f, color.a/255.f};

        _vertexData[_count].position = cornors[a] * half_step * scale + relativePos;
        _vertexData[_count].normal = normal2;
        _vertexData[_count].seed = seed;
        _vertexData[_count++].color = {color.r/255.f, color.g/255.f, color.b/255.f, color.a/255.f};

        _vertexData[_count].position = cornors[c] * half_step * scale + relativePos;
        _vertexData[_count].normal = normal2;
        _vertexData[_count].seed = seed;
        _vertexData[_count++].color = {color.r/255.f, color.g/255.f, color.b/255.f, color.a/255.f};

        _vertexData[_count].position = cornors[d] * half_step * scale + relativePos;
        _vertexData[_count].normal = normal2;
        _vertexData[_count].seed = seed;
        _vertexData[_count++].color = {color.r/255.f, color.g/255.f, color.b/255.f, color.a/255.f};
    };

    for (auto& p : data) {
        for (auto& pix : *p.pixels) {
            cocos2d::Vec3 relativePos = p.position + Vec3{static_cast<float>(pix.pos.x), static_cast<float>(pix.pos.y), 0.f} * p.scale;
            float seed = rand_0_1();
            genface(0,1,2,3,pix.color, relativePos, {0,0,1}, p.scale, seed);
            genface(4,0,3,7,pix.color, relativePos, {1,0,0}, p.scale, seed);
            genface(5,4,7,6,pix.color, relativePos, {0,0,-1}, p.scale, seed);
            genface(1,5,6,2,pix.color, relativePos, {-1,0,0}, p.scale, seed);
            genface(4,5,1,0,pix.color, relativePos, {0,1,0}, p.scale, seed);
            genface(6,7,3,2,pix.color, relativePos, {0,-1,0}, p.scale, seed);
        }
    }
    if (!_batched) {
        glGenVertexArrays(1, &_vao);
        cocos2d::GL::bindVAO(_vao);
        glGenBuffers(1, &_vbo);
        glBindBuffer(GL_ARRAY_BUFFER, _vbo);

        glEnableVertexAttribArray(0);
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(PixelVertexPormat), (GLvoid *)offsetof(PixelVertexPormat, position));
        glEnableVertexAttribArray(1);
        glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(PixelVertexPormat), (GLvoid *)offsetof(PixelVertexPormat, color));
        glEnableVertexAttribArray(2);
        glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(PixelVertexPormat), (GLvoid *)offsetof(PixelVertexPormat, normal));
        glEnableVertexAttribArray(3);
        glVertexAttribPointer(3, 1, GL_FLOAT, GL_FALSE, sizeof(PixelVertexPormat), (GLvoid *)offsetof(PixelVertexPormat, seed));


        cocos2d::GL::bindVAO(0);
        glBindBuffer(GL_ARRAY_BUFFER, 0);
        CCLOG("pixel batch new VAO=%d VBO=%d", _vao, _vbo);
    }


    glBindBuffer(GL_ARRAY_BUFFER, _vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(PixelVertexPormat)*_count, _vertexData, GL_STREAM_DRAW);
    glBindBuffer(GL_ARRAY_BUFFER, 0);


    free(_vertexData);

    _batched = true;
}
bool WelcomeScene::init()
{
	if (!Layer::init())
	{
		return false;
	}
	auto visibleSize = Director::getInstance()->getVisibleSize();
	Vec2 origin = Director::getInstance()->getVisibleOrigin();
	SpriteFrameCache::getInstance()->addSpriteFramesWithFile("image/all_pic.plist");

	bgLayer = BgLayer::create();
	bgLayer->removeChildByTag(BgLayer::TimeTag);
	bgLayer->removeChildByTag(BgLayer::ProgressTag);
	bgLayer->removeChildByTag(BgLayer::ProgressBgtag);
	this->addChild(bgLayer);

	menuLayer = MenuLayer::create();
	this->addChild(menuLayer);

	// 标题
	auto titleLabel = Label::createWithTTF("Meteorite Crisis", "fonts/Marker Felt.ttf", 60);
	titleLabel->setPosition(visibleSize.width / 2, visibleSize.height * 0.8);
	addChild(titleLabel);

	//menu play
	auto one_man = MenuItemImage::create();
	auto normal1 = SpriteFrameCache::getInstance()->getSpriteFrameByName("one_man_normal.png");
	auto selected1 = SpriteFrameCache::getInstance()->getSpriteFrameByName("one_man_clicked.png");
	one_man->setNormalSpriteFrame(normal1);
	one_man->setSelectedSpriteFrame(selected1);
	one_man->setCallback([](Ref*){
		auto s = GameScene::createScene();
		float t = 0.5f;
		struct timeval psv;
		gettimeofday(&psv, NULL);
		unsigned rand_seed = (unsigned)(psv.tv_sec + psv.tv_usec);    //转化为毫秒 
		srand(rand_seed);
		float choice = rand_0_1();
		if (choice < 0.25)
		{
			Director::getInstance()->replaceScene(TransitionFlipY::create(t, s));
		}
		else if (choice >= 0.25 && choice < 0.5)
		{
			Director::getInstance()->replaceScene(TransitionFlipY::create(t, s));
		}
		else if (choice >= 0.5 && choice < 0.75)
		{
			Director::getInstance()->replaceScene(TransitionProgressRadialCCW::create(t, s));
		}
		else if (choice >= 0.75 && choice < 1.0)
		{
			Director::getInstance()->replaceScene(TransitionProgressRadialCW::create(t, s));
		}
	});
	one_man->setScale(0.5f);
	//menu how to play
	auto howToPlay = MenuItemImage::create();
	auto normal2 = SpriteFrameCache::getInstance()->getSpriteFrameByName("howtoplay_normal.png");
	auto selected2 = SpriteFrameCache::getInstance()->getSpriteFrameByName("howtoplay_clicked.png");
	howToPlay->setNormalSpriteFrame(normal2);
	howToPlay->setSelectedSpriteFrame(selected2);
	howToPlay->setCallback([&,this](Ref*){
		auto s = HowToPlay::createScene();
		float t = 0.5f;
		struct timeval psv;
		gettimeofday(&psv, NULL);
		unsigned rand_seed = (unsigned)(psv.tv_sec + psv.tv_usec);    //转化为毫秒 
		srand(rand_seed);
		float choice = rand_0_1();
		if (choice < 0.25)
		{
			Director::getInstance()->replaceScene(TransitionFlipY::create(t, s));
		}
		else if (choice >= 0.25 && choice < 0.5)
		{
			Director::getInstance()->replaceScene(TransitionFlipY::create(t, s));
		}
		else if (choice >= 0.5 && choice < 0.75)
		{
			Director::getInstance()->replaceScene(TransitionProgressRadialCCW::create(t, s));
		}
		else if (choice >= 0.75 && choice < 1.0)
		{
			Director::getInstance()->replaceScene(TransitionProgressRadialCW::create(t, s));
		}
	});
	howToPlay->setScale(0.5f);
	howToPlay->setPositionY(- howToPlay->getContentSize().height/2 - 5);
	auto menu = Menu::create(one_man, howToPlay, NULL);
	menu->setPosition(visibleSize.width / 2, visibleSize.height * 0.5);
	menu->setAnchorPoint(Vec2(0.5,1));
	
	addChild(menu);

	// 主角模型
	auto player = Sprite::createWithSpriteFrameName("SpaceFlier4.png");
	player->setScale(0.5);
	player->setPosition(visibleSize.width/2, visibleSize.height * 0.65);
	auto cache = SpriteFrameCache::getInstance();
	Vector<SpriteFrame*> vec_sf;
	SpriteFrame* sf = NULL;
	for (int i = 1; i <= 5; ++i)
	{
		sf = cache->getSpriteFrameByName(StringUtils::format("SpaceFlier%d.png", i));
		vec_sf.pushBack(sf);
	}
	Animation* animation = Animation::createWithSpriteFrames(vec_sf, 0.05f, -1);
	auto action = Animate::create(animation);
	player->runAction(CCRepeatForever::create(
		Sequence::create(action, action->reverse(), NULL)));
	addChild(player);

	// 最高分
	// 最高分标题
	auto highScoreTitle = Label::createWithTTF("BestScore:", "fonts/Marker Felt.ttf", 25);
	highScoreTitle->setPosition(visibleSize.width * 0.48, visibleSize.height * 0.2);
	this->addChild(highScoreTitle);
	// 最高分
	auto bestScore = UserDefault::getInstance()->getIntegerForKey("highScore");
	auto highScore = Label::createWithTTF(
		__String::createWithFormat("%i", bestScore)->getCString(),
		"fonts/Marker Felt.ttf",
		25);
	highScore->setPosition(visibleSize.width * 0.6 , visibleSize.height * 0.2);
	this->addChild(highScore);

	return true;
}
Esempio n. 23
0
bool GameScene::init(bool _clickRed) {
	if (!Layer::init()){
		return false;
	}
	this->aiPlayer = new AIPlayer(this);

	clickRed = _clickRed;
	Size visibleSize = Director::getInstance()->getVisibleSize();
	Vec2 origin = Director::getInstance()->getVisibleOrigin();
	auto closeItem = MenuItemImage::create(
		"CloseNormal.png",
		"CloseSelected.png",
		CC_CALLBACK_1(GameScene::menuCloseCallback, this));
	closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width / 2,
		origin.y + closeItem->getContentSize().height / 2));

	MenuItemImage* backMenu = MenuItemImage::create("res/regret.png", "res/regret_selected.png", CC_CALLBACK_1(GameScene::backQIMenuCallback, this));
	backMenu->setPosition(Vec2(visibleSize.width - 200, visibleSize.height / 2 - 100));

	MenuItemImage* newGameMenu = MenuItemImage::create("res/new.png", "res/new_selected.png", CC_CALLBACK_1(GameScene::newGameMenuCallback, this));
	newGameMenu->setPosition(Vec2(visibleSize.width - 200, visibleSize.height / 2));

	auto menu = Menu::create(closeItem, backMenu, newGameMenu, NULL);
	menu->setPosition(Vec2::ZERO);
	this->addChild(menu, 1);
	/*
	auto label = Label::createWithTTF(getStringByKey("GuideStart"), "fonts/fangzheng.ttf", 24);
	label->setPosition(Vec2(origin.x + visibleSize.width/2,
	origin.y + visibleSize.height - label->getContentSize().height));
	this->addChild(label, 1);
	*/

	Vec2 offset = Vec2(20.0, 10.0);
	auto floor = Sprite::create("res/floor.png");
	floor->setPosition(Vec2(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y));
	floor->setScaleX(visibleSize.width / floor->getContentSize().width);
	floor->setScaleY(visibleSize.height / floor->getContentSize().height);
	this->addChild(floor);

	Sprite* qipan = Sprite::create("res/background.png");
	qipan->setAnchorPoint(Vec2::ZERO);
	qipan->setPosition(offset);
	qipan->setScale((visibleSize.height - offset.y * 2) / qipan->getContentSize().height);
	this->addChild(qipan);
	// 给棋盘添加touch监听
	EventListenerTouchOneByOne *touchListener = EventListenerTouchOneByOne::create();
	touchListener->onTouchBegan = CC_CALLBACK_2(GameScene::onTouchesBegan, this);
	touchListener->onTouchCancelled = CC_CALLBACK_2(GameScene::onTouchCancelled, this);
	touchListener->onTouchEnded = CC_CALLBACK_2(GameScene::onTouchEnded, this);
	touchListener->onTouchMoved = CC_CALLBACK_2(GameScene::onTouchMoved, this);
	EventDispatcher* eventDispatcher = Director::getInstance()->getEventDispatcher();
	eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener->clone(), qipan);

	for (int i = 0; i < 32; i++){
		sts[i] = Stone::create(i, clickRed);
		sts[i]->setPosition(Vec2(rand_0_1()*visibleSize.width, rand_0_1()*visibleSize.height));
		MoveTo* moveTo = MoveTo::create(0.6f, Vec2(sts[i]->getRealX(), sts[i]->getRealY()));
		//MoveTo* moveTo = MoveTo::create(0.6f, Vec2(stone_x + sts[i]->getX()*def, stone_y + sts[i]->getY()*def));
		//sts[i]->setPosition(Vec2(stone_x + sts[i]->getX()*def, stone_y + sts[i]->getY()*def));
		sts[i]->runAction(moveTo);
		this->addChild(sts[i]);
	}

	spriteSelected = Sprite::create("res/selected.png");
	spriteSelected->setVisible(false);
	addChild(spriteSelected, 10);
	select_id = -1;
	//level = 1;
	isRedTurn = true;
	steps = Array::create();
	steps->retain();

	scheduleOnce(CC_SCHEDULE_SELECTOR(GameScene::updateAutoGo), 1.0f);
	return true;
}
Esempio n. 24
0
void StrayBulletLayer::shootStrayBullet( float t )
{
	 auto bullet = GameData::getInstance()->getBulletFactory()->createStrayBullet();
	 bullet->setPosition(30 + (m_winSize.width - 30)* rand_0_1(),-50);
	 UIController::getInstance()->getEffectsLayer()->addChild(bullet,1);
}
float Helper::rand(float min, float max)
{
	return rand_0_1()*(max - min + 1) + min;
}