-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathFShake.cpp
100 lines (82 loc) · 2.6 KB
/
FShake.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include "stdafx.h"
// Code by Francois Guibert
// Contact: www.frozax.com - http://twitter.com/frozax - www.facebook.com/frozax
#include "FShake.h"
// not really useful, but I like clean default constructors
FShake::FShake() : _strength_x(0), _strength_y(0), _displacement_x(0), _displacement_y(0)
{
}
FShake* FShake::create( float d, float strength )
{
// call other construction method with twice the same strength
return create( d, strength, strength );
}
FShake* FShake::actionWithDuration( float d, float strength )
{
// call other construction method with twice the same strength
return create( d, strength, strength );
}
FShake* FShake::actionWithDuration(float duration, float strength_x, float strength_y)
{
return create(duration, strength_x, strength_y);
}
FShake* FShake::create(float duration, float strength_x, float strength_y)
{
FShake *p_action = new FShake();
p_action->initWithDuration(duration, strength_x, strength_y);
p_action->autorelease();
return p_action;
}
bool FShake::initWithDuration(float duration, float strength_x, float strength_y)
{
if (cocos2d::ActionInterval::initWithDuration(duration))
{
_strength_x = strength_x;
_strength_y = strength_y;
return true;
}
return false;
}
// Helper function. I included it here so that you can compile the whole file
// it returns a random value between min and max included
float fgRangeRand( float min, float max )
{
float rnd = ((float)rand()/(float)RAND_MAX);
return rnd*(max-min)+min;
}
void FShake::update(float time)
{
auto target = this->getTarget();
if (!target) { return; }
float rand_x = fgRangeRand( -_strength_x, _strength_x );
float rand_y = fgRangeRand( -_strength_y, _strength_y );
auto currentPosition = target->getPosition();
// move the target to a shaked position
target->setPosition(
currentPosition.x - _displacement_x + rand_x,
currentPosition.y - _displacement_y + rand_y
);
// Keep track of the last displacement
_displacement_x = rand_x;
_displacement_y = rand_y;
}
void FShake::stop(void)
{
auto target = this->getTarget();
if (target)
{
auto currentPosition = target->getPosition();
// Action is done, reset clip position
target->setPosition(currentPosition.x - _displacement_x,
currentPosition.y - _displacement_y);
}
ActionInterval::stop();
}
FShake* FShake::clone()
{
// no copy constructor
auto a = new (std::nothrow) FShake();
a->initWithDuration(_duration, _strength_x, _strength_y);
a->autorelease();
return a;
}