I'm building a small space shooter and want my player to have multiple weapons available. I'm using an array and a vector for the weapons (both initialized when the player is initialized). Both the weapon array and vector are members of the player.
CWeapon m_aWeapons[3]; // Array for unlockable weapons
vector<CWeapon> m_vWeapons; // Vector for unlocked weapons
The weapons that can be unlocked are initialized in an array at the beginning.
// Set unlockable weapons
m_aWeapons[0].Init("LaserOrange.bmp", 0.2f, 400.0f, 20.0f);
m_aWeapons[1].Init("LaserBlue.bmp", 0.2f, 600.0f, 20.0f);
m_aWeapons[2].Init("LaserRed.bmp", 0.2f, 800.0f, 20.0f);
I save the weapons the player has available at current in the vector.
After each level the next weapon is unlocked, if possible, by pushing the next element of the array into the vector with the public method CPlayer::UnlockWeapon ().
// Unlock
//
// Task: Unlock next weapon
//
bool CPlayer::UnlockWeapon()
{
// Unlocked new weapon?
bool bUnlocked = false;
// Temp for size of weapon vector and array
int VectorSize = static_cast<int> (m_vWeapons.size ());
int ArraySize = sizeof(m_aWeapons) / sizeof(CWeapon);
// Not unlocked every weapon?
if (VectorSize < ArraySize)
{
// Yes, then unlock next
m_vWeapons.push_back(m_aWeapons[VectorSize]);
// Unlocked new weapon
bUnlocked = true;
}
return (bUnlocked);
} // UnlockWeapon
I save the index of the currently selected weapon in a variable and when the player shoots, I create a shot and initialize it with the speed and shotsprite of the vector element at the index of the currently selected weapon variable.
// ProcessShooting
//
// Aufgabe: Shoot weapon
//
void CPlayer::ProcessShooting ()
{
// Hasn't shot until now
m_bHasShot = false;
// Pressed "Space" and can shoot?
if (g_pFramework->KeyDown (SDL_SCANCODE_SPACE) && m_bShotLock == false)
{
// Has shot
m_bHasShot = true;
// Create and initialize new shot
CShot Shot;
// Temp for ease
CWeapon Temp = m_vWeapons.at(m_CurrentWeapon);
Shot.Init(Temp.GetSprite(), m_fXPos, m_fYPos, Temp.GetSpeed ());
// Insert shot into shotlist
m_ShotList.push_back (Shot);
// Shoot again, when space released
m_bShotLock = true;
}
// Released space, so allow shooting
if (g_pFramework->KeyDown (SDL_SCANCODE_SPACE) == false)
m_bShotLock = false;
} // ProcessShooting
Is that a strange approach or can I stick with it?
m_aWeapons
when unlocking, isn't the code unlocking the same weapon all the time? \$\endgroup\$m_aWeapons[VectorSize]
. \$\endgroup\$VectorSize
andArraySize
. And guess why? Because calling a vector sizeVectorSize
is as usefull as calling a strings_string
:) \$\endgroup\$unlockableWeaponsSize
?? \$\endgroup\$