本文整理汇总了C++中BaseGameEntity类的典型用法代码示例。如果您正苦于以下问题:C++ BaseGameEntity类的具体用法?C++ BaseGameEntity怎么用?C++ BaseGameEntity使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了BaseGameEntity类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: update
void EntityManager::update(float dt) {
CCArray *keys = m_pIDToEntitiesMap->allKeys();
if (keys) { // if the dictionary has no objects, keys will be NULL
for (int i=0; i<keys->count(); i++) {
CCInteger *integer = (CCInteger *)keys->objectAtIndex(i);
int key = integer->getValue();
BaseGameEntity *entity = (BaseGameEntity *)m_pIDToEntitiesMap->objectForKey(key);
if (entity->getIsActive()) { // Only update the entity if it's active.
entity->update(dt);
}
}
}
/*
// Add new entities.
for (int i=0; i<m_pEntitiesToAdd->count(); i++) {
BaseGameEntity *newEntity = (BaseGameEntity *)m_pEntitiesToAdd->objectAtIndex(i);
m_pIDToEntitiesMap->setObject(newEntity, newEntity->getID());
}
m_pEntitiesToAdd->removeAllObjects();
*/
// Remove old entities.
for (int i=0; i<m_pEntitiesToRemove->count(); i++) {
BaseGameEntity *oldEntity = (BaseGameEntity *)m_pEntitiesToRemove->objectAtIndex(i);
m_pIDToEntitiesMap->removeObjectForKey(oldEntity->getID());
}
m_pEntitiesToRemove->removeAllObjects();
}
示例2: while
//---------------------- DispatchDelayedMessages -------------------------
//
// This function dispatches any telegrams with a timestamp that has
// expired. Any dispatched telegrams are removed from the queue
//------------------------------------------------------------------------
void MessageDispatcher::DispatchDelayedMessages()
{
//first get current time
double CurrentTime = TickCounter->GetCurrentFrame();
//now peek at the queue to see if any telegrams need dispatching.
//remove all telegrams from the front of the queue that have gone
//past their sell by date
while( !PriorityQ.empty() &&
(PriorityQ.begin()->DispatchTime < CurrentTime) &&
(PriorityQ.begin()->DispatchTime > 0) )
{
//read the telegram from the front of the queue
const Telegram& telegram = *PriorityQ.begin();
//find the recipient
BaseGameEntity* pReceiver = EntityMgr->GetEntityFromID(telegram.Receiver);
#ifdef SHOW_MESSAGING_INFO
debug_con << "\nQueued telegram ready for dispatch: Sent to "
<< pReceiver->ID() << ". Msg is "<< telegram.Msg << "";
#endif
//send the telegram to the recipient
Discharge(pReceiver, telegram);
//remove it from the queue
PriorityQ.erase(PriorityQ.begin());
}
}
示例3: while
//---------------------- DispatchDelayedMessages -------------------------
//
// This function dispatches any telegrams with a timestamp that has
// expired. Any dispatched telegrams are removed from the queue
//------------------------------------------------------------------------
void MessageDispatcher::DispatchDelayedMessages()
{
// cout << "\nDispatch Delayed Message";
//first get current time
double CurrentTime = Clock->GetCurrentTime();
//cout << "\nCurrent time" << CurrentTime;
//now peek at the queue to see if any telegrams need dispatching.
//remove all telegrams from the front of the queue that have gone
//past their sell by date
/*if(!PriorityQ.empty()){
cout << "\nDispatch time" << PriorityQ.begin()->DispatchTime;
}*/
while( !PriorityQ.empty() &&
(PriorityQ.begin()->DispatchTime < CurrentTime) &&
(PriorityQ.begin()->DispatchTime > 0) )
{
//read the telegram from the front of the queue
const Telegram& telegram = *PriorityQ.begin();
//find the recipient
BaseGameEntity* pReceiver = EntityMgr->GetEntityFromID(telegram.Receiver);
cout << "\nQueued telegram ready for dispatch: Sent to "
<< GetNameOfEntity(pReceiver->ID()) << ". Msg is " << MsgToStr(telegram.Msg);
//send the telegram to the recipient
Discharge(pReceiver, telegram);
//remove it from the queue
PriorityQ.erase(PriorityQ.begin());
}
}
示例4: Animate
void
StateZombieChase::Execute(Zombie* pZombie, u32 elapsedTime)
{
Animate(pZombie, elapsedTime);
//--------------------------------------------
//
// use physics model for executing
//
//--------------------------------------------
// find target object
ZombiePhysics* pPhysicsModel = pZombie->GetPhysicsModel();
pPhysicsModel->ResetTarget();
vector2df me(pZombie->Pos().X,pZombie->Pos().Y);
std::vector<BaseGameEntity*> enties = EntityMgr.GetEntityListFromGroupID(ENTITY_TYPE_HUMAN);
bool isTarget = false;
for (std::vector<BaseGameEntity*>::iterator iter = enties.begin(); iter != enties.end(); iter++)
{
// find out close human, but now just get first human....
BaseGameEntity* pEntity = *iter;
f32 collisiondistance = me.getDistanceFrom(vector2df(pEntity->Pos().X, pEntity->Pos().Y));
if(RANGE_ZOMBIE_TARGET_RECOGNITION >= collisiondistance)//ÀÎ½Ä ¹üÀ§ ¾È¿¡¼ ÀÖ´ÂÁö?
{
if(RANGE_ZOMBIE_ATTACKMEELE_RECOGNITION >= collisiondistance)//¸Â ´ê¾Æ¼ attack mode·Î º¯°æ
{
pZombie->GetFSM()->ChangeState(StateZombieAttackBite::Instance());
isTarget = true;
break;
}
else//¾ÆÁ÷ Á»ºñ°¡ °ø°ÝÇÒ Á¤µµ·Î °¡±õÁö ¾ÊÀ½
{
pPhysicsModel->SetTarget(b2Vec2(pEntity->Pos().X, pEntity->Pos().Y));
isTarget = true;
break;
}
}
}
if(!isTarget)//Ÿ°ÙÀ» †õÄ¡¸é ´Ù½Ã roam »óÅ·Î
{
//°Ë»ö µÇ¸é ÃßÀû ½ºÅ×ÀÌÆ®·Î º¯½Å
pZombie->GetPhysicsModel()->GetBody()->m_maxForwardSpeed = ZOMBIE_ROAMSTATE_PHYSICS_MAX_FORWARDSPEED;
pZombie->GetPhysicsModel()->GetBody()->m_maxDriveForce = ZOMBIE_ROAMSTATE_PHYSICS_MAX_FRONTFORCE;
//RAN_LOG("Zombie[chase] changestate - Roam");
pZombie->GetFSM()->ChangeState(StateZombieRoam::Instance());
}
pPhysicsModel->Update(elapsedTime);
//--------------------------------------------
//
// apply executed result to object property
//
//--------------------------------------------
b2Vec2 vec = pZombie->GetPhysicsModel()->GetPosition();
f32 angle = pZombie->GetPhysicsModel()->GetAngle();
pZombie->SetPos(vector3df(vec.x, vec.y, 0));
pZombie->SetRotation(vector3df(0.f, 0.f, ANGLE_TO_RADIAN(angle)));
}
示例5: CohesionPlus
//-------------------------------- Cohesion ------------------------------
//
// returns a steering force that attempts to move the agent towards the
// center of mass of the agents in its immediate area
//
// USES SPACIAL PARTITIONING
//------------------------------------------------------------------------
Vector2D SteeringBehavior::CohesionPlus(const vector<Vehicle*> &neighbors)
{
//first find the center of mass of all the agents
Vector2D CenterOfMass, SteeringForce;
int NeighborCount = 0;
//iterate through the neighbors and sum up all the position vectors
for (BaseGameEntity* pV = m_pVehicle->World()->CellSpace()->begin();
!m_pVehicle->World()->CellSpace()->end();
pV = m_pVehicle->World()->CellSpace()->next())
{
//make sure *this* agent isn't included in the calculations and that
//the agent being examined is close enough
if (pV != m_pVehicle)
{
CenterOfMass += pV->Pos();
++NeighborCount;
}
}
if (NeighborCount > 0)
{
//the center of mass is the average of the sum of positions
CenterOfMass /= (double)NeighborCount;
//now seek towards that position
SteeringForce = Seek(CenterOfMass);
}
//the magnitude of cohesion is usually much larger than separation or
//allignment so it usually helps to normalize it.
return Vec2DNormalize(SteeringForce);
}
示例6: enter
void HeroHurt::enter(Hero *object)
{
// 面向对你造成伤害者
int entity_id = object->getStateMachine()->userdata().hurt_source;
BaseGameEntity *entity = object->getEntityManger()->getEntityByID(entity_id);
if (entity != nullptr)
{
if (entity->getPositionX() < object->getPositionX())
{
object->setDirection(BaseGameEntity::kLeftDirection);
}
else
{
object->setDirection(BaseGameEntity::kRightDirection);
}
}
system_clock::time_point current_time = system_clock::now();
system_clock::time_point last_hurt_time = object->getStateMachine()->userdata().was_hit_time;
system_clock::duration duration = current_time - last_hurt_time;
if (duration_cast<milliseconds>(duration).count() < 1000)
{
++object->getStateMachine()->userdata().was_hit_count;
}
else
{
object->getStateMachine()->userdata().was_hit_count = 1;
}
if (object->getStateMachine()->userdata().was_hit_count < 3)
{
Animation *animation = AnimationManger::instance()->getAnimation("hero_hurt");
Animate *animate = Animate::create(animation);
animate->setTag(ActionTags::kHeroHurt);
object->runAction(animate);
object->getStateMachine()->userdata().was_hit_time = system_clock::now();
}
else
{
object->getStateMachine()->change_state(HeroKnockout::instance());
}
if (object->hasWeapon())
{
auto current_level = object->getEntityManger()->getCurrentLevel();
current_level->dropWeapon(object);
}
}
示例7: Execute
void RabbitWanderingState::Execute(Rabbit* rabbit)
{
Node* current = rabbit->GetPosition();
Node* next = current->GetEdges()[Random::Next(0, current->GetEdges().size() - 1)]->child;
if (next->ContainsEntity("Pill")) {
BaseGameEntity *pill = next->ContainsEntity("Pill");
next->RemoveEntity(pill);
Node *random = rabbit->GetGraph()->GetRandomNode(next);
random->AddEntity(pill);
pill->SetPosition(random);
rabbit->GetFSM()->ChangeState(RabbitSleepingState::Instance());
}
rabbit->MoveTo(next);
}
示例8: Execute
void RabbitSearchPillState::Execute(Rabbit* rabbit)
{
Node* current = rabbit->GetPosition();
Node* next = current->GetEdges()[Random::Next(0, current->GetEdges().size() - 1)]->child;
if (next->ContainsEntity("Pill")) {
BaseGameEntity *pill = next->ContainsEntity("Pill");
next->RemoveEntity(pill);
pill->SetPosition(nullptr);
rabbit->Pickup(static_cast<GameItem*>(pill));
printf("Rabbit: picked up pill\n");
rabbit->GetFSM()->ChangeState(RabbitWanderingState::Instance());
}
rabbit->MoveTo(next);
}
示例9: Animate
void
ChaseGroupState::Execute(ChaserPlayer* pPlayer, u32 elapsedTime)
{
//sk
//충돌 처리를 여기 넣는게 맞나?? - 현재 정의된 어떤 상태이든 총알에 영향을 받기 때문에
//충돌 테스트 - 나중에 독립된 함수로 분리
std::vector<BaseGameEntity*> vec = EntityMgr.GetCollidedEntites(pPlayer);
if(vec.size() > 0)
{
//if there is bullet, chaser state should be changed.
std::vector<BaseGameEntity*>::iterator iter;
for (iter = vec.begin(); iter != vec.end(); iter++)
{
BaseGameEntity* pEntity = *iter;
if(pEntity->Name() == "Bullet")
{
pPlayer->GetFSM()->ChangeState(ChaseDeadState::Instance());
return;
}
}
}
Animate(pPlayer, elapsedTime);
//플레이어를 향해 가도록 설정
//*/
//BaseGameEntity* pTargetEntity = EntityMgr.GetEntityFromID(12);
//주인공 케릭터를 얻어오는 방식이 수정되어야 함. 현재 id로 얻어 오는 방식은 ID가 계속 변하기 때문에 의미가 없음.
std::vector<BaseGameEntity*> fugivevec = EntityMgr.GetEntityListFromGroupID(100);
BaseGameEntity* pTargetEntity = fugivevec[0];//
vector3df forwardobject = pTargetEntity->Pos()-pPlayer->Pos();
pPlayer->SetPos(pPlayer->m_myAI.ObjectFlokcing(pPlayer->Pos(),pPlayer->Velocity(), pPlayer->MaxSpeed() ,
elapsedTime,forwardobject.normalize(),pPlayer->m_uGroupID,pPlayer));
/*/테스트용 patrol
pPlayer->SetPos(pPlayer->m_myAI.ObjectFlokcing(pPlayer->Pos(),pPlayer->Velocity(), pPlayer->MaxSpeed() ,
elapsedTime,pPlayer->Heading(),pPlayer->m_uGroupID,pPlayer));
//*/
//end sk
}
示例10:
//--------------------- GetPosOfClosestSwitch -----------------------------
//
// returns the position of the closest visible switch that triggers the
// door of the specified ID
//-----------------------------------------------------------------------------
Vector2D
Raven_Game::GetPosOfClosestSwitch(Vector2D botPos, unsigned int doorID)const
{
std::vector<unsigned int> SwitchIDs;
//first we need to get the ids of the switches attached to this door
std::vector<Raven_Door*>::const_iterator curDoor;
for (curDoor = m_pMap->GetDoors().begin();
curDoor != m_pMap->GetDoors().end();
++curDoor)
{
if ((*curDoor)->ID() == doorID)
{
SwitchIDs = (*curDoor)->GetSwitchIDs(); break;
}
}
Vector2D closest;
double ClosestDist = MaxDouble;
//now test to see which one is closest and visible
std::vector<unsigned int>::iterator it;
for (it = SwitchIDs.begin(); it != SwitchIDs.end(); ++it)
{
BaseGameEntity* trig = EntityMgr->GetEntityFromID(*it);
if (isLOSOkay(botPos, trig->Pos()))
{
double dist = Vec2DDistanceSq(botPos, trig->Pos());
if ( dist < ClosestDist)
{
ClosestDist = dist;
closest = trig->Pos();
}
}
}
return closest;
}
示例11: switch
bool Projectile::handleMessage(const Telegram *telegram) {
switch (telegram->message) {
case kMessageReachPosition:
reset();
return true;
case kMessageCollide:
BaseGameEntity *entity = GameModel::instance()->getEntityForID(telegram->sender);
if (arc4random()%10 > 3) {
return false;
}
if (entity->getEntityType() == kFighter && entity->getController() != m_eController) {
MessageDispatcher::instance()->dispatchMessage(0, m_uID, entity->getID(), kMessageHit, (void *)&m_iDamage);
reset();
return true;
}
return false;
}
return false;
}
示例12: if
void
IdleCamera::Execute(BaseCamera* pCamera, u32 elapsedTime)
{
// follow target
int id = pCamera->GetTargetEntityID();
if (id < 0)
{
return;
}
BaseGameEntity* pTargetEntity = EntityMgr.GetEntityFromID(id);
vector3df targetPos = pTargetEntity->Pos();
vector3df newPos = vector3df(targetPos.X, targetPos.Y, pCamera->Pos().Z);
static EventReceiver* pEventReceiver = &(EventRcv);
/*if (pEventReceiver->IsKeyDown(KEY_KEY_W))
{
pEventReceiver->SetKeyDown(KEY_KEY_W, false);
newPos.Z += 10.0f;
if (0 <= newPos.Z)
{
newPos.Z = -10.f;
}
}
else if (pEventReceiver->IsKeyDown(KEY_KEY_S))
{
pEventReceiver->SetKeyDown(KEY_KEY_S, false);
newPos.Z -= 10.0f;
}*/
//pCamera->SetDestPos(newPos, true);
pCamera->SetPos(newPos);
pCamera->SetLookAt(vector3df(newPos.X, newPos.Y, targetPos.Z));
}
示例13: SeparationPlus
//---------------------------- Separation --------------------------------
//
// this calculates a force repelling from the other neighbors
//
// USES SPACIAL PARTITIONING
//------------------------------------------------------------------------
Vector2D SteeringBehavior::SeparationPlus(const vector<Vehicle*> &neighbors)
{
Vector2D SteeringForce;
//iterate through the neighbors and sum up all the position vectors
for (BaseGameEntity* pV = m_pVehicle->World()->CellSpace()->begin();
!m_pVehicle->World()->CellSpace()->end();
pV = m_pVehicle->World()->CellSpace()->next())
{
//make sure this agent isn't included in the calculations and that
//the agent being examined is close enough
if (pV != m_pVehicle)
{
Vector2D ToAgent = m_pVehicle->Pos() - pV->Pos();
//scale the force inversely proportional to the agents distance
//from its neighbor.
SteeringForce += Vec2DNormalize(ToAgent) / ToAgent.Length();
}
}
return SteeringForce;
}
示例14: SetTextColor
//---------------------------- DispatchMessage ---------------------------
//
// given a message, a receiver, a sender and any time delay , this function
// routes the message to the correct agent (if no delay) or stores
// in the message queue to be dispatched at the correct time
//------------------------------------------------------------------------
void MessageDispatcher::DispatchMessage(double delay,
int sender,
int receiver,
int msg,
void* ExtraInfo)
{
SetTextColor(BACKGROUND_RED|FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE);
//get pointers to the sender and receiver
BaseGameEntity* pSender = EntityMgr->GetEntityFromID(sender);
BaseGameEntity* pReceiver = EntityMgr->GetEntityFromID(receiver);
//make sure the receiver is valid
if (pReceiver == NULL)
{
cout << "\nWarning! No Receiver with ID of " << receiver << " found";
return;
}
//create the telegram
Telegram telegram(0, sender, receiver, msg, ExtraInfo);
//if there is no delay, route telegram immediately
if (delay <= 0.0f)
{
SetTextColor(BACKGROUND_RED|FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE);
cout << "\nInstant telegram dispatched at time: " << Clock->GetCurrentTime()
<< " by " << GetNameOfEntity(pSender->ID()) << " for " << GetNameOfEntity(pReceiver->ID())
<< ". Msg is "<< MsgToStr(msg);
//send the telegram to the recipient
Discharge(pReceiver, telegram);
}
//else calculate the time when the telegram should be dispatched
else
{
double CurrentTime = Clock->GetCurrentTime();
telegram.DispatchTime = CurrentTime + delay;
//and put it in the queue
PriorityQ.insert(telegram);
SetTextColor(BACKGROUND_RED|FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE);
cout << "\nDelayed telegram from " << GetNameOfEntity(pSender->ID()) << " recorded at time "
<< Clock->GetCurrentTime() << " for " << GetNameOfEntity(pReceiver->ID())
<< ". Msg is "<< MsgToStr(msg);
}
}
示例15: GetFSM
bool
Human::Update(u32 elapsedTime)
{
//--------------------------------------------
//
// update entity
//
//--------------------------------------------
MovingEntity::Update(elapsedTime);
#ifdef HUMAN_AILEVEL_STARVATION_SYSTEM
//effect which are applied independently of state
if(m_fCurrentLifeEnergy>0)
m_fCurrentLifeEnergy-= (elapsedTime * HUMAN_ENERGYDECREASE_PER_MILLISECOND);
else
m_fCurrentLifeEnergy=0;
if(m_fCurrentLifeEnergy < HUMAN_THRESHOLD_TO_STARVATION &&
this-> m_State != HUMAN_STATE_STARVATION &&
this-> m_State != HUMAN_STATE_DEATH){
m_State = HUMAN_STATE_STARVATION;
GetFSM()->ChangeState(StateHumanStarvation::Instance());
}
#endif
#ifdef HUMAN_AILEVEL_EAT_SYSTEM
vector2df me(this->Pos().X,this->Pos().Y);
std::vector<BaseGameEntity*> enties = EntityMgr.GetEntityListFromGroupID(ENTITY_TYPE_ITEM_FOOD);
//bool isTarget = false;
for (std::vector<BaseGameEntity*>::iterator iter = enties.begin(); iter != enties.end(); iter++)
{
// find out close human, but now just get first human....
BaseGameEntity* pEntity = *iter;
f32 collisiondistance = me.getDistanceFrom(vector2df(pEntity->Pos().X, pEntity->Pos().Y));
if(RANGE_HUMAN_EAT_RECOGNITION >= collisiondistance)
{
//식량 섭취
m_fCurrentLifeEnergy = HUMAN_MAX_LIFE_ENERGY_DEFAULT;
HumanPhysics* pPhysicsModel = this->GetPhysicsModel();
pPhysicsModel->ResetTarget();
GetFSM()->ChangeState(StateHumanHide::Instance());
//해당 아이템에 소멸 메세지 전달
int idfood = pEntity->ID();
Dispatcher->DispatchMsg(SEND_MSG_IMMEDIATELY, // time delay
ID(), // ID of sender
idfood, // ID of recipient
MSG_TYPE_FOOD_DISAPPEAR, // the message
NO_ADDITIONAL_INFO);
//((BaseItem*)pEntity)->GetFSM()->ChangeState(StateBaseItemDisappear::Instance());
break;
}
}
#endif
if (m_pStateMachine)
{
m_pStateMachine->Update(elapsedTime);
}
//이전 프레임의 위치가 필요하므로 저장한다.(업데이트 되기전의 이전 좌표)
m_VecTemporayPos.X = Pos().X;
m_VecTemporayPos.Y = Pos().Y;
//--------------------------------------------
//
// sync property with scene node
//
//--------------------------------------------
if (m_p2DSprite)
{
m_p2DSprite->setPosition(Pos());
}
return this->IsAlived();
}