1 | // Copyright (C) 2017 The Qt Company Ltd. |
---|---|
2 | // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only |
3 | |
4 | #include "qquickvelocitycalculator_p_p.h" |
5 | |
6 | #include <QtCore/qdebug.h> |
7 | |
8 | QT_BEGIN_NAMESPACE |
9 | |
10 | /* |
11 | Usage: |
12 | |
13 | QQuickVelocityCalculator velocityCalculator; |
14 | |
15 | // ... |
16 | |
17 | velocityCalcular.startMeasuring(event->pos(), event->timestamp()); |
18 | velocityCalcular.stopMeasuring(event->pos(), event->timestamp()); |
19 | |
20 | // ... |
21 | |
22 | if (velocityCalculator.velocity().x() > someAmount) |
23 | doSomething(); |
24 | else if (velocityCalculator.velocity().x() < -someAmount) |
25 | doSomethingElse(); |
26 | */ |
27 | |
28 | void QQuickVelocityCalculator::startMeasuring(const QPointF &point1, qint64 timestamp) |
29 | { |
30 | m_point1 = point1; |
31 | |
32 | if (timestamp != 0) |
33 | m_point1Timestamp = timestamp; |
34 | else |
35 | m_timer.start(); |
36 | } |
37 | |
38 | void QQuickVelocityCalculator::stopMeasuring(const QPointF &point2, qint64 timestamp) |
39 | { |
40 | if (timestamp == 0 && !m_timer.isValid()) { |
41 | qWarning() << "QQuickVelocityCalculator: a call to stopMeasuring() must be preceded by a call to startMeasuring()"; |
42 | return; |
43 | } |
44 | |
45 | m_point2 = point2; |
46 | m_point2Timestamp = timestamp != 0 ? timestamp : m_timer.elapsed(); |
47 | m_timer.invalidate(); |
48 | } |
49 | |
50 | void QQuickVelocityCalculator::reset() |
51 | { |
52 | m_point1 = QPointF(); |
53 | m_point2 = QPointF(); |
54 | m_point1Timestamp = 0; |
55 | m_point2Timestamp = 0; |
56 | m_timer.invalidate(); |
57 | } |
58 | |
59 | QPointF QQuickVelocityCalculator::velocity() const |
60 | { |
61 | if ((m_point2Timestamp == 0 || m_point1Timestamp == m_point2Timestamp) && !m_timer.isValid()) |
62 | return QPointF(); |
63 | |
64 | const qreal secondsElapsed = (m_point2Timestamp != 0 ? m_point2Timestamp - m_point1Timestamp : m_timer.elapsed()) / 1000.0; |
65 | const QPointF distance = m_point2 - m_point1; |
66 | return distance / secondsElapsed; |
67 | } |
68 | |
69 | QT_END_NAMESPACE |
70 |