Пример #1
0
/*virtual*/ void CEarthBoss::HandleEvent(CEvent* pEvent)
{
	if (pEvent->GetEventID() == "New_Player")
		SetTarget((CEntity*)(pEvent->GetParam()));
	if (pEvent->GetDestination() == this)
	{
		if (pEvent->GetEventID() == "ModifyHealth")
			ModifyHealth( *(int*)(pEvent->GetParam()) );
		if (pEvent->GetDestination() == this && pEvent->GetEventID() == "Set_State")
			m_pEState->SetState((CEntityState::ENTITY_STATE)(int)(pEvent->GetParam()) );
		if (pEvent->GetDestination() == this && pEvent->GetEventID() == "Dodge_Pitfall")
			HandleCollision((const IEntity*)pEvent->GetSender(), *(const RECT*)pEvent->GetParam());
		if (pEvent->GetDestination() == this && pEvent->GetEventID() == "Kill_Self")
		{
			CRemoveEntityMessage* pDestroyMsg = new CRemoveEntityMessage(this);
			CSGD_MessageSystem::GetInstance()->SendMsg(pDestroyMsg);
			pDestroyMsg = nullptr;
		}
		if (pEvent->GetEventID() == "Self Destruct")
		{
			CRemoveEntityMessage* pMsg = new CRemoveEntityMessage(this);
			CSGD_MessageSystem::GetInstance()->SendMsg(pMsg);
			pMsg = nullptr;

			CDropEXPMessage* free_money = new CDropEXPMessage(m_nExpPts);
			CSGD_MessageSystem::GetInstance()->SendMsg(free_money);
			free_money = nullptr;
		}
	}
}
Пример #2
0
void Map::Update()
{
	for (std::vector<Entity*>::iterator it = entities.begin(); it != entities.end();)
	{
		if ((*it)->active)
			++it;
		else {
			delete *it;
			it = entities.erase(it);
		}
	}

	HandleCollision();
	HandleEvents();

	Entity* entity;
	for (std::vector<Entity*>::iterator it = entities.begin(); it != entities.end(); ++it)
	{
		entity = (*it);
		if (entity->OnScreen == false)
			continue;
		if (entity->GetLight() > 0 && ((int) entity->shape->GetCenterX() != (int) (entity->prevPos.x + entity->GetSize().x / 2.0) || (int) entity->shape->GetCenterY() != (int) (entity->prevPos.y + entity->GetSize().y / 2.0)))
			lightDirty = true;
	}
	skyManager->Update();
}
Пример #3
0
void Paddle::UpdatePosition(sbe::World::Ptr const& world)
{
  if (paused_)
    return;

  sbe::Rect const& bound = world->Boundary();

  UpdateVelocity();
  UpdateY(vel_y_);
  HandleCollision(bound);
}
Пример #4
0
// ----------------------------------------------------------------------- //
//
//	ROUTINE:	CLightCycleMgr::Update
//
//	PURPOSE:	Updates the light cycle mgr
//
// ----------------------------------------------------------------------- //
void CLightCycleMgr::Update()
{
	if(!m_bUpdating)
		return;

	// Vars
	LTVector vPos;
	LTVector vOldForward;
	LIGHT_CYCLIST* pCyclist;
	LIGHT_CYCLE_TRAIL *pTrail;
	std::vector<LIGHT_CYCLIST*>::iterator iter;

	// Walk the list
	for(iter=m_collCyclists.begin();iter!=m_collCyclists.end();iter++)
	{
		pCyclist = (*iter);
		if(pCyclist->bUpdating)
		{
			// Update his trail
			ASSERT(pCyclist->hObject);
			g_pLTServer->GetObjectPos(pCyclist->hObject,&vPos);

			pTrail = pCyclist->pCurTrail;

			// Check to see if we have a trail
			if(pTrail)
			{
				vOldForward = pCyclist->vForward;

				// Update the trail
				UpdateLightCycleTrail(pCyclist, vPos);
			}
			else
			{
				// Simple case: We're starting a new trail
				BeginLightCycleTrail(pCyclist,vPos);
			}

			// Now we check to see if this guy collided
			LightCycleCollisionInfo info;
			if(CheckForCollision(pCyclist,info))
			{
				// Uh-oh. We have a crash. And crashing is bad, m'kay?
				HandleCollision(pCyclist,info);
			}
		}
	}
}
Пример #5
0
void sv::ObstacleManager::Update(ulong deltaTime)
{
	Iterator iter = First();
	while(iter)
	{
		Obstacle* obstacle = Get(iter);
		iter = Next(iter);

		obstacle->Update(deltaTime);
		if( obstacle->IsEdge() )
			HandleCollision(obstacle);
		if( obstacle->GetPos() == Grid::InvalidPos )
			DeleteObstacle(obstacle);
	}

	UpdateLevel(deltaTime);
}
Пример #6
0
unsigned char Ball::Tick(double t)
{
    _transform->Tick();

    _direction->Matrix()->Position(*_transform->Position());
    _direction->Tick(t);

    _speed -= 0.02f;

    if (_speed <= 0.f)
    {
        _speed = 0.f;
        return STATUS_OK;
    }

    float dt = (float) t;

    glm::vec3 normal = _tile->Normal();

    // If we just hit the ball, the velocity will always be restricted to the XZ-plane
    *_velocity = ComputeSurfaceDirection(*_velocity, glm::vec3(0.f, 1.f, 0.f), normal);
    glm::vec3 pos = *_transform->Position();
    glm::vec3 endpos = *_transform->Position() + ((dt * _speed) * *_velocity);

    // Did we collide into another tile?
    while (HandleFakeCollision(dt, pos, endpos, *_velocity, 0.f))
    {
        pos = endpos;
        *_velocity = ComputeSurfaceDirection(*_velocity, glm::vec3(0.f, 1.f, 0.f), _tile->Normal());
        endpos = pos + ((dt * _speed) * *_velocity);
    }

    // Did we collide into a wall?
    while (HandleCollision(dt, pos, endpos, *_velocity, 0.03f))
    {
        pos = endpos;
        endpos = pos + ((dt * _speed) * *_velocity);
    }

    _transform->Position(endpos);
    _direction->Matrix()->Position(endpos);

    return STATUS_OK;
}
Пример #7
0
void Game::MainLoop()
{

	sf::Clock FPSClock;
	map = new tmx::MapLoader("maps/");
	map->Load("map_test.tmx");
	sf::Clock frameClock;
	sf::Time frameTime;

	view.reset(sf::FloatRect(0, 0, 800/2, 600/2));
	view.setViewport(sf::FloatRect(0, 0, 1.0f, 1.0f));
	sf::Vector2f viewPosition(800 / 2, 600 / 2);
	view.zoom(0.6f);
	sf::Clock clock;
	sf::Time timeSinceLastUpdate = sf::Time::Zero;	


	//sf::SoundBuffer *mainThemeBuffer;
	mainThemeBuffer = new sf::SoundBuffer();

	if (!mainThemeBuffer->loadFromFile("audio/main.wav"))
	{
		std::cout << "Failed to load mainTheme.wav" << std::endl;
		delete mainThemeBuffer;
		mainThemeBuffer = 0;
	}

	main = new sf::Sound(*mainThemeBuffer);
	main->setLoop(true);
	main->setVolume(75.0f);
	//main->play();

	layers = map->GetLayers();

	hBar = new HealthBar(view.getCenter());	

	while(wnd->isOpen())
	{


		if (currentState == GameStates::PLAYING)
		{

			sf::Time elapsedTime = clock.restart();
			timeSinceLastUpdate += elapsedTime;
			while (timeSinceLastUpdate > TimePerFrame)
			{
				timeSinceLastUpdate -= TimePerFrame;

				//Update logic
				mPlayer->Update(TimePerFrame);

				hBar->Update(TimePerFrame);

				for (size_t i = 0; i < slimes.size(); i++)
					slimes.at(i)->Update(TimePerFrame);

				for (size_t i = 0; i < items.size(); i++)
					items.at(i)->Update(TimePerFrame);

				for (size_t i = 0; i < fireMonsters.size(); i++)
					fireMonsters.at(i)->Update(TimePerFrame);
			}
	
			//Collision Detection
			HandleCollision();

			hBar->SetHealthState(mPlayer->GetHealth());

			if (mPlayer->getPosition().x > 120 && mPlayer->getPosition().x < 2278)
				view.setCenter(mPlayer->getPosition().x, mPlayer->getPosition().y - 30);
			else
			{
				if (mPlayer->getPosition().x < 2278)
					view.setCenter(120, mPlayer->getPosition().y - 30);
				else
					view.setCenter(2278, mPlayer->getPosition().y - 30);
			}

			hBar->setPosition(view.getCenter().x - 105, view.getCenter().y - 75);

			wnd->setView(view);

			if (mPlayer->Succeded() || mPlayer->Dead())
				main->stop();
		}
		else
		{
			timeSinceLastUpdate = sf::Time::Zero;
			clock.restart();
		}

		HandleInput();
		
		Draw();
	}
}
Пример #8
0
/*
 * Handle a DUB response (inc. timeouts).
 * @param data the raw response, excluding the start code
 * @param length the length of the response, 0 if no response was received.
 */
void DiscoveryAgent::BranchComplete(const uint8_t *data, unsigned int length) {
  OLA_INFO << "BranchComplete, got " << length;
  if (length == 0) {
    // timeout
    if (!m_uid_ranges.empty()) {
      FreeCurrentRange();
    }
    SendDiscovery();
    return;
  }

  // Must at least have the separator, the EUID and the checksum
  if (length < 1 + EUID_SIZE + CHECKSUM_SIZE) {
    HandleCollision();
    return;
  }

  unsigned int offset = 0;
  while (data[offset] != PREAMBLE_SEPARATOR && offset < PREAMBLE_SIZE - 1) {
    if (data[offset] != PREAMBLE) {
      OLA_INFO << "Preamble " << offset << " " << strings::ToHex(data[offset]);
      HandleCollision();
      return;
    }
    offset++;
  }

  if (data[offset] != PREAMBLE_SEPARATOR) {
    OLA_INFO << "Preamble separator" << offset << " "
             << strings::ToHex(data[offset]);
    HandleCollision();
    return;
  }

  offset++;
  unsigned int remaining = length - offset;
  if (remaining < EUID_SIZE + CHECKSUM_SIZE) {
    OLA_INFO << "Insufficient data remaining, was " << remaining;
    HandleCollision();
    return;
  }

  typedef struct {
    uint8_t euid11;
    uint8_t euid10;
    uint8_t euid9;
    uint8_t euid8;
    uint8_t euid7;
    uint8_t euid6;
    uint8_t euid5;
    uint8_t euid4;
    uint8_t euid3;
    uint8_t euid2;
    uint8_t euid1;
    uint8_t euid0;
    uint8_t ecs3;
    uint8_t ecs2;
    uint8_t ecs1;
    uint8_t ecs0;
  } dub_response_structure;

  const dub_response_structure *response =
      reinterpret_cast<const dub_response_structure*>(data + offset);

  uint16_t calculated_checksum = 0;
  for (unsigned int i = offset; i < offset + EUID_SIZE; i++) {
    calculated_checksum += data[i];
  }

  uint16_t recovered_checksum = JoinUInt8((response->ecs3 & response->ecs2),
                                          (response->ecs1 & response->ecs0));

  if (recovered_checksum != calculated_checksum) {
    OLA_INFO << "Recovered checksum: " << recovered_checksum << " != "
             << "calculated checksum: " << calculated_checksum;
    HandleCollision();
    return;
  }

  // ok this is a valid response
  uint16_t manufacturer_id = JoinUInt8((response->euid11 & response->euid10),
                                       (response->euid9 & response->euid8));
  uint32_t device_id = JoinUInt8((response->euid7 & response->euid6),
                                 (response->euid5 & response->euid4),
                                 (response->euid3 & response->euid2),
                                 (response->euid1 & response->euid0));

  UIDRange *range = m_uid_ranges.top();

  // we store this as an instance variable so we don't have to create a new
  // callback each time.
  UID located_uid = UID(manufacturer_id, device_id);
  if (m_uids.Contains(located_uid)) {
    OLA_WARN << "Previous muted responder " << located_uid
             << " continues to respond";
    range->failures++;
    // ignore this and continue on to the next branch.
    SendDiscovery();
  } else if (m_bad_uids.Contains(located_uid)) {
    // we've already tried this one
    range->failures++;
    SendDiscovery();
  } else {
    m_muting_uid = located_uid;
    m_mute_attempts = 0;
    OLA_INFO << "Muting " << m_muting_uid;
    m_target->MuteDevice(m_muting_uid, m_branch_mute_callback.get());
  }
}
Пример #9
0
/**
 * Called when we get a response (or timeout) to a branch request.
 * @param data the raw response, excluding the start code
 * @param length the length of the response, 0 if no response was received.
 */
void DiscoveryAgent::BranchComplete(const uint8_t *data, unsigned int length) {
  if (length == 0) {
    // timeout
    FreeCurrentRange();
    SendDiscovery();
    return;
  }

  if (length < MIN_DUB_RESPONSE_SIZE || length > MAX_DUB_RESPONSE_SIZE) {
    HandleCollision();
    return;
  }

  unsigned int preamble_size = length - MIN_DUB_RESPONSE_SIZE;
  for (unsigned int i = 0; i < preamble_size; i++) {
    if (data[i] != 0xfe) {
      OLA_INFO << "preamble " << i << " " << std::hex <<
        static_cast<int>(data[i]);
      HandleCollision();
      return;
    }
  }

  unsigned int offset = preamble_size;
  if (data[offset++] != 0xaa) {
    OLA_INFO << "preamble separator is " << std::hex <<
      static_cast<int>(data[offset]);
    HandleCollision();
    return;
  }

  typedef struct {
    uint8_t euid11;
    uint8_t euid10;
    uint8_t euid9;
    uint8_t euid8;
    uint8_t euid7;
    uint8_t euid6;
    uint8_t euid5;
    uint8_t euid4;
    uint8_t euid3;
    uint8_t euid2;
    uint8_t euid1;
    uint8_t euid0;
    uint8_t ecs3;
    uint8_t ecs2;
    uint8_t ecs1;
    uint8_t ecs0;
  } dub_response_structure;

  const dub_response_structure *response =
      reinterpret_cast<const dub_response_structure*>(data + offset);

  uint16_t calculated_checksum = 0;
  for (unsigned int i = offset; i < offset + 12; i++)
    calculated_checksum += data[i];

  uint16_t recovered_checksum =
    ((response->ecs3 & response->ecs2) << 8) +
    (response->ecs1 & response->ecs0);

  if (recovered_checksum != calculated_checksum) {
    OLA_INFO << "recovered checksum: " << recovered_checksum << " != " <<
      "calculated checksum: " << calculated_checksum;
    HandleCollision();
    return;
  }

  // ok this is a valid response
  uint16_t manufacturer_id =
    ((response->euid11 & response->euid10) << 8) +
    (response->euid9 & response->euid8);
  uint32_t device_id =
    ((response->euid7 & response->euid6) << 24) +
    ((response->euid5 & response->euid4) << 16) +
    ((response->euid3 & response->euid2) << 8) +
    (response->euid1 & response->euid0);

  UIDRange *range = m_uid_ranges.top();

  // we store this as an instance variable so we don't have to create a new
  // callback each time.
  UID located_uid = UID(manufacturer_id, device_id);
  if (m_uids.Contains(located_uid)) {
    OLA_WARN << "Previous muted responder " << located_uid <<
      " continues to respond";
    range->failures++;
    // ignore this and continue on to the next branch.
    SendDiscovery();
  } else if (m_bad_uids.Contains(located_uid)) {
    // we've already tried this one
    range->failures++;
    SendDiscovery();
  } else {
    m_muting_uid = located_uid;
    m_mute_attempts = 0;
    OLA_INFO << "muting " << m_muting_uid;
    m_target->MuteDevice(m_muting_uid, m_branch_mute_callback);
  }
}
Пример #10
0
void neFixedTimeStepSimulator::SolveContactConstrain()
{
// first solve all single object to terrain/animated body contacts

	cresultHeap2.Clear();

	neStackInfoItem * sitem = (neStackInfoItem * )stackHeaderX.head;

	solverStage = 1;

	while (sitem)
	{
		neStackInfo * sinfo = (neStackInfo *)sitem;

		sitem = sitem->next;

		if (sinfo->body->status == neRigidBody_::NE_RBSTATUS_IDLE)
		{
			continue;
		}
		if (!sinfo->body->needSolveContactDynamic)
		{
			continue;
		}
		sinfo->body->AddContactImpulseRecord(0);

		if (cresultHeap2.GetUsedCount() == 0)
		{
			continue;
		}
		
		neRigidBody_* rb = NULL;
		

		for (s32 tt = 0; tt < cresultHeap2.GetUsedCount(); tt++)
		{
			//neCollisionResult * cr = (neCollisionResult *)ci;
			neCollisionResult * cr = &cresultHeap2[tt];//(neCollisionResult *)ci;

			HandleCollision(cr->bodyA, cr->bodyB, *cr, IMPULSE_CONTACT, 1.0f/*cr->impulseScale*/);

			//ci = ci->next;
			rb = cr->bodyA->AsRigidBody();
		}
		cresultHeap2.Clear();

		ASSERT(rb);

		if (rb->CheckStationary())
		{
			if (rb->IsRestPointStillValid())
			{
				if (rb->CheckRestHull())
				{
					rb->BecomeIdle();
				}
			}
		}
	}

	// release any empty stack header
	
	neStackHeaderItem * hitem = (neStackHeaderItem *)(*stackHeaderHeap.BeginUsed());

	while (hitem)
	{		
		neStackHeader * sheader = (neStackHeader *) hitem;

		hitem = hitem->next;

		if (sheader->infoCount > 1)
			continue;

		neStackInfo * s = sheader->head;

		neRigidBody_ * rb = s->body;

		if (s->isTerminator)
		{
			ASSERT(rb->AllRestRecordInvalid());
			
			rb->stackInfo = NULL;

			sheader->Remove(s, 1);

			stackInfoHeap.Dealloc(s, 1);

			stackHeaderHeap.Dealloc(sheader);
		}
		else
		{
			sheader->Remove(s, 1);

			stackHeaderHeap.Dealloc(sheader);

			stackHeaderX.Add(s);
		}
	}
	hitem = (neStackHeaderItem *)(*stackHeaderHeap.BeginUsed());

	while (hitem)
	{
		neStackHeader * sheader = (neStackHeader *) hitem;

		hitem = hitem->next;

		if (sheader->isAllIdle || sheader->dynamicSolved)
			continue;

		pointerBuffer2.Clear(); // stack headers

		pointerBuffer1.Clear(); // constraint headers

		contactConstraintHeader.RemoveAll();

		cresultHeap2.Clear();

		sheader->AddToSolver(/*true*/);

#ifdef _WIN32
		perf->UpdateConstrain1();
#endif

		SolveOneConstrainChain(-1.0f, 2);

#ifdef _WIN32
		perf->UpdateConstrain2();
#endif

		if (contactConstraintHeader.StationaryCheck())
		{
			//all of object are stationary enough
			contactConstraintHeader.BecomeIdle(true);
		}
	}
	contactConstraintHeader.RemoveAll();

	cresultHeap2.Clear();
}
Пример #11
0
void UpdateLocalPlayer(int gameTime) {
	float deltaTimeS = (float)(gameTime) / 1000;
	Vector2 originalPosition = localPlayer.position;

	for (auto &tile : pushTileMap) {
		if (CheckCollision(tile.tile) == true) {
			//0=up 1=down 2=right 3=left
			if (tile.GetDirection(pushTileMap) == 0) localPlayer.velocityY = tile.force * deltaTimeS;
			if (tile.GetDirection(pushTileMap) == 1) localPlayer.velocityY = -tile.force * deltaTimeS;
			if (tile.GetDirection(pushTileMap) == 2) localPlayer.velocityX = tile.force * deltaTimeS;
			if (tile.GetDirection(pushTileMap) == 3) localPlayer.velocityX = -tile.force * deltaTimeS;
		}
	}

	if (floatingMovement) FloatingMovement(deltaTimeS);

	localPlayer.position.x += localPlayer.velocityX;
	localPlayer.position.y += localPlayer.velocityY;
	localPlayer.velocityX = 0;

	if (std::find(keyList.begin(), keyList.end(), SDLK_f) != keyList.end()) floatingMovement = !floatingMovement;

	if (std::find(keyList.begin(), keyList.end(), SDLK_LCTRL) != keyList.end()) { localPlayer.speed = 150; }
	else { localPlayer.speed = 100; }
	if (std::find(keyList.begin(), keyList.end(), SDLK_LEFT) != keyList.end() && std::find(keyList.begin(), keyList.end(), SDLK_RIGHT) == keyList.end()) localPlayer.velocityX =  -localPlayer.speed * deltaTimeS;
	if (std::find(keyList.begin(), keyList.end(), SDLK_RIGHT) != keyList.end() && std::find(keyList.begin(), keyList.end(), SDLK_LEFT) == keyList.end()) localPlayer.velocityX = localPlayer.speed * deltaTimeS;

	if (localPlayer.onGround == true) { 
		if (jumpPress == false) {
			if (std::find(keyList.begin(), keyList.end(), SDLK_SPACE) != keyList.end()) {
				localPlayer.velocityY = -3.5; localPlayer.onGround = false; jumpPress = true;
			}
		}
	}
	else {
		localPlayer.velocityY += 9.8 * deltaTimeS;
	}

	if (std::find(keyList.begin(), keyList.end(), SDLK_SPACE) == keyList.end()) {
		if (localPlayer.velocityY < 0 && localPlayer.onGround == false) localPlayer.velocityY += 9.8 * deltaTimeS;
		if (localPlayer.onGround == true) jumpPress = false;
	}

	for (auto &tile : tileMap) {
		if (tile.tileID == 1) {
			if (CheckCollision(tile) == true) HandleCollision(tile);
		}
	}

	std::vector<Tile> tempGroundTileList;
	for (auto &tile : groundTileList) {
		if (CheckCollision(tile) == false) {
			tempGroundTileList.push_back(tile);
		}
	}

	for (auto &tile : tempGroundTileList) {
		groundTileList.erase(std::remove(groundTileList.begin(), groundTileList.end(), tile), groundTileList.end());
	}
	tempGroundTileList.clear();

	if (groundTileList.size() == 0) localPlayer.onGround = false;

	if (originalPosition != localPlayer.position) {
		char positionChar[BUFLEN];
		std::string positionX(std::to_string(localPlayer.position.x)), positionY(std::to_string(localPlayer.position.y).c_str());
		strcpy(positionChar, ("position>" + positionX.substr(0, positionX.find('.') + 3) + "," + positionY.substr(0, positionY.find('.') + 3)).c_str());
		SendMessageWithTimer(positionChar);
	}
}
void RigidBodySimulator::Simulate(){
	//
	//check item number
	if (pObjectList.size() == 0 || pForceList.size() == 0){ //not enough items
		//cannot preceed
		std::cerr << "not enough object/force!" << std::endl;
	}

	else{               // able to simulate
		//traverse objects
		for (auto item : pObjectList){
			//traverse forces
			isCollide = false;
			//collision detection
			for (auto other_item : pObjectList){
				
				if (other_item == item) //same item
					continue;
				else{
					//check coll8ison 
					if (CheckObjectCollision(item, other_item)){
						//handle collision
						HandleCollision(item, other_item);
						isCollide = true;
					}
				}
			}//end travere other objects

			//sumarize all forces
			//if (item->getALLForces().size() == 0){ //check if no force apply
			//	continue;
			//}
			
			std::vector<Physical_Force*>forces = item->getALLForces();
			Physical_Force totalForce = *forces[0];
			if (forces.size() > 1){
				for (int i = 0; i < forces.size(); i++){
					if (i = 0){
						continue;
					}
					totalForce += *forces[i];
				}
			}
			
			//if (haveGravity){ //gravity applied
			//	totalForce += Physical_Force(Vec3f(0.0, 0.0, -9.8)*item->GetMass());
			
			//for (auto force : item->getALLForces()){
			//	//
			//	totalForce += *force;
			//}
			//update accleration ///////////////////////
			
			if (true/*!isCollide*/){  //applyforce only when no collision
				Acceleration acclerate = Acceleration(&totalForce, item->GetMass());

				//update velocity ////////////////////////////
				Vec3f inspedct = (acclerate*dt).getunifiedVector();
				Velocity vincre = acclerate*dt;
				//Velocity vincre = Velocity(inspedct);
				//Velocity i = item->GetVelovity() + vincre;
				item->SetVelocity(item->GetVelovity() + vincre);
			}
			

			//update transition //////////////////////////////////
			Vec3f dis = item->GetVelovity().getunifiedVector()*dt;
			//item->Translate(item->GetVelovity()*dt);
			item->Translate(dis);
			item->Rotation(0.5);
			
		}
	}
}