3630cf6e31ec4fe347e3e0e89b964d356a2f4d59
[supertux.git] / src / object / pushbutton.cpp
1 //  $Id$
2 //
3 //  SuperTux - PushButton running a script
4 //  Copyright (C) 2006 Christoph Sommer <christoph.sommer@2006.expires.deltadevelopment.de>
5 //
6 //  This program is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU General Public License
8 //  as published by the Free Software Foundation; either version 2
9 //  of the License, or (at your option) any later version.
10 //
11 //  This program is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 //  GNU General Public License for more details.
15 //
16 //  You should have received a copy of the GNU General Public License
17 //  along with this program; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19
20 #include <config.h>
21 #include <stdexcept>
22
23 #include "pushbutton.hpp"
24 #include "object_factory.hpp"
25 #include "player.hpp"
26 #include "audio/sound_manager.hpp"
27 #include "sprite/sprite_manager.hpp"
28 #include "sector.hpp"
29 #include "log.hpp"
30 #include "sprite/sprite.hpp"
31
32 namespace {
33   const std::string BUTTON_SOUND = "sounds/switch.ogg";
34  //14 -> 8
35 }
36
37 PushButton::PushButton(const lisp::Lisp& lisp)
38         : MovingSprite(lisp, "images/objects/pushbutton/pushbutton.sprite", LAYER_BACKGROUNDTILES+1, COLGROUP_MOVING), state(OFF)
39 {
40   sound_manager->preload(BUTTON_SOUND);
41   set_action("off", -1);
42   bbox.set_size(sprite->get_current_hitbox_width(), sprite->get_current_hitbox_height());
43
44   if (!lisp.get("script", script)) throw std::runtime_error("no script set");
45 }
46
47 void
48 PushButton::update(float /*elapsed_time*/)
49 {
50 }
51
52 HitResponse
53 PushButton::collision(GameObject& other, const CollisionHit& hit)
54 {
55   Player* player = dynamic_cast<Player*>(&other);
56   if (!player) return FORCE_MOVE;
57   float vy = player->physic.get_velocity_y();
58
59   //player->add_velocity(Vector(0, -150));
60   player->physic.set_velocity_y(-150);
61
62   if (state != OFF) return FORCE_MOVE;
63   if (!hit.top) return FORCE_MOVE;
64   if (vy <= 0) return FORCE_MOVE;
65
66   // change appearance
67   state = ON;
68   float old_bbox_height = bbox.get_height();
69   set_action("on", -1);
70   float new_bbox_height = bbox.get_height();
71   set_pos(get_pos() + Vector(0, old_bbox_height - new_bbox_height));
72
73   // play sound
74   sound_manager->play(BUTTON_SOUND);
75
76   // run script
77   std::istringstream stream(script);
78   Sector::current()->run_script(stream, "PushButton");
79
80   return FORCE_MOVE;
81 }
82
83 IMPLEMENT_FACTORY(PushButton, "pushbutton");