that means player can only shoot one canon ball at once, he can make the next shot after the first canon ball has been deleted
There are better ways to do this. For example, all classes based on QObject have a QObject::destroyed() signal that is emitted in the QObject destructor. You can use this signal to detect when your cannonball is being destroyed instead of relying of a static (global) variable:
void Ship::fireCannonball()
{
if ( canFireCannon() )
{
Canon * cannonball = new Canon( this );
connect( canonball, &QObject::destroyed, this, &Ship::onCannonballDestroyed );
cannonballInFlight = true;
}
}
void Ship
::onCannonballDestroyed( QObject * ) // ignore "obj" argument since we know it is a cannonball {
cannonballInFlight = false; // allows a new ball to be fired now
}
bool Ship::canFireCannon()
{
return ( cannonballInFlight == false ); // cannonballInFlight is a member variable of Ship, initialized to false
}
void Ship::fireCannonball()
{
if ( canFireCannon() )
{
Canon * cannonball = new Canon( this );
connect( canonball, &QObject::destroyed, this, &Ship::onCannonballDestroyed );
cannonballInFlight = true;
}
}
void Ship::onCannonballDestroyed( QObject * ) // ignore "obj" argument since we know it is a cannonball
{
cannonballInFlight = false; // allows a new ball to be fired now
}
bool Ship::canFireCannon()
{
return ( cannonballInFlight == false ); // cannonballInFlight is a member variable of Ship, initialized to false
}
To copy to clipboard, switch view to plain text mode
By making cannonballInFlight a member of Ship (instead of a global variable in Canon), you can have any number of ships firing cannonballs at the same time. Each Ship only has to check that it is allowed to fire another cannonball before it fires again. The last cannonball that it fired tells it when it is gone using the destroyed() signal, so the ship doesn't really have to do anything except wait for that after the cannonball is fired.
Bookmarks