[cppcheck] Part 1: Performance
[supertux.git] / src / object / coin_rain.cpp
1 //  SuperTux
2 //  Copyright (C) 2013 LMH <lmh.0013@gmail.com>
3 //
4 //  This program is free software: you can redistribute it and/or modify
5 //  it under the terms of the GNU General Public License as published by
6 //  the Free Software Foundation, either version 3 of the License, or
7 //  (at your option) any later version.
8 //
9 //  This program is distributed in the hope that it will be useful,
10 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
11 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 //  GNU General Public License for more details.
13 //
14 //  You should have received a copy of the GNU General Public License
15 //  along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
17 #include "object/coin_rain.hpp"
18
19 #include "math/random_generator.hpp"
20 #include "object/coin.hpp"
21 #include "sprite/sprite.hpp"
22 #include "sprite/sprite_manager.hpp"
23 #include "supertux/sector.hpp"
24
25 static const float DROP_TIME = .1f; // time duration between "drops" of coin rain
26
27 CoinRain::CoinRain(const Vector& pos, bool emerge) :
28   sprite(SpriteManager::current()->create("images/objects/coin/coin.sprite")),
29   position(pos),
30   emerge_distance(0),
31   timer(),
32   counter(0),
33   drop(0)
34 {
35   if(emerge) {
36     emerge_distance = sprite->get_height();
37   }
38 }
39
40 void
41 CoinRain::update(float elapsed_time)
42 {
43   // first a single (untouchable) coin flies up above the sector
44   if(position.y > -32){
45     float dist = -500 * elapsed_time;
46     position.y += dist;
47     emerge_distance += dist;
48   } // then the first collectable coin drops from one of ten random positions
49   else if (counter==0){
50     drop = gameRandom.rand(10);
51     Sector::current()->add_object(std::make_shared<HeavyCoin>(Vector (position.x+32*((drop<5)?-drop-1:drop-4),-32), Vector (0,0)));
52     counter++;
53     timer.start(DROP_TIME);
54   } // finally the remainder of the coins drop in a determined but appears to be a random order
55   else if(timer.check()){
56     if(counter<10){
57       drop += 7;
58       if(drop >= 10) drop -=10;
59       Sector::current()->add_object(std::make_shared<HeavyCoin>(Vector (position.x+32*((drop<5)?-drop-1:drop-4),-32), Vector (0,0)));
60       counter++;
61       timer.start(DROP_TIME);
62     }else{
63       remove_me();
64     }
65   }
66 }
67
68 void
69 CoinRain::draw(DrawingContext& context)
70 {
71   int layer;
72   if(emerge_distance > 0) {
73     layer = LAYER_OBJECTS - 5;
74   } else {
75     layer = LAYER_OBJECTS + 5;
76   }
77   sprite->draw(context, position, layer);
78 }
79
80 /* EOF */