Esempio n. 1
0
static void fight(char_t *c)
{
	// Always hit the enemy first
	int damage = getDamage(getPlayer(), c);

	char buf[50];
	if(!doDamage(c, damage)){
		getPlayer()->stats.xp += c->stats.xp;
		removeCharMap(&map, c);

		sprintf(buf, "You killed \"%s\"", getNameFromChar(c));
		popupText(buf);

		checkLevelUp();
		return;
	}else{
		sprintf(buf, "You deal %d damage", damage);
		popupText(buf);
	}

	damage = getDamage(c, getPlayer());
	sprintf(buf, "You take %d damage", damage);
	popupText(buf);
	if(!doDamage(getPlayer(), damage)){
		getPlayer()->stats.health = 0;
		die();
	}
}
void LifeForm::move(const LCreal fwd, const LCreal sdws)
{
    if (getDamage() < 1) {
        osg::Vec3 old = getEulerAngles();
        LCreal hdg = old.z();

        LCreal tempFwd = fwd, tempSdws = sdws;

        // our deadband (if we are barely moving, just stop)
        if (lcAbs(tempFwd) < 0.9f) tempFwd = 0;
        if (lcAbs(tempSdws) < 0.9f) tempSdws = 0;
        const double xVel = tempFwd * (lcCos(hdg));
        const double yVel = tempFwd * (lcSin(hdg));

        // now calculate our sideways velocity
        const double xxVel = tempSdws * (lcCos((hdg + (90 * static_cast<LCreal>(Basic::Angle::D2RCC)))));
        const double yyVel = tempSdws * (lcSin((hdg + (90 * static_cast<LCreal>(Basic::Angle::D2RCC)))));

        // now add the vectors
        const double newXVel = xVel + xxVel;
        const double newYVel = yVel + yyVel;

        LCreal zVel = 0.0;
        setVelocity(static_cast<LCreal>(newXVel), static_cast<LCreal>(newYVel), zVel);
    }
    else setVelocity(0, 0, 0);
}
Esempio n. 3
0
void Battle::shootEachOther()// implied "if possible"
  {
  if (abs(s1.distance) < s1.range && !s1.cannonTimer)
    {
    s2.refToShip.durability -= getDamage(s1, s2);
    if (s1.refToShip.cannonList.size() > 0)
      s1.cannonTimer = ceil(1/((double)s1.refToShip.cannonList.front().reload+2) * 20.0f);
    }

  if (abs(s2.distance) < s2.range && !s2.cannonTimer)
    {
    s1.refToShip.durability -= getDamage(s2, s1);
    if (s2.refToShip.cannonList.size() > 0)
       s2.cannonTimer = ceil(1/((double)s2.refToShip.cannonList.front().reload+2) * 20.0f);
    }
  }
Esempio n. 4
0
int characterShell::getDamage(lua_State* pLua)
{
	auto pCharacter = worldShell::CWorldSingleton::instance()->getPlayer()->getCharacter();

	if(pCharacter != nullptr)
		lua_pushinteger(pLua, pCharacter->getDamage());

	return 1;
}
bool CvAirMissionDefinition::isDead(BattleUnitTypes unitType) const
{
	checkBattleUnitType(unitType);
	FAssertMsg(getUnit(unitType) != NULL, "[Jason] Invalid battle unit type.");
	if(getDamage(unitType) >= getUnit(unitType)->maxHitPoints())
		return true;
	else
		return false;
}
Esempio n. 6
0
	void Enemy::attack()
	{
		float table[4] = { 0.f, 1.f ,2.f};
		kuma_.setSrcX(table[anim_.xNo_]);
		if (anim_.xNo_ == 1)
		{
			auto p = getObjectFromRoot("1P");
			auto player = ci_ext::weak_to_shared<Player>(p);
			player->getDamage(attackPow_);
		}
	}
Esempio n. 7
0
	int ShotGun::calculateDamage(const Point& p1, const Point& p2) const
	{
		graphlib::GenericVector2<float> v1(p1.x(),p1.y());
		graphlib::GenericVector2<float> v2(p2.x(),p2.y());
		float dist = (v1-v2).length();
		float mult = 0.0;
		if (dist <= shotRange/2) {
			mult = 1.0;
		} else if (dist <= shotRange) {
			mult = (-dist / (shotRange/2)) + 2.0;
		}
		return (mult * getDamage());
	}
Esempio n. 8
0
//Constructor from the code of AI and the level of the different capacities
Unit::Unit(std::string iaCode, int speedLevel, int lifeLevel, int armorLevel, int regenLevel, int damageLevel, int rangeLevel, int firerateLevel)
{
    init_();
    this->iaCode_ = iaCode;
	tree = std::shared_ptr<TreeElement>((TreeElement*)NodeConstructor::create(&iaCode));
    getSpeed().upgrade(speedLevel);
    getLife().upgrade(lifeLevel);
    getArmor().upgrade(armorLevel);
    getRegen().upgrade(regenLevel);
    getDamage().upgrade(damageLevel);
    getRange().upgrade(rangeLevel);
    getFirerate().upgrade(firerateLevel);
}
int LightsaberCrystalComponentImplementation::inflictDamage(TangibleObject* attacker, int damageType, float damage, bool destroy, bool notifyClient) {
	if (isDestroyed()) {
		return 0;
	}

	TangibleObjectImplementation::inflictDamage(attacker, damageType, damage, destroy, notifyClient);

	if (isDestroyed()) {
		ManagedReference<WeaponObject*> weapon = cast<WeaponObject*>(_this.getReferenceUnsafeStaticCast()->getParent().get()->getParent().get().get());

		if (weapon != NULL) {
			if (getColor() == 31) {
				weapon->setAttackSpeed(weapon->getAttackSpeed() - getAttackSpeed());
				weapon->setMinDamage(weapon->getMinDamage() - getDamage());
				weapon->setMaxDamage(weapon->getMaxDamage() - getDamage());
				weapon->setHealthAttackCost(weapon->getHealthAttackCost() - getSacHealth());
				weapon->setActionAttackCost(weapon->getActionAttackCost() - getSacAction());
				weapon->setMindAttackCost(weapon->getMindAttackCost() - getSacMind());
				weapon->setWoundsRatio(weapon->getWoundsRatio() - getWoundChance());
				weapon->setForceCost(weapon->getForceCost() - getForceCost());
			}

			if (getColor() != 31) {
				weapon->setBladeColor(31);
				weapon->setCustomizationVariable("/private/index_color_blade", 31, true);

				if (weapon->isEquipped()) {
					ManagedReference<CreatureObject*> parent = cast<CreatureObject*>(weapon->getParent().get().get());
					ManagedReference<SceneObject*> inventory = parent->getSlottedObject("inventory");
					inventory->transferObject(weapon, -1, true, true);
					parent->sendSystemMessage("@jedi_spam:lightsaber_no_color"); //That lightsaber can not be used until it has a color-modifying Force crystal installed.
				}
			}
		}
	}

	return 0;
}
Esempio n. 10
0
void Hero_Attack1::ProcessCollision(MyObject *_Obj)
{
	
	if(getiCollision() == true )
	{
		CRECT r;
		r.Left =m_Hero_Attack1_BallInfoSprite.getX();
		r.Top = m_Hero_Attack1_BallInfoSprite.getY() ;
		r.Right = r.Left+ 415;
		r.Bottom = r.Top  + 143;
		CRECT r1;
		r1.Left =m_Hero_Attack1InfoSprite.getX(); ;
		r1.Top = m_Hero_Attack1InfoSprite.getY() ;
		r1.Right = r1.Left+570;
		r1.Bottom = r1.Top  + 255 ;
		if(r.iCollision(_Obj->getRect())== true ||r1.iCollision(_Obj->getRect())== true)
		{
			if(_Obj->getActive() == false  )
			{
				return ;
			}//true la chua trung

			EffectFont* m_EffectFont = new EffectFont(_Obj->getX(), _Obj->getY(),m_Damage);
			ManagerObject::Instance()->getListEffect()->push_back(m_EffectFont);
			if (m_Direct<0)
			{
				Hero_Effect1 *m_HeroEffect1 = new Hero_Effect1(_Obj->getX()+20,_Obj->getY()+50);
				m_HeroEffect1->m_InfoSprite.setScaleX(1);
				m_HeroEffect1->m_InfoSprite.setXY(_Obj->getX()+_Obj->getWidth()/2-25,r.Top);
				ManagerObject::Instance()->getListEffect()->push_back(m_HeroEffect1);
			}
			else
			{
				Hero_Effect1 *m_HeroEffect1 = new Hero_Effect1(_Obj->getX()+130,_Obj->getY()+50);
				m_HeroEffect1->m_InfoSprite.setScaleX(-1);
				m_HeroEffect1->m_InfoSprite.setXY(_Obj->getX()+_Obj->getWidth()/2+25,r.Top);
				ManagerObject::Instance()->getListEffect()->push_back(m_HeroEffect1);
			}

			_Obj->setActive(false);
			_Obj->setFrenzey(true);
			_Obj->setHp(_Obj->getHp() - getDamage());
			if(_Obj->getHp() <= 0)
			{
				_Obj->setLife(false); 
			}	
		}
		
	}
}
Esempio n. 11
0
QMap<QString, pokemonStruct> accessAllCaughtPokemon(QString trainerName)
{
    QMap<QString, pokemonStruct> data;
    QSqlQuery query(Dynamic);
    QString statement = "SELECT * FROM CaughtPokemon WHERE trainer='" + trainerName + "'";
    if( !query.exec(statement) )
    {
        qDebug() << query.lastError().databaseText();
        return data;
    }
    while( query.next() )
    {        
        pokemonStruct saved;
        saved.PID = query.record().field("PID").value().toInt();
        saved.attEV = query.record().field("AtEV").value().toInt();
        saved.CPID = query.record().field("CPID").value().toInt();
        saved.defEV = query.record().field("DefEV").value().toInt();
        saved.EXP = query.record().field("EXP").value().toInt();
        saved.HPEV = query.record().field("HPEV").value().toInt();
        saved.speedEV = query.record().field("speedEV").value().toInt();
        saved.HP = query.record().field("HP").value().toInt();
        saved.level = getLevel(saved.EXP);
        saved.name = getPokemonName(QString::number(saved.PID));
        saved.attack = getStat(saved.attEV, getBaseAtt(saved.name), saved.level);
        saved.defense = getStat(saved.defEV, getBaseDef(saved.name), saved.level);
        saved.speed = getStat(saved.speedEV, getBaseSpeed(saved.name), saved.level);
        saved.HP = getHP(saved.HPEV, getBaseHP(saved.name), saved.level);
        QString moves = query.record().field("Moves").value().toString();
        QStringList l = moves.split("|");
        for(int i = 0; i < l.size(); i++)
        {
            QStringList m = l[i].split(".");
            moveStruct move;
            move.name = m[0];
            move.pp = m[1].toInt();
            move.accuracy = getAccuracy(move.name);
            move.damage = getDamage(move.name);
            move.type = getMoveType(move.name);
            saved.moves.append(move);
        }
        data.insert(saved.name, saved);
    }
    return data;
}
Esempio n. 12
0
//------------------------------------------------------------------------------
// nib2PlayerState() --
//   Called by our processInputList() to update the state of networked player.
//------------------------------------------------------------------------------
void Nib::nib2PlayerState()
{
   models::Player* player = getPlayer();
   if (player != nullptr) {

      // Drive modes
      player->freeze( isFrozen() );
      player->setMode( getMode() );

      // Appearance
      player->setDamage( getDamage() );
      player->setSmoke( getSmoke() );
      player->setFlames( getFlames() );
      player->setCamouflageType( getCamouflageType() );

      // IPlayer's position and Euler angles are set by the player
      // during its dynamics phase and using our DR functions.
   }
}
Esempio n. 13
0
/**
* This method updates all of the enemies in the game.
*/
void Level::update(Player& player)
{
    for (auto& enemy : enemies)
    {
        enemy->update(this, player);
    }

    for (auto& projectile : enemy_projectiles)
    {
        projectile.update();
    }

    for (auto& wall : wall_rects)
    {
        for (auto projectile = enemy_projectiles.begin(); projectile != enemy_projectiles.end();)
        {
            if (SDL_HasIntersection(&wall, &projectile->getRect()))
            {
                enemy_projectiles.erase(projectile);
            }
            else
            {
                projectile++;
            }
        }
    }

    for (auto projectile = enemy_projectiles.begin(); projectile != enemy_projectiles.end();)
    {
        if (SDL_HasIntersection(&projectile->getRect(), &player.getRect()))
        {
            player.damage(projectile->getDamage());
            enemy_projectiles.erase(projectile);
        }
        else
        {
            projectile++;
        }
    }
}
Esempio n. 14
0
void FightLayer::combatAction(int index){
    
    if(index>=_combatVec.size()){
        
        runAction(Sequence::create(DelayTime::create(0.6),CallFunc::create(CC_CALLBACK_0(FightLayer::combatEnd, this)) ,NULL));
        return;
    }
 
    auto cb = _combatVec.at(index);
    
    auto attacker = getCardByHash(cb->getAttacker());
    auto beattacked = getCardByHash(cb->getBeattacked());
    
    if(!attacker||!beattacked){
        return;
    }
    
    auto delay =2;

    if (cb->getSkill()>0) {
        
        attacker->attack(cb->getSkill());

        beattacked->runAction(Sequence::create(DelayTime::create(1.4),CallFunc::create([beattacked](){beattacked->hurt(1, true);}),NULL));
        delay = 2.5;
    }else{
        
        attacker->attack(0);
        auto ba = Sequence::create(DelayTime::create(delay),
                                   CallFunc::create([&](){beattacked->hurt(cb->getDamage(), false);}),NULL);
        beattacked->runAction(ba);
    }
    
    auto action = Sequence::create(DelayTime::create(delay),CallFunc::create([index, this](){auto ni = index+1; combatAction(ni);}), NULL);
    
    runAction(action);
}
Esempio n. 15
0
	void Enemy::distanceCheck()
	{
		if (state_ != State::Attack && state_ != State::Back)
		{
			auto p = getObjectFromRoot("1P");
			auto player = ci_ext::weak_to_shared<Player>(p);
			float distance = player->posX() + player->playerRadius();
			if (kuma_.posX() < distance)
			{

				if (state_ == State::Rush)
				{
					//肘攻撃
					player->getDamage(rushPow_);
				}
				state_ = State::Attack;
				kuma_.setVelocity(ci_ext::Vec3f::zero());
				anim_.setAnimation(3, 0.1f);
				kuma_.setSrcY(1.f);
				

			}
		}
	}
void HumanoidCombatComponent::attack(GameObject& attacker, GameObject& target) {
	target.getCombat()->takeDamage(attacker, target, getDamage());
	restartAttackClock();
}
Esempio n. 17
0
//------------------------------------------------------------------------------
// isPlayerStateUpdateRequired() -- check to see if an update is required
//------------------------------------------------------------------------------
bool Nib::isPlayerStateUpdateRequired(const double curExecTime)
{
   enum { NO, YES, UNSURE } result = UNSURE;

   // ---
   // 1) Make sure that we have a valid player and entity type
   // ---
   const models::Player* player = getPlayer();
   if (player == nullptr || isEntityTypeInvalid()) result = NO;

   // ---
   // 2) Mode changes
   // ---
   if ( (result == UNSURE) && isNotMode( player->getMode()) ) result = YES;

   // 2-a) NIB is being deleted, send one more update to deactivate the entity
   if ( (result == UNSURE) && isMode( models::Player::DELETE_REQUEST ) ) result = YES;

   // ---
   // 3) When we're a local player, check for one of the following ...
   // ---
   if ( (result == UNSURE) && player->isLocalPlayer()) {

      //double drTime = curExecTime - getTimeExec();
      models::SynchronizedState playerState = player->getSynchronizedState();
      const double drTime = static_cast<double>(playerState.getTimeExec()) - getTimeExec();

      // 3-a) Freeze flag has changed
      if ( (player->isFrozen() && isNotFrozen()) || (!player->isFrozen() && isFrozen()) ) {
         result = YES;
      }

      // 3-b) Max DR timeout
      if (result == UNSURE) {
         if ( drTime >= getNetIO()->getMaxTimeDR(this) ) {
            result = YES;
         }
      }

      // 3-c) Appearance has changed
      if (result == UNSURE &&
         (player->getDamage() != getDamage() ||
         player->getSmoke()  != getSmoke()   ||
         player->getFlames() != getFlames() ||
         player->getCamouflageType() != getCamouflageType() )
         ) {
            result = YES;
      }

      // 3-d) Check dead reckoning errors
      if (result == UNSURE && isNotFrozen()) {

         // Compute our dead reckoned position and angles, which are
         // based on our last packet sent.
         base::Vec3d drPos;
         base::Vec3d drAngles;
         mainDeadReckoning(drTime, &drPos, &drAngles);

         // 3-d-1) Position error
         if (!player->isPositionFrozen() && !player->isAltitudeFrozen()) {

            // max position error (meters)
            const double maxPosErr = getNetIO()->getMaxPositionErr(this);
            const double maxPosErr2 = maxPosErr*maxPosErr;  // squared

            // Check if the length of the position error (squared) is greater
            // than the max error (squared)
            //base::Vec3d ppos = player->getGeocPosition();
            const base::Vec3d ppos = playerState.getGeocPosition();
            const base::Vec3d errPos = drPos - ppos;
            if (errPos.length2() >= maxPosErr2) {
               result = YES;
            }
         }

         // 3-d-2) Orientation error
         if (result == UNSURE && !player->isAttitudeFrozen()) {

            // max angle error (radians)
            const double maxAngleErr = getNetIO()->getMaxOrientationErr(this);

            // Compute angular error
            //base::Vec3 errAngles = drAngles - player->getGeocEulerAngles();
            base::Vec3d errAngles = drAngles - playerState.getGeocEulerAngles();

            // Check if any angle error is greater than the max error
            errAngles[0] = std::fabs( base::angle::aepcdDeg(errAngles[0]) );
            if (errAngles[0] >= maxAngleErr) result = YES;

            errAngles[1] = std::fabs( base::angle::aepcdDeg(errAngles[1]) );
            if (errAngles[1] >= maxAngleErr) result = YES;

            errAngles[2] = std::fabs( base::angle::aepcdDeg(errAngles[2]) );
            if (errAngles[2] >= maxAngleErr) result = YES;
         }
      }
   }

   // ---
   // 4) Check for air vehicle articulated and attached parts (always check this)
   // ---
   if ( player != nullptr && player->isMajorType(models::Player::AIR_VEHICLE) ) {

      const models::AirVehicle* av = static_cast<const models::AirVehicle*>(player);

      // (4-a) Check wing sweep angle.  We only send out wing sweep as
      // an part if the position is greater than zero or if we've previously been
      // sending the wing sweep (count > 0).
      {
         const double angle = av->getWingSweepAngle();  //  radians
         if (angle > 0 || apartWingSweepCnt > 0) {
            // Check if the angle has changed.
            if (angle != apartWingSweep) {
               apartWingSweep = angle;
               apartWingSweepCnt++;
               result = YES;
            }
         }
      }

      // (4-b) Check landing gear position.  We only send out gear position as
      // an part if the gear is not up (pos != 0) or if we've previously been
      // sending the gear position (count > 0).
      {
         const double pos = av->getLandingGearPosition(); // (0% up; 100% down)
         if (pos > 0 || apartGearPosCnt > 0) {
            // Check if the pos has changed.
            if (pos != apartLandingGear) {
               apartLandingGear = pos;
               apartGearPosCnt++;
               result = YES;
            }
         }
      }

      // (4-c) Check bay door position.  We only send out bay door posiiton as
      // an part if the door is not closed (pos != 0) or if we've previously been
      // sending the door position (count > 0).
      {
         const double pos = av->getWeaponBayDoorPosition(); // % (0% closed; 100% open)
         if (pos > 0 || apartBayDoorCnt > 0) {
            // Check if the pos has changed.
            if (pos != apartBayDoor) {
               apartBayDoor = pos;
               apartBayDoorCnt++;
               result = YES;
            }
         }
      }

   }

   // ---
   // 5) Check for ground vehicle articulated and attached parts (always check this)
   // ---
   if ( player != nullptr && player->isMajorType(models::Player::GROUND_VEHICLE) ) {

      const models::GroundVehicle* gv = static_cast<const models::GroundVehicle*>(player);

      // (5-a) Send launcher elevation angle and for an attached missile
      //       (on SamVehicles and Artillery only)
      if ( gv->isClassType(typeid(models::SamVehicle)) || gv->isClassType(typeid(models::Artillery)) ) {

         const double angle = gv->getLauncherPosition();  //  (radians)

         // First pass --
         if (apartLnchrElevCnt == 0) {

            // find all missiles missiles
            const models::StoresMgr* sm = gv->getStoresManagement();
            if (sm != nullptr) {
               const base::PairStream* stores = sm->getStores();
               if (stores != nullptr) {
                  const base::List::Item* item = stores->getFirstItem();
                  while (item != nullptr && apartNumMissiles < MAX_AMSL) {
                     const auto pair = static_cast<const base::Pair*>(item->getValue());
                     if (pair != nullptr) {
                        const auto msl = dynamic_cast<const models::Missile*>( pair->object() );
                        if (msl != nullptr) {
                           // Save the pointer to the missile, set the missile's change count to 1,
                           // and up the missile count
                           msl->ref();
                           apartMsl[apartNumMissiles] = msl;
                           apartMslAttached[apartNumMissiles] = !(msl->isMode(models::Player::LAUNCHED));
                           apartMslCnt[apartNumMissiles] = 1;
                           apartNumMissiles++;
                        }
                     }
                     item = item->getNext();
                  }
                  stores->unref();
                  stores = nullptr;
               }

            }

            // If we have missile then set the launcher angle
            if (apartNumMissiles > 0) {
               apartLnchrElev = angle;
               apartLnchrElevCnt++;
            }
         }

         // If we have the launcher angle and missiles then check for changes
         if (apartLnchrElevCnt != 0) {

            // Check if the pos has changed
            if (angle != apartLnchrElev) {
               apartLnchrElev = angle;
               apartLnchrElevCnt++;
               result = YES;
            }

            // Check all missiles for change in launched status
            for (unsigned int i = 0; i < apartNumMissiles; i++) {
               bool attached = !(apartMsl[i]->isMode(models::Player::LAUNCHED));
               if (attached != apartMslAttached[i]) {
                  // There's been a change in status
                  apartMslAttached[i] = attached;
                  apartMslCnt[i]++;
               }
            }

         }

      }

   }

   // ---
   // 6) When we're a network player -- Update when the exec time of the
   //    last input (player's NIB) is different that our exec time.
   // ---
   if ( (result == UNSURE) && player->isNetworkedPlayer() ) {
      const auto playerNib = dynamic_cast<const Nib*>(player->getNib());
      if (playerNib->getTimeExec() != getTimeExec()) {
         result = YES;
      }
   }

   return (result == YES);
}
Esempio n. 18
0
int
Player::attack()
{
  PLAYER_PRINTF("I am a cool player attack!\n");
  return getDamage();
}
Esempio n. 19
0
void Muncher::attack(){
    if((target->getPosition()-position).GetLength() <= range){
        target->receiveDamage(getDamage(target), this);
    }
}
Esempio n. 20
0
void Cannon::shot(WorldObject *worldObject)
{
    world->addWorldObject(new Cannonball(pos, worldObject, getDamage()), pos);
}
void SnakeMens_Attack4::ProcessCollision(MyObject *_Obj)
{

	if(getiCollision() == true )
	{
		CRECT r;
		r.Left =m_SnakeMens_Attack4_BallInfoSprite.getX();
		r.Top = m_SnakeMens_Attack4_BallInfoSprite.getY() ;
		r.Right = r.Left+ 622;
		r.Bottom = r.Top  + 622;
		CRECT r1;
		r1.Left =m_SnakeMens_Attack4InfoSprite.getX(); ;
		r1.Top = m_SnakeMens_Attack4InfoSprite.getY() ;
		r1.Right = r1.Left+328;
		r1.Bottom = r1.Top  + 522 ;
		if(r.iCollision(_Obj->getRect())== true||r1.iCollision(_Obj->getRect())== true)
		{

			if(_Obj->getActive() == false  )
			{
				return ;
			}//true la chua trung

			EffectFont* m_EffectFont = new EffectFont(_Obj->getX(), _Obj->getY(),m_Damage);
			ManagerObject::Instance()->getListEffect()->push_back(m_EffectFont);
			EffectFrenzy* m_EffectFrenzy = new EffectFrenzy(_Obj->getX(), _Obj->getY());
			ManagerObject::Instance()->getListEffect()->push_back(m_EffectFrenzy);
// 			if (m_Direct<0)
// 			{
// 
// 				m_iCollision=false;
// 				for(int i=0;i<5;i++)
// 				{
// 					SnakeMens_Effect2 *m_SnakeMensEffect2 = new SnakeMens_Effect2(_Obj->getX()+20,_Obj->getY()+40);
// 					m_SnakeMensEffect2->m_InfoSprite.setScaleX(1);
// 					m_SnakeMensEffect2->m_InfoSprite.setXY(_Obj->getX()-50*(2-i),_Obj->getY()-150);
// 					ManagerObject::Instance()->getListEffect()->push_back(m_SnakeMensEffect2);
// 				}
// 				
// 			}
// 			else
// 			{
// 
// 				m_iCollision=false;
// 				for(int i=0;i<5;i++)
// 				{
// 				SnakeMens_Effect2 *m_SnakeMensEffect2 = new SnakeMens_Effect2(_Obj->getX()+20,_Obj->getY()+40);
// 				m_SnakeMensEffect2->m_InfoSprite.setScaleX(1);
// 				m_SnakeMensEffect2->m_InfoSprite.setXY(_Obj->getX()-50*(2-i),_Obj->getY()-150);
// 				ManagerObject::Instance()->getListEffect()->push_back(m_SnakeMensEffect2);
// 				}
// 			}

			_Obj->setActive(false);
			_Obj->setFrenzey(true);
			_Obj->setHp(_Obj->getHp() - getDamage());
			if(_Obj->getHp() <= 0)
			{
				_Obj->setLife(false); 
			}	
		}

	}
}
Esempio n. 22
0
//------------------------------------------------------------------------------
// entityStateManager() --  (Output support)
//    -- Update the entity object for this NIB(Player)
//------------------------------------------------------------------------------
bool Nib::entityStateManager(const LCreal curExecTime)
{
   bool ok = false;

   // Get the player pointer
   const Simulation::Player* player = getPlayer();
   if (player == nullptr) return ok;

   // Dummy weapon?
   const Simulation::Weapon* ww = dynamic_cast<const Simulation::Weapon*>( player );
   if (ww != nullptr) {
      if (ww->isDummy()) return ok;
   }

   if (isPlayerStateUpdateRequired(curExecTime)) {

      //
      // Send an entity state PDU
      //   1) create buffer
      //   2) set state information
      //   3) send data
      //

      // Get our NetIO and the main simulation
      NetIO* disIO = static_cast<NetIO*>(getNetIO());
      Simulation::Simulation* sim = disIO->getSimulation();

      // Capture the player data, reset the dead reckoning and
      // mark the current time.
      playerState2Nib();

      // ---
      // Create buffer and cast it as an entity state PDU
      // ---
      char pduBuffer[NetIO::MAX_PDU_SIZE];
      EntityStatePDU* pdu = (EntityStatePDU*) &pduBuffer[0];

      //
      // Entity state PDU structure
      // =========================================================
      // PDUHeader            header;
      // EntityIdentifierDIS  entityID;
      // uint8_t              forceID;
      // uint8_t              numberOfArticulationParameters;
      // EntityType           entityType;
      // EntityType           alternativeType;
      // VectorDIS            entityLinearVelocity;
      // WorldCoordinates     entityLocation;
      // EulerAngles          entityOrientation;
      // uint32_t             appearance;
      // uint8_t              deadReckoningAlgorithm;
      // uint8_t              otherParameters[15];
      // VectorDIS            DRentityLinearAcceleration;
      // AngularVelocityVectorDIS DRentityAngularVelocity;
      // EntityMarking        entityMarking;
      // uint32_t             capabilities;
      // =========================================================
      //

      // ---
      // Standard header (PDUHeader)
      // ---
      pdu->header.protocolVersion = disIO->getVersion();
      pdu->header.exerciseIdentifier = disIO->getExerciseID();
      pdu->header.PDUType = NetIO::PDU_ENTITY_STATE;
      pdu->header.protocolFamily = NetIO::PDU_FAMILY_ENTITY_INFO;
      //
      if (disIO->getTimeline() == Simulation::NetIO::UTC)
         pdu->header.timeStamp = disIO->makeTimeStamp( getTimeUtc(), true );
      else
         pdu->header.timeStamp = disIO->makeTimeStamp( getTimeExec(), false );
      //
      pdu->header.status = 0;
      pdu->header.padding = 0;

      // ---
      // Entity ID (EntityIdentifierID)
      // ---
      pdu->entityID.simulationID.siteIdentification = getSiteID();
      pdu->entityID.simulationID.applicationIdentification = getApplicationID();
      pdu->entityID.ID = getPlayerID();

      // ---
      // Force ID: When mapping Player side to force IDs ...
      // ---
      if (getSide() == Simulation::Player::BLUE) {
         // blue's are friendly, ...
         pdu->forceID = NetIO::FRIENDLY_FORCE;
      }
      else if (getSide() == Simulation::Player::RED) {
         // red's are not, ...
         pdu->forceID = NetIO::OPPOSING_FORCE;
      }
      else if (getSide() == Simulation::Player::WHITE) {
         // white is neutral, ...
         pdu->forceID = NetIO::NEUTRAL_FORCE;
      }
      else {
         // and everyone else is type OTHER.
         pdu->forceID = NetIO::OTHER_FORCE;
      }

      // ---
      // Entity type (EntityType)
      // ---
      pdu->entityType.kind                 = getEntityKind();
      pdu->entityType.domain               = getEntityDomain();
      pdu->entityType.country              = getEntityCountry();
      pdu->entityType.category             = getEntityCategory();
      pdu->entityType.subcategory          = getEntitySubcategory();
      pdu->entityType.specific             = getEntitySpecific();
      pdu->entityType.extra                = getEntityExtra();
      // ---
      // Alternative type (EntityType)
      // ---
      pdu->alternativeType.kind            = getEntityKind();
      pdu->alternativeType.domain          = getEntityDomain();
      pdu->alternativeType.country         = getEntityCountry();
      pdu->alternativeType.category        = getEntityCategory();
      pdu->alternativeType.subcategory     = getEntitySubcategory();
      pdu->alternativeType.specific        = getEntitySpecific();
      pdu->alternativeType.extra           = getEntityExtra();

      // ---
      // Player position and orientation state data data
      // 1) All data is geocentric (ECEF)
      // 2) The playerState2Nib() function, which was called above, captures
      //    the state data and passed the state data to the dead reckoning
      //    system, and we're using this DR captured data.
      // ---
      {
         // ---
         // Entity linear velocity (VectorDIS)
         // ---
         osg::Vec3d geocVel = getDrVelocity();
         pdu->entityLinearVelocity.component[0] = static_cast<float>(geocVel[0]);
         pdu->entityLinearVelocity.component[1] = static_cast<float>(geocVel[1]);
         pdu->entityLinearVelocity.component[2] = static_cast<float>(geocVel[2]);

         // ---
         // Entity location (WorldCoordinates)
         // ---
         osg::Vec3d geocPos = getDrPosition();
         pdu->entityLocation.X_coord = geocPos[Basic::Nav::IX];
         pdu->entityLocation.Y_coord = geocPos[Basic::Nav::IY];
         pdu->entityLocation.Z_coord = geocPos[Basic::Nav::IZ];

         // ---
         // Entity orientation (EulerAngles)
         // ---
         osg::Vec3d geocAngles = getDrEulerAngles();
         pdu->entityOrientation.phi   = static_cast<float>(geocAngles[Basic::Nav::IPHI]);
         pdu->entityOrientation.theta = static_cast<float>(geocAngles[Basic::Nav::ITHETA]);
         pdu->entityOrientation.psi   = static_cast<float>(geocAngles[Basic::Nav::IPSI]);
      }

      // ---
      // Appearance bits generic to all domains (except munitions)
      // ---
      {
         pdu->appearance = 0x0;

         // ---
         // Frozen?
         // ---
         if ( isFrozen() || sim->isFrozen() ) {
            pdu->appearance |= FROZEN_BIT;
         }

         // Deactive this entity?
         {
            if (isMode(Simulation::Player::DELETE_REQUEST) || player->isDead() )
               pdu->appearance |= DEACTIVATE_BIT;
         }


         // Damage or health?  (Bits 3-4)
         {
            unsigned int bits = 0;
            if (getDamage() > 0.9f) bits = 3;       // Destroyed or Fatality
            else if (getDamage() > 0.5) bits = 2;   // Moderate
            else if (getDamage() > 0.0) bits = 1;   // Slight
            else bits = 0;                          // None
            pdu->appearance |= (bits << 3);
         }


         // Camouflage type
         // Note: air platform appearance bits 17 and 18 are not used, but we're using them the same as land platforms
         {
            unsigned int bits = getCamouflageType();
            if (bits > 0 && bits <= 4) {
               pdu->appearance |= CAMOUFLAGE_BIT;

               // Land based camouflage bits
               if (player->isMajorType(Simulation::Player::GROUND_VEHICLE)) {
                  // Subtract one to match DIS camouflage bits.
                  // Our camouflage type for DIS is the camouflage appearance bits
                  // plus one because our camouflage type of zero is no camouflage.
                  bits--;
                  pdu->appearance |= (bits << 17);
               }
            }
         }

         // Life forms appearance bits
         if (player->isMajorType(Simulation::Player::LIFE_FORM)) {
            const Simulation::LifeForm* lf = dynamic_cast<const Simulation::LifeForm*>(player);
            if (lf != nullptr) {
               // Health (aka damaged for other domains) same bits (3-4) - this is from the NIB, because it IS
               // updated
               // bits 5-8 compliance (not implemented)
               // bits 9 - 11 unused
               // bit 12 flashlight (not implemented)
               // bits 13-15 unused
               // bits 16 - 19 life form state
               // data is from the player, because NIB doesn't have actions associated with it
               {
                  unsigned int bits = 1;      // upright, standing still
                  if (lf->getActionState() == Simulation::LifeForm::UPRIGHT_STANDING) bits = 1;       // standing
                  else if (lf->getActionState() == Simulation::LifeForm::UPRIGHT_WALKING) bits = 2;   // walking
                  else if (lf->getActionState() == Simulation::LifeForm::UPRIGHT_RUNNING) bits = 3;   // running
                  else if (lf->getActionState() == Simulation::LifeForm::KNEELING) bits = 4;          // kneeling
                  else if (lf->getActionState() == Simulation::LifeForm::PRONE) bits = 5;             // prone
                  else if (lf->getActionState() == Simulation::LifeForm::CRAWLING) bits = 6;          // crawling
                  else if (lf->getActionState() == Simulation::LifeForm::SWIMMING) bits = 7;          // swimming
                  else if (lf->getActionState() == Simulation::LifeForm::PARACHUTING) bits = 8;       // parachuting
                  else if (lf->getActionState() == Simulation::LifeForm::JUMPING) bits = 9;           // jumping
                  else if (lf->getActionState() == Simulation::LifeForm::SITTING) bits = 10;          // sitting
                  else if (lf->getActionState() == Simulation::LifeForm::SQUATTING) bits = 11;        // squatting
                  else if (lf->getActionState() == Simulation::LifeForm::CROUCHING) bits = 12;        // crouching
                  else if (lf->getActionState() == Simulation::LifeForm::WADING) bits = 13;           // wading
                  else if (lf->getActionState() == Simulation::LifeForm::SURRENDER) bits = 14;        // surrender
                  else if (lf->getActionState() == Simulation::LifeForm::DETAINED) bits = 15;         // detained
                  else bits = 1;
                  pdu->appearance |= (bits << 16);
               }
               // bit 20 unused
               // bit 21 frozen status (taken care of above)
               // bits 24 - 25 weapon 1 (not implemented)
               // bits 26-27 weapon 2 (N/I)
               // bits 28-29
            }
         }

         // Common Non-life form appearance bits
         else {

            // Smoking?  (Bits 5-6) Standard (IST-CF-03-01, May 5, 2003)
            {
               unsigned int bits = 0;
               if (getSmoke() > 0.9f) bits = 3;
               else if (getSmoke() > 0.5) bits = 2;
               else if (getSmoke() > 0.0) bits = 1;
               else bits = 0;
               pdu->appearance |= (bits << 5);
            }

            // Flames? (Bit 15) Standard (IST-CF-03-01, May 5, 2003)
            {
               if (getFlames() > 0.5f)
                  pdu->appearance |= FLAMES_BIT;
            }

            // Power plant status bit (just leave ON for now)
            pdu->appearance |= POWER_PLANT_BIT;
         }


      }

      // ---
      // Dead reckoning algorithm
      // ---
      pdu->deadReckoningAlgorithm = static_cast<unsigned char>(getDeadReckoning());

      // ---
      // Other parameters
      // ---
      for (unsigned int i=0; i<15; i++) {
          pdu->otherParameters[i] = 0;
      }

      // ---
      // Dead reckoning information
      // ---
      {
         // ---
         // Dead reckoning linear acceleration (VectorDIS)
         // ---
         osg::Vec3d geocAcc = getDrAcceleration();
         pdu->DRentityLinearAcceleration.component[0] = static_cast<float>(geocAcc[0]);
         pdu->DRentityLinearAcceleration.component[1] = static_cast<float>(geocAcc[1]);
         pdu->DRentityLinearAcceleration.component[2] = static_cast<float>(geocAcc[2]);

         // ---
         // Dead reckoning angular velocity (AngularVelocityVectorDIS)
         // ---
         osg::Vec3d geocAngVel = getDrAngularVelocities();
         pdu->DRentityAngularVelocity.x_axis = static_cast<float>(geocAngVel[Basic::Nav::IX]);
         pdu->DRentityAngularVelocity.y_axis = static_cast<float>(geocAngVel[Basic::Nav::IY]);
         pdu->DRentityAngularVelocity.z_axis = static_cast<float>(geocAngVel[Basic::Nav::IZ]);
      }

      // ---
      // Entity marking (EntityMarking)
      // ---
      {
         const char* const pName = getPlayerName();
         size_t nameLen = std::strlen(pName);
         for (unsigned int i = 0; i < EntityMarking::BUFF_SIZE; i++) {
            if (i < nameLen) {
               pdu->entityMarking.marking[i] = pName[i];
            }
            else {
               pdu->entityMarking.marking[i] = '\0';
            }
         }
         pdu->entityMarking.characterSet = 1;
      }

      // ---
      // Capabilities
      // ---
      pdu->capabilites = 0x0;

      // ---
      // Articulation parameters
      // ---
      pdu->numberOfArticulationParameters = manageArticulationParameters(pdu);

      // Size of the PDU package
      unsigned short length = sizeof(EntityStatePDU) + (pdu->numberOfArticulationParameters * sizeof(VpArticulatedPart));
      pdu->header.length = length;

      if (Basic::NetHandler::isNotNetworkByteOrder()) pdu->swapBytes();
      ok = disIO->sendData( reinterpret_cast<char*>(pdu), length );
   }
   return ok;
}
void LifeForm::look(const LCreal up, const LCreal sdws)
{
    if (getDamage() < 1) {
        if (lockMode != LOCKED) {
            lockMode = SEARCHING;
            // our up and sideways come in as -5 to 5, which is a rate to adjust heading
            const osg::Vec3 old = getEulerAngles();
            LCreal hdg = old.z();
            LCreal ptc = lookAngle;
            LCreal tempSdws = sdws;
            LCreal tempUp = up;
            if (lcAbs(tempSdws) < 0.00005) tempSdws = 0;
            if (lcAbs(tempUp) < 0.05) tempUp = 0;
            hdg += tempSdws;
            hdg = lcAepcRad(hdg);
            // we don't change our pitch when we look up and down, we only change our look angle, so we have to keep
            // that separate.  WE do, however, change our heading based on where we are looking, so that is correct
            ptc += tempUp;
            if (ptc > 90) ptc = 90;
            else if (ptc < -90) ptc = -90;
            //std::cout << "HEADING = " << hdg << std::endl;
            setLookAngle(ptc);
            osg::Vec3 eul(0, 0, hdg);
            setEulerAngles(eul);
            // now based on this we need to know if we have a target in our crosshairs...
            tgtAquired = false;
            if (tgtPlayer != nullptr) tgtPlayer->unref();
            tgtPlayer = nullptr;
            const osg::Vec3 myPos = getPosition();
            osg::Vec3 tgtPos;
            osg::Vec3 vecPos;
            LCreal az = 0.0, el = 0.0, range = 0.0, diffAz = 0.0, diffEl = 0.0;
            const LCreal maxAz = (0.7f * static_cast<LCreal>(Basic::Angle::D2RCC));
            const LCreal maxEl = (0.7f * static_cast<LCreal>(Basic::Angle::D2RCC));
            //LCreal maxRange = 1500.0f; // long range right now
            const LCreal la = lookAngle * static_cast<LCreal>(Basic::Angle::D2RCC);
            Simulation* sim = getSimulation();
            if (sim != nullptr) {
                Basic::PairStream* players = sim->getPlayers();
                if (players != nullptr) {
                    Basic::List::Item* item = players->getFirstItem();
                    while (item != nullptr && !tgtAquired) {
                        Basic::Pair* pair = static_cast<Basic::Pair*>(item->getValue());
                        if (pair != nullptr) {
                            Player* player = dynamic_cast<Player*>(pair->object());
                            if (player != nullptr && player != this && !player->isMajorType(WEAPON) && !player->isDestroyed()) {
                                // ok, calculate our position from this guy
                                tgtPos = player->getPosition();
                                vecPos = tgtPos - myPos;
                                az = lcAtan2(vecPos.y(), vecPos.x());
                                range = (vecPos.x() * vecPos.x() + vecPos.y() * vecPos.y());
                                range = std::sqrt(range);
                                // now get our elevation
                                el = lcAtan2(-vecPos.z(), range);
                                diffAz = lcAbs(lcAepcRad(az - static_cast<LCreal>(getHeadingR())));
                                diffEl = lcAbs(lcAepcRad(la - el));
                                if ((diffAz <= maxAz) && (diffEl <= maxEl)) {
                                    lockMode = TGT_IN_SIGHT;
                                    tgtAquired = true;
                                    if (tgtPlayer != player) {
                                        if (tgtPlayer != nullptr) tgtPlayer->unref();
                                        tgtPlayer = player;
                                        tgtPlayer->ref();
                                    }
                                }
                            }
                        }
                        item = item->getNext();
                    }
                    players->unref();
                    players = nullptr;
                }
            }
        }
        // else we are locking on target, and need to follow our target player
        else {
            if (tgtPlayer == nullptr) lockMode = SEARCHING;
            else {
                const osg::Vec3 vecPos = tgtPlayer->getPosition() - getPosition();
                const LCreal az = lcAtan2(vecPos.y(), vecPos.x());
                LCreal range = (vecPos.x() * vecPos.x() + vecPos.y() * vecPos.y());
                range = std::sqrt(range);
                // now get our elevation
                const LCreal el = lcAtan2(-vecPos.z(), range);
                // now force that on us
                setLookAngle(el * static_cast<LCreal>(Basic::Angle::R2DCC));
                setEulerAngles(0, 0, az);
            }
        }
    }
}