Game Programming using Qt 5 Beginner's Guide
上QQ阅读APP看书,第一时间看更新

Time for action - Adding a jump animation

Go to the myscene.h file and add a private qreal m_jumpFactor field. Next, declare a getter, a setter, and a change signal for this field:

public:
//...
qreal jumpFactor() const;
void setJumpFactor(const qreal &jumpFactor);
signals:
void jumpFactorChanged(qreal);

In the header file, we declare the jumpFactor property by adding the following code just after the Q_OBJECT macro:

Q_PROPERTY(qreal jumpFactor
           READ jumpFactor
           WRITE setjumpFactor
           NOTIFY jumpFactorChanged)

Here, qreal is the type of the property, jumpFactor is the registered name, and the following three lines register the corresponding member functions of the MyScene class in the property system. We'll need this property to make Benjamin jump, as we will see later on.

The jumpFactor() getter function simply returns the m_jumpFactor private member, which is used to store the actual position. The implementation of the setter looks like this:

void MyScene::setjumpFactor(const qreal &pos) {
    if (pos == m_jumpFactor) {
        return;
    }
    m_jumpFactor = pos;
    emit jumpFactorChanged(m_jumpFactor);
} 

It is important to check whether pos will change the current value of m_jumpFactor. If this is not the case, exit the function, because we don't want the change signal to be emitted even if nothing has changed. Otherwise, we set m_jumpFactor to pos and emit the signal that informs about the change.