1 | // Copyright (C) 2016 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 "qquickfriction_p.h" |
5 | #include <qmath.h> |
6 | |
7 | QT_BEGIN_NAMESPACE |
8 | /*! |
9 | \qmltype Friction |
10 | \instantiates QQuickFrictionAffector |
11 | \inqmlmodule QtQuick.Particles |
12 | \ingroup qtquick-particles |
13 | \inherits Affector |
14 | \brief For applying friction proportional to the particle's current velocity. |
15 | |
16 | */ |
17 | |
18 | /*! |
19 | \qmlproperty real QtQuick.Particles::Friction::factor |
20 | |
21 | A drag will be applied to moving objects which is this factor of their current velocity. |
22 | */ |
23 | /*! |
24 | \qmlproperty real QtQuick.Particles::Friction::threshold |
25 | |
26 | The drag will only be applied to objects with a velocity above the threshold velocity. The |
27 | drag applied will bring objects down to the threshold velocity, but no further. |
28 | |
29 | The default threshold is 0 |
30 | */ |
31 | static qreal sign(qreal a) |
32 | { |
33 | return a >= 0 ? 1 : -1; |
34 | } |
35 | |
36 | static const qreal epsilon = 0.00001; |
37 | |
38 | QQuickFrictionAffector::QQuickFrictionAffector(QQuickItem *parent) : |
39 | QQuickParticleAffector(parent), m_factor(0.0), m_threshold(0.0) |
40 | { |
41 | } |
42 | |
43 | bool QQuickFrictionAffector::affectParticle(QQuickParticleData *d, qreal dt) |
44 | { |
45 | if (!m_factor) |
46 | return false; |
47 | qreal curVX = d->curVX(particleSystem: m_system); |
48 | qreal curVY = d->curVY(particleSystem: m_system); |
49 | if (!curVX && !curVY) |
50 | return false; |
51 | qreal newVX = curVX + (curVX * m_factor * -1 * dt); |
52 | qreal newVY = curVY + (curVY * m_factor * -1 * dt); |
53 | |
54 | if (!m_threshold) { |
55 | if (sign(a: curVX) != sign(a: newVX)) |
56 | newVX = 0; |
57 | if (sign(a: curVY) != sign(a: newVY)) |
58 | newVY = 0; |
59 | } else { |
60 | qreal curMag = qSqrt(v: curVX*curVX + curVY*curVY); |
61 | if (curMag <= m_threshold + epsilon) |
62 | return false; |
63 | qreal newMag = qSqrt(v: newVX*newVX + newVY*newVY); |
64 | if (newMag <= m_threshold + epsilon || //went past the threshold, stop there instead |
65 | sign(a: curVX) != sign(a: newVX) || //went so far past maybe it came out the other side! |
66 | sign(a: curVY) != sign(a: newVY)) { |
67 | qreal theta = qAtan2(y: curVY, x: curVX); |
68 | newVX = m_threshold * qCos(v: theta); |
69 | newVY = m_threshold * qSin(v: theta); |
70 | } |
71 | } |
72 | |
73 | d->setInstantaneousVX(vx: newVX, particleSystem: m_system); |
74 | d->setInstantaneousVY(vy: newVY, particleSystem: m_system); |
75 | return true; |
76 | } |
77 | QT_END_NAMESPACE |
78 | |
79 | #include "moc_qquickfriction_p.cpp" |
80 |