Skip to content

Ch 10. MultiplayerGameState's Sorting After Receiving SpawnEnemy #25

@kyuhyunp

Description

@kyuhyunp

Since the program uses TCP, the packets are guaranteed to be received in order.

In GameServer's tick, the value of mBattleFieldRect.top decreases for every function call. Thus, the value of mWorldHeight - mBattleFieldRect.top + 500 increases for every function call.

if (now() >= mTimeForNextSpawn + mLastSpawnTime)
	{	
		// No more enemies are spawned near the end
		if (mBattleFieldRect.top > 600.f)
		{
			std::size_t enemyCount = 1u + randomInt(2);
			float spawnCenter = static_cast<float>(randomInt(500) - 250);

			// In case only one enemy is being spawned, it appears directly at the spawnCenter
			float planeDistance = 0.f;
			float nextSpawnPosition = spawnCenter;
			
			// In case there are two enemies being spawned together, each is spawned at each side of the spawnCenter, with a minimum distance
			if (enemyCount == 2)
			{
				planeDistance = static_cast<float>(150 + randomInt(250));
				nextSpawnPosition = spawnCenter - planeDistance / 2.f;
			}

			// Send the spawn orders to all clients
			for (std::size_t i = 0; i < enemyCount; ++i)
			{
				sf::Packet packet;
				packet << static_cast<sf::Int32>(Server::SpawnEnemy);
				packet << static_cast<sf::Int32>(1 + randomInt(Aircraft::TypeCount-1));
				packet << mWorldHeight - mBattleFieldRect.top + 500;
				packet << nextSpawnPosition;

				nextSpawnPosition += planeDistance / 2.f;

				sendToAll(packet);
			}

			mLastSpawnTime = now();
			mTimeForNextSpawn = sf::milliseconds(2000 + randomInt(6000));
		}
	}

Therefore, the height is already sorted in increasing order and sorting the enemy after every SpawnEnemy packet is wasteful. Using a deque to sort the height for networked state would be more efficient.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions