Replaced more lisp::Lisp/lisp::Writer with Reader/Writer
[supertux.git] / src / object / pushbutton.cpp
1 //  SuperTux - PushButton running a script
2 //  Copyright (C) 2006 Christoph Sommer <christoph.sommer@2006.expires.deltadevelopment.de>
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 "audio/sound_manager.hpp"
18 #include "object/player.hpp"
19 #include "object/pushbutton.hpp"
20 #include "sprite/sprite.hpp"
21 #include "supertux/object_factory.hpp"
22 #include "supertux/sector.hpp"
23 #include "util/reader.hpp"
24
25 namespace {
26 const std::string BUTTON_SOUND = "sounds/switch.ogg";
27 //14 -> 8
28 }
29
30 PushButton::PushButton(const Reader& lisp) :
31   MovingSprite(lisp, "images/objects/pushbutton/pushbutton.sprite", LAYER_BACKGROUNDTILES+1, COLGROUP_MOVING), 
32   script(),
33   state(OFF)
34 {
35   sound_manager->preload(BUTTON_SOUND);
36   set_action("off", -1);
37   bbox.set_size(sprite->get_current_hitbox_width(), sprite->get_current_hitbox_height());
38
39   if (!lisp.get("script", script)) throw std::runtime_error("no script set");
40 }
41
42 void
43 PushButton::update(float /*elapsed_time*/)
44 {
45 }
46
47 HitResponse
48 PushButton::collision(GameObject& other, const CollisionHit& hit)
49 {
50   Player* player = dynamic_cast<Player*>(&other);
51   if (!player) return FORCE_MOVE;
52   float vy = player->get_physic().get_velocity_y();
53
54   //player->add_velocity(Vector(0, -150));
55   player->get_physic().set_velocity_y(-150);
56
57   if (state != OFF) return FORCE_MOVE;
58   if (!hit.top) return FORCE_MOVE;
59   if (vy <= 0) return FORCE_MOVE;
60
61   // change appearance
62   state = ON;
63   float old_bbox_height = bbox.get_height();
64   set_action("on", -1);
65   float new_bbox_height = bbox.get_height();
66   set_pos(get_pos() + Vector(0, old_bbox_height - new_bbox_height));
67
68   // play sound
69   sound_manager->play(BUTTON_SOUND);
70
71   // run script
72   std::istringstream stream(script);
73   Sector::current()->run_script(stream, "PushButton");
74
75   return FORCE_MOVE;
76 }
77
78 IMPLEMENT_FACTORY(PushButton, "pushbutton");
79
80 /* EOF */