torpedo.cpp Example File
demos/sub-attaq/torpedo.cpp
#include "torpedo.h"
#include "pixmapitem.h"
#include "boat.h"
#include "graphicsscene.h"
#include "animationmanager.h"
#include "qanimationstate.h"
#include <QtCore/QPropertyAnimation>
#include <QtCore/QStateMachine>
#include <QtCore/QFinalState>
Torpedo::Torpedo() : PixmapItem(QString::fromLatin1("torpedo"),GraphicsScene::Big),
currentSpeed(0)
{
setZValue(2);
}
void Torpedo::launch()
{
QPropertyAnimation *launchAnimation = new QPropertyAnimation(this, "pos");
AnimationManager::self()->registerAnimation(launchAnimation);
launchAnimation->setEndValue(QPointF(x(),qobject_cast<GraphicsScene *>(scene())->sealLevel() - 15));
launchAnimation->setEasingCurve(QEasingCurve::InQuad);
launchAnimation->setDuration(y()/currentSpeed*10);
connect(launchAnimation,SIGNAL(valueChanged(QVariant)),this,SLOT(onAnimationLaunchValueChanged(QVariant)));
connect(this,SIGNAL(torpedoExploded()), launchAnimation, SLOT(stop()));
QStateMachine *machine = new QStateMachine(this);
QAnimationState *launched = new QAnimationState(machine);
launched->setAnimation(launchAnimation);
QFinalState *final = new QFinalState(machine);
machine->setInitialState(launched);
launched->addTransition(this, SIGNAL(torpedoExploded()),final);
launched->addTransition(launched, SIGNAL(animationFinished()), final);
connect(machine,SIGNAL(finished()),this, SIGNAL(torpedoExecutionFinished()));
machine->start();
}
void Torpedo::setCurrentSpeed(int speed)
{
if (speed < 0) {
qWarning("Torpedo::setCurrentSpeed : The speed is invalid");
return;
}
currentSpeed = speed;
}
void Torpedo::onAnimationLaunchValueChanged(const QVariant &)
{
foreach (QGraphicsItem *item , collidingItems(Qt::IntersectsItemBoundingRect)) {
if (Boat *b = qgraphicsitem_cast<Boat*>(item))
b->destroy();
}
}
void Torpedo::destroy()
{
emit torpedoExploded();
}
[+] Documentation Feedback