submarine_p.h Example File
animation/sub-attaq/submarine_p.h
#ifndef SUBMARINE_P_H
#define SUBMARINE_P_H
#include "animationmanager.h"
#include "submarine.h"
#include "qanimationstate.h"
#include <QtCore/QPropertyAnimation>
#include <QtCore/QRandomGenerator>
#include <QtWidgets/QGraphicsScene>
class MovementState : public QAnimationState
{
Q_OBJECT
public:
explicit MovementState(SubMarine *submarine, QState *parent = 0) : QAnimationState(parent)
{
movementAnimation = new QPropertyAnimation(submarine, "pos");
connect(movementAnimation,SIGNAL(valueChanged(const QVariant &)),this,SLOT(onAnimationMovementValueChanged(const QVariant &)));
setAnimation(movementAnimation);
AnimationManager::self()->registerAnimation(movementAnimation);
this->submarine = submarine;
}
protected slots:
void onAnimationMovementValueChanged(const QVariant &)
{
if (QRandomGenerator::global()->bounded(200) + 1 == 3)
submarine->launchTorpedo(QRandomGenerator::global()->bounded(3) + 1);
}
protected:
void onEntry(QEvent *e) override
{
if (submarine->currentDirection() == SubMarine::Left) {
movementAnimation->setEndValue(QPointF(0,submarine->y()));
movementAnimation->setDuration(submarine->x()/submarine->currentSpeed()*12);
}
else {
movementAnimation->setEndValue(QPointF(submarine->scene()->width()-submarine->size().width(),submarine->y()));
movementAnimation->setDuration((submarine->scene()->width()-submarine->size().width()-submarine->x())/submarine->currentSpeed()*12);
}
QAnimationState::onEntry(e);
}
private:
SubMarine *submarine;
QPropertyAnimation *movementAnimation;
};
class ReturnState : public QAnimationState
{
public:
explicit ReturnState(SubMarine *submarine, QState *parent = 0) : QAnimationState(parent)
{
returnAnimation = new QPropertyAnimation(submarine->rotation(), "angle");
returnAnimation->setDuration(500);
AnimationManager::self()->registerAnimation(returnAnimation);
setAnimation(returnAnimation);
this->submarine = submarine;
}
protected:
void onEntry(QEvent *e) override
{
returnAnimation->stop();
returnAnimation->setEndValue(submarine->currentDirection() == SubMarine::Right ? 360. : 180.);
QAnimationState::onEntry(e);
}
void onExit(QEvent *e) override
{
submarine->currentDirection() == SubMarine::Right ? submarine->setCurrentDirection(SubMarine::Left) : submarine->setCurrentDirection(SubMarine::Right);
QAnimationState::onExit(e);
}
private:
SubMarine *submarine;
QPropertyAnimation *returnAnimation;
};
#endif // SUBMARINE_P_H