Finished up code for basic functionality of earthflower powerup.
[supertux.git] / src / object / player.cpp
1 //  SuperTux
2 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
3 //
4 //  This program is free software; you can redistribute it and/or
5 //  modify it under the terms of the GNU General Public License
6 //  as published by the Free Software Foundation; either version 2
7 //  of the License, or (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, write to the Free Software
16 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
17
18 #include "object/player.hpp"
19
20 #include "audio/sound_manager.hpp"
21 #include "badguy/badguy.hpp"
22 #include "control/input_manager.hpp"
23 #include "math/random_generator.hpp"
24 #include "object/bullet.hpp"
25 #include "object/camera.hpp"
26 #include "object/display_effect.hpp"
27 #include "object/falling_coin.hpp"
28 #include "object/particles.hpp"
29 #include "object/portable.hpp"
30 #include "object/sprite_particle.hpp"
31 #include "scripting/squirrel_util.hpp"
32 #include "supertux/game_session.hpp"
33 #include "supertux/globals.hpp"
34 #include "supertux/sector.hpp"
35 #include "supertux/tile.hpp"
36 #include "trigger/climbable.hpp"
37
38 #include <math.h>
39
40 //#define SWIMMING
41
42 namespace {
43 static const float BUTTJUMP_MIN_VELOCITY_Y = 400.0f;
44 static const float SHOOTING_TIME = .150f;
45 static const float GLIDE_TIME_PER_FLOWER = 0.5f;
46 static const float STONE_TIME_PER_FLOWER = 2.0f;
47
48 /** number of idle stages, including standing */
49 static const unsigned int IDLE_STAGE_COUNT = 5;
50 /**
51  * how long to play each idle animation in milliseconds
52  * '0' means the sprite action is played once before moving onto the next
53  * animation
54  */
55 static const int IDLE_TIME[] = { 5000, 0, 2500, 0, 2500 };
56 /** idle stages */
57 static const std::string IDLE_STAGES[] =
58 { "stand",
59   "idle",
60   "stand",
61   "idle",
62   "stand" };
63
64 /** acceleration in horizontal direction when walking
65  * (all accelerations are in  pixel/s^2) */
66 static const float WALK_ACCELERATION_X = 300;
67 /** acceleration in horizontal direction when running */
68 static const float RUN_ACCELERATION_X = 400;
69 /** acceleration when skidding */
70 static const float SKID_XM = 200;
71 /** time of skidding in seconds */
72 static const float SKID_TIME = .3f;
73 /** maximum walk velocity (pixel/s) */
74 static const float MAX_WALK_XM = 230;
75 /** maximum run velocity (pixel/s) */
76 static const float MAX_RUN_XM = 320;
77 /** bonus run velocity addition (pixel/s) */
78 static const float BONUS_RUN_XM = 80;
79 /** maximum horizontal climb velocity */
80 static const float MAX_CLIMB_XM = 96;
81 /** maximum vertical climb velocity */
82 static const float MAX_CLIMB_YM = 128;
83 /** maximum vertical glide velocity */
84 static const float MAX_GLIDE_YM = 128;
85 /** instant velocity when tux starts to walk */
86 static const float WALK_SPEED = 100;
87
88 /** multiplied by WALK_ACCELERATION to give friction */
89 static const float NORMAL_FRICTION_MULTIPLIER = 1.5f;
90 /** multiplied by WALK_ACCELERATION to give friction */
91 static const float ICE_FRICTION_MULTIPLIER = 0.1f;
92 static const float ICE_ACCELERATION_MULTIPLIER = 0.25f;
93
94 /** time of the kick (kicking mriceblock) animation */
95 static const float KICK_TIME = .3f;
96
97 /** if Tux cannot unduck for this long, he will get hurt */
98 static const float UNDUCK_HURT_TIME = 0.25f;
99 /** gravity is higher after the jump key is released before
100     the apex of the jump is reached */
101 static const float JUMP_EARLY_APEX_FACTOR = 3.0;
102
103 static const float JUMP_GRACE_TIME = 0.25f; /**< time before hitting the ground that the jump button may be pressed (and still trigger a jump) */
104
105 /* Tux's collision rectangle */
106 static const float TUX_WIDTH = 31.8f;
107 static const float RUNNING_TUX_WIDTH = 34;
108 static const float SMALL_TUX_HEIGHT = 30.8f;
109 static const float BIG_TUX_HEIGHT = 62.8f;
110 static const float DUCKED_TUX_HEIGHT = 31.8f;
111
112 bool no_water = true;
113 }
114
115 Player::Player(PlayerStatus* _player_status, const std::string& name_) :
116   deactivated(),
117   controller(),
118   scripting_controller(),
119   player_status(_player_status),
120   duck(),
121   dead(),
122   dying(),
123   winning(),
124   backflipping(),
125   backflip_direction(),
126   peekingX(),
127   peekingY(),
128   ability_time(),
129   stone(),
130   swimming(),
131   speedlimit(),
132   scripting_controller_old(0),
133   jump_early_apex(),
134   on_ice(),
135   ice_this_frame(),
136   lightsprite(SpriteManager::current()->create("images/creatures/tux/light.sprite")),
137   powersprite(SpriteManager::current()->create("images/creatures/tux/powerups.sprite")),
138   dir(),
139   old_dir(),
140   last_ground_y(),
141   fall_mode(),
142   on_ground_flag(),
143   jumping(),
144   can_jump(),
145   jump_button_timer(),
146   wants_buttjump(),
147   does_buttjump(),
148   invincible_timer(),
149   skidding_timer(),
150   safe_timer(),
151   kick_timer(),
152   shooting_timer(),
153   ability_timer(),
154   cooldown_timer(),
155   dying_timer(),
156   growing(),
157   backflip_timer(),
158   physic(),
159   visible(),
160   grabbed_object(NULL),
161   sprite(),
162   airarrow(),
163   floor_normal(),
164   ghost_mode(false),
165   edit_mode(false),
166   unduck_hurt_timer(),
167   idle_timer(),
168   idle_stage(0),
169   climbing(0)
170 {
171   this->name = name_;
172   controller = InputManager::current()->get_controller();
173   scripting_controller.reset(new CodeController());
174   // if/when we have complete penny gfx, we can
175   // load those instead of Tux's sprite in the
176   // constructor
177   sprite = SpriteManager::current()->create("images/creatures/tux/tux.sprite");
178   airarrow = Surface::create("images/engine/hud/airarrow.png");
179   idle_timer.start(IDLE_TIME[0]/1000.0f);
180
181   SoundManager::current()->preload("sounds/bigjump.wav");
182   SoundManager::current()->preload("sounds/jump.wav");
183   SoundManager::current()->preload("sounds/hurt.wav");
184   SoundManager::current()->preload("sounds/kill.wav");
185   SoundManager::current()->preload("sounds/skid.wav");
186   SoundManager::current()->preload("sounds/flip.wav");
187   SoundManager::current()->preload("sounds/invincible_start.ogg");
188   SoundManager::current()->preload("sounds/splash.ogg");
189
190   init();
191 }
192
193 Player::~Player()
194 {
195   if (climbing) stop_climbing(*climbing);
196 }
197
198 void
199 Player::init()
200 {
201   if(is_big())
202     set_size(TUX_WIDTH, BIG_TUX_HEIGHT);
203   else
204     set_size(TUX_WIDTH, SMALL_TUX_HEIGHT);
205
206   dir = RIGHT;
207   old_dir = dir;
208   duck = false;
209   dead = false;
210
211   dying = false;
212   winning = false;
213   peekingX = AUTO;
214   peekingY = AUTO;
215   last_ground_y = 0;
216   fall_mode = ON_GROUND;
217   jumping = false;
218   jump_early_apex = false;
219   can_jump = true;
220   wants_buttjump = false;
221   does_buttjump = false;
222   growing = false;
223   deactivated = false;
224   backflipping = false;
225   backflip_direction = 0;
226   sprite->set_angle(0.0f);
227   visible = true;
228   ability_time = 0;
229   stone = false;
230   swimming = false;
231   on_ice = false;
232   ice_this_frame = false;
233   speedlimit = 0; //no special limit
234   lightsprite->set_blend(Blend(GL_SRC_ALPHA, GL_ONE));
235
236   on_ground_flag = false;
237   grabbed_object = NULL;
238
239   climbing = 0;
240
241   physic.reset();
242 }
243
244 void
245 Player::expose(HSQUIRRELVM vm, SQInteger table_idx)
246 {
247   if (name.empty())
248     return;
249
250   scripting::expose_object(vm, table_idx, dynamic_cast<scripting::Player *>(this), name, false);
251 }
252
253 void
254 Player::unexpose(HSQUIRRELVM vm, SQInteger table_idx)
255 {
256   if (name.empty())
257     return;
258
259   scripting::unexpose_object(vm, table_idx, name);
260 }
261
262 float
263 Player::get_speedlimit()
264 {
265   return speedlimit;
266 }
267
268 void
269 Player::set_speedlimit(float newlimit)
270 {
271   speedlimit=newlimit;
272 }
273
274 void
275 Player::set_controller(Controller* controller_)
276 {
277   this->controller = controller_;
278 }
279
280 void
281 Player::set_winning()
282 {
283   if( ! is_winning() ){
284     winning = true;
285     invincible_timer.start(10000.0f);
286   }
287 }
288
289 void
290 Player::use_scripting_controller(bool use_or_release)
291 {
292   if ((use_or_release == true) && (controller != scripting_controller.get())) {
293     scripting_controller_old = get_controller();
294     set_controller(scripting_controller.get());
295   }
296   if ((use_or_release == false) && (controller == scripting_controller.get())) {
297     set_controller(scripting_controller_old);
298     scripting_controller_old = 0;
299   }
300 }
301
302 void
303 Player::do_scripting_controller(std::string control, bool pressed)
304 {
305   for(int i = 0; Controller::controlNames[i] != 0; ++i) {
306     if(control == std::string(Controller::controlNames[i])) {
307       scripting_controller->press(Controller::Control(i), pressed);
308     }
309   }
310 }
311
312 bool
313 Player::adjust_height(float new_height)
314 {
315   Rectf bbox2 = bbox;
316   bbox2.move(Vector(0, bbox.get_height() - new_height));
317   bbox2.set_height(new_height);
318
319
320   if(new_height > bbox.get_height()) {
321     Rectf additional_space = bbox2;
322     additional_space.set_height(new_height - bbox.get_height());
323     if(!Sector::current()->is_free_of_statics(additional_space, this, true))
324       return false;
325   }
326
327   // adjust bbox accordingly
328   // note that we use members of moving_object for this, so we can run this during CD, too
329   set_pos(bbox2.p1);
330   set_size(bbox2.get_width(), bbox2.get_height());
331   return true;
332 }
333
334 void
335 Player::trigger_sequence(std::string sequence_name)
336 {
337   if (climbing) stop_climbing(*climbing);
338   backflipping = false;
339   backflip_direction = 0;
340   sprite->set_angle(0.0f);
341   GameSession::current()->start_sequence(sequence_name);
342 }
343
344 void
345 Player::update(float elapsed_time)
346 {
347   if( no_water ){
348     swimming = false;
349   }
350   no_water = true;
351
352   if(dying && dying_timer.check()) {
353     set_bonus(NO_BONUS, true);
354     dead = true;
355     return;
356   }
357
358   if(!dying && !deactivated)
359     handle_input();
360
361   /*
362   // handle_input() calls apply_friction() when Tux is not walking, so we'll have to do this ourselves
363   if (deactivated)
364   apply_friction();
365   */
366
367   // extend/shrink tux collision rectangle so that we fall through/walk over 1
368   // tile holes
369   if(fabsf(physic.get_velocity_x()) > MAX_WALK_XM) {
370     set_width(RUNNING_TUX_WIDTH);
371   } else {
372     set_width(TUX_WIDTH);
373   }
374
375   // on downward slopes, adjust vertical velocity so tux walks smoothly down
376   if (on_ground() && !dying) {
377     if(floor_normal.y != 0) {
378       if ((floor_normal.x * physic.get_velocity_x()) >= 0) {
379         physic.set_velocity_y(250);
380       }
381     }
382   }
383
384   // handle backflipping
385   if (backflipping && !dying) {
386     //prevent player from changing direction when backflipping
387     dir = (backflip_direction == 1) ? LEFT : RIGHT;
388     if (backflip_timer.started()) physic.set_velocity_x(100 * backflip_direction);
389     //rotate sprite during flip
390     sprite->set_angle(sprite->get_angle() + (dir==LEFT?1:-1) * elapsed_time * (360.0f / 0.5f));
391   }
392
393   // set fall mode...
394   if(on_ground()) {
395     fall_mode = ON_GROUND;
396     last_ground_y = get_pos().y;
397   } else {
398     if(get_pos().y > last_ground_y)
399       fall_mode = FALLING;
400     else if(fall_mode == ON_GROUND)
401       fall_mode = JUMPING;
402   }
403
404   // check if we landed
405   if(on_ground()) {
406     jumping = false;
407     if (backflipping && (backflip_timer.get_timegone() > 0.15f)) {
408       backflipping = false;
409       backflip_direction = 0;
410       sprite->set_angle(0.0f);
411
412       // if controls are currently deactivated, we take care of standing up ourselves
413       if (deactivated)
414         do_standup();
415     }
416     if (player_status->bonus == AIR_BONUS)
417       ability_time = player_status->max_air_time * GLIDE_TIME_PER_FLOWER;
418   }
419
420   // calculate movement for this frame
421   movement = physic.get_movement(elapsed_time);
422
423   if(grabbed_object != NULL && !dying) {
424     position_grabbed_object();
425   }
426
427   if(grabbed_object != NULL && dying){
428     grabbed_object->ungrab(*this, dir);
429     grabbed_object = NULL;
430   }
431
432   if(!ice_this_frame && on_ground())
433     on_ice = false;
434
435   on_ground_flag = false;
436   ice_this_frame = false;
437
438   // when invincible, spawn particles
439   if (invincible_timer.started())
440   {
441     if (graphicsRandom.rand(0, 2) == 0) {
442       float px = graphicsRandom.randf(bbox.p1.x+0, bbox.p2.x-0);
443       float py = graphicsRandom.randf(bbox.p1.y+0, bbox.p2.y-0);
444       Vector ppos = Vector(px, py);
445       Vector pspeed = Vector(0, 0);
446       Vector paccel = Vector(0, 0);
447       Sector::current()->add_object(std::make_shared<SpriteParticle>(
448                                       "images/objects/particles/sparkle.sprite",
449                                       // draw bright sparkle when there is lots of time left,
450                                       // dark sparkle when invincibility is about to end
451                                       (invincible_timer.get_timeleft() > TUX_INVINCIBLE_TIME_WARNING) ?
452                                       // make every other a longer sparkle to make trail a bit fuzzy
453                                       (size_t(game_time*20)%2) ? "small" : "medium"
454                                       :
455                                       "dark", ppos, ANCHOR_MIDDLE, pspeed, paccel, LAYER_OBJECTS+1+5));
456     }
457   }
458
459   if (growing) {
460     if (sprite->animation_done()) growing = false;
461   }
462
463   // when climbing animate only while moving
464   if(climbing){
465     if((physic.get_velocity_x()==0)&&(physic.get_velocity_y()==0))
466       sprite->stop_animation();
467     else
468       sprite->set_animation_loops(-1);
469   }
470
471 }
472
473 bool
474 Player::on_ground()
475 {
476   return on_ground_flag;
477 }
478
479 bool
480 Player::is_big()
481 {
482   if(player_status->bonus == NO_BONUS)
483     return false;
484
485   return true;
486 }
487
488 void
489 Player::apply_friction()
490 {
491   if ((on_ground()) && (fabs(physic.get_velocity_x()) < WALK_SPEED)) {
492     physic.set_velocity_x(0);
493     physic.set_acceleration_x(0);
494   } else {
495     float friction = WALK_ACCELERATION_X * (on_ice ? ICE_FRICTION_MULTIPLIER : NORMAL_FRICTION_MULTIPLIER);
496     if(physic.get_velocity_x() < 0) {
497       physic.set_acceleration_x(friction);
498     } else if(physic.get_velocity_x() > 0) {
499       physic.set_acceleration_x(-friction);
500     } // no friction for physic.get_velocity_x() == 0
501   }
502 }
503
504 void
505 Player::handle_horizontal_input()
506 {
507   float vx = physic.get_velocity_x();
508   float vy = physic.get_velocity_y();
509   float ax = physic.get_acceleration_x();
510   float ay = physic.get_acceleration_y();
511
512   float dirsign = 0;
513   if(!duck || physic.get_velocity_y() != 0) {
514     if(controller->hold(Controller::LEFT) && !controller->hold(Controller::RIGHT)) {
515       old_dir = dir;
516       dir = LEFT;
517       dirsign = -1;
518     } else if(!controller->hold(Controller::LEFT)
519               && controller->hold(Controller::RIGHT)) {
520       old_dir = dir;
521       dir = RIGHT;
522       dirsign = 1;
523     }
524   }
525
526   // do not run if we're holding something which slows us down
527   if ( grabbed_object && grabbed_object->is_hampering() ) {
528     ax = dirsign * WALK_ACCELERATION_X;
529     // limit speed
530     if(vx >= MAX_WALK_XM && dirsign > 0) {
531       vx = MAX_WALK_XM;
532       ax = 0;
533     } else if(vx <= -MAX_WALK_XM && dirsign < 0) {
534       vx = -MAX_WALK_XM;
535       ax = 0;
536     }
537   } else {
538     if( vx * dirsign < MAX_WALK_XM ) {
539       ax = dirsign * WALK_ACCELERATION_X;
540     } else {
541       ax = dirsign * RUN_ACCELERATION_X;
542     }
543     // limit speed
544     if(vx >= MAX_RUN_XM + BONUS_RUN_XM *((player_status->bonus == AIR_BONUS) ? 1 : 0) && dirsign > 0) {
545       vx = MAX_RUN_XM + BONUS_RUN_XM *((player_status->bonus == AIR_BONUS) ? 1 : 0);
546       ax = 0;
547     } else if(vx <= -MAX_RUN_XM - BONUS_RUN_XM *((player_status->bonus == AIR_BONUS) ? 1 : 0) && dirsign < 0) {
548       vx = -MAX_RUN_XM - BONUS_RUN_XM *((player_status->bonus == AIR_BONUS) ? 1 : 0);
549       ax = 0;
550     }
551   }
552
553   // we can reach WALK_SPEED without any acceleration
554   if(dirsign != 0 && fabs(vx) < WALK_SPEED) {
555     vx = dirsign * WALK_SPEED;
556   }
557
558   //Check speedlimit.
559   if( speedlimit > 0 &&  vx * dirsign >= speedlimit ) {
560     vx = dirsign * speedlimit;
561     ax = 0;
562   }
563
564   // changing directions?
565   if(on_ground() && ((vx < 0 && dirsign >0) || (vx>0 && dirsign<0))) {
566     // let's skid!
567     if(fabs(vx)>SKID_XM && !skidding_timer.started()) {
568       skidding_timer.start(SKID_TIME);
569       SoundManager::current()->play("sounds/skid.wav");
570       // dust some particles
571       Sector::current()->add_object(
572         std::make_shared<Particles>(
573           Vector(dir == RIGHT ? get_bbox().p2.x : get_bbox().p1.x, get_bbox().p2.y),
574           dir == RIGHT ? 270+20 : 90-40, dir == RIGHT ? 270+40 : 90-20,
575           Vector(280, -260), Vector(0, 300), 3, Color(.4f, .4f, .4f), 3, .8f,
576           LAYER_OBJECTS+1));
577
578       ax *= 2.5;
579     } else {
580       ax *= 2;
581     }
582   }
583
584   if(on_ice) {
585     ax *= ICE_ACCELERATION_MULTIPLIER;
586   }
587
588   physic.set_velocity(vx, vy);
589   physic.set_acceleration(ax, ay);
590
591   // we get slower when not pressing any keys
592   if(dirsign == 0) {
593     apply_friction();
594   }
595
596 }
597
598 void
599 Player::do_cheer()
600 {
601   do_duck();
602   do_backflip();
603   do_standup();
604 }
605
606 void
607 Player::do_duck() {
608   if (duck)
609     return;
610   if (!is_big())
611     return;
612
613   if (physic.get_velocity_y() != 0)
614     return;
615   if (!on_ground())
616     return;
617   if (does_buttjump)
618     return;
619
620   if (adjust_height(DUCKED_TUX_HEIGHT)) {
621     duck = true;
622     growing = false;
623     unduck_hurt_timer.stop();
624   } else {
625     // FIXME: what now?
626   }
627 }
628
629 void
630 Player::do_standup() {
631   if (!duck)
632     return;
633   if (!is_big())
634     return;
635   if (backflipping)
636     return;
637
638   if (adjust_height(BIG_TUX_HEIGHT)) {
639     duck = false;
640     unduck_hurt_timer.stop();
641   } else {
642     // if timer is not already running, start it.
643     if (unduck_hurt_timer.get_period() == 0) {
644       unduck_hurt_timer.start(UNDUCK_HURT_TIME);
645     }
646     else if (unduck_hurt_timer.check()) {
647       kill(false);
648     }
649   }
650
651 }
652
653 void
654 Player::do_backflip() {
655   if (!duck)
656     return;
657   if (!on_ground())
658     return;
659
660   backflip_direction = (dir == LEFT)?(+1):(-1);
661   backflipping = true;
662   do_jump((player_status->bonus == AIR_BONUS) ? -720 : -580);
663   SoundManager::current()->play("sounds/flip.wav");
664   backflip_timer.start(TUX_BACKFLIP_TIME);
665 }
666
667 void
668 Player::do_jump(float yspeed) {
669   if (!on_ground())
670     return;
671
672   physic.set_velocity_y(yspeed);
673   //bbox.move(Vector(0, -1));
674   jumping = true;
675   on_ground_flag = false;
676   can_jump = false;
677
678   // play sound
679   if (is_big()) {
680     SoundManager::current()->play("sounds/bigjump.wav");
681   } else {
682     SoundManager::current()->play("sounds/jump.wav");
683   }
684 }
685
686 void
687 Player::early_jump_apex()
688 {
689   if (!jump_early_apex)
690   {
691     jump_early_apex = true;
692     physic.set_gravity_modifier(JUMP_EARLY_APEX_FACTOR);
693   }
694 }
695
696 void
697 Player::do_jump_apex()
698 {
699   if (jump_early_apex)
700   {
701     jump_early_apex = false;
702     physic.set_gravity_modifier(1.0f);
703   }
704 }
705
706 void
707 Player::handle_vertical_input()
708 {
709   // Press jump key
710   if(controller->pressed(Controller::JUMP)) jump_button_timer.start(JUMP_GRACE_TIME);
711   if(controller->hold(Controller::JUMP) && jump_button_timer.started() && can_jump) {
712     jump_button_timer.stop();
713     if (duck) {
714       // when running, only jump a little bit; else do a backflip
715       if ((physic.get_velocity_x() != 0) ||
716           (controller->hold(Controller::LEFT)) ||
717           (controller->hold(Controller::RIGHT)))
718       {
719         do_jump(-300);
720       }
721       else
722       {
723         do_backflip();
724       }
725     } else {
726       // airflower allows for higher jumps-
727       // jump a bit higher if we are running; else do a normal jump
728       if(player_status->bonus == AIR_BONUS)
729         do_jump((fabs(physic.get_velocity_x()) > MAX_WALK_XM) ? -620 : -580);
730       else
731         do_jump((fabs(physic.get_velocity_x()) > MAX_WALK_XM) ? -580 : -520);
732     }
733     // airflower glide only when holding jump key
734   } else  if (controller->hold(Controller::JUMP) && player_status->bonus == AIR_BONUS && physic.get_velocity_y() > MAX_GLIDE_YM) {
735       if (ability_time > 0 && !ability_timer.started())
736         ability_timer.start(ability_time);
737       else if (ability_timer.started()) {
738         // glide stops after some duration or if buttjump is initiated
739         if ((ability_timer.get_timeleft() <= 0.05f) || controller->hold(Controller::DOWN)) {
740           ability_time = 0;
741           ability_timer.stop();
742         } else {
743           physic.set_velocity_y(MAX_GLIDE_YM);
744           physic.set_acceleration_y(0);
745         }
746       }
747     }
748
749
750   // Let go of jump key
751   else if(!controller->hold(Controller::JUMP)) {
752     if (!backflipping && jumping && physic.get_velocity_y() < 0) {
753       jumping = false;
754       early_jump_apex();
755     }
756     if (player_status->bonus == AIR_BONUS && ability_timer.started()){
757       ability_time = ability_timer.get_timeleft();
758       ability_timer.stop();
759     }
760   }
761
762   if(jump_early_apex && physic.get_velocity_y() >= 0) {
763     do_jump_apex();
764   }
765
766   /* In case the player has pressed Down while in a certain range of air,
767      enable butt jump action */
768   if (controller->hold(Controller::DOWN) && !duck && is_big() && !on_ground()) {
769     wants_buttjump = true;
770     if (physic.get_velocity_y() >= BUTTJUMP_MIN_VELOCITY_Y) does_buttjump = true;
771   }
772
773   /* When Down is not held anymore, disable butt jump */
774   if(!controller->hold(Controller::DOWN)) {
775     wants_buttjump = false;
776     does_buttjump = false;
777   }
778
779   // swimming
780   physic.set_acceleration_y(0);
781 #ifdef SWIMMING
782   if (swimming) {
783     if (controller->hold(Controller::UP) || controller->hold(Controller::JUMP))
784       physic.set_acceleration_y(-2000);
785     physic.set_velocity_y(physic.get_velocity_y() * 0.94);
786   }
787 #endif
788 }
789
790 void
791 Player::handle_input()
792 {
793   if (ghost_mode) {
794     handle_input_ghost();
795     return;
796   }
797   if (climbing) {
798     handle_input_climbing();
799     return;
800   }
801
802   /* Peeking */
803   if( controller->released( Controller::PEEK_LEFT ) || controller->released( Controller::PEEK_RIGHT ) ) {
804     peekingX = AUTO;
805   }
806   if( controller->released( Controller::PEEK_UP ) || controller->released( Controller::PEEK_DOWN ) ) {
807     peekingY = AUTO;
808   }
809   if( controller->pressed( Controller::PEEK_LEFT ) ) {
810     peekingX = LEFT;
811   }
812   if( controller->pressed( Controller::PEEK_RIGHT ) ) {
813     peekingX = RIGHT;
814   }
815   if(!backflipping && !jumping && on_ground()) {
816     if( controller->pressed( Controller::PEEK_UP ) ) {
817       peekingY = UP;
818     } else if( controller->pressed( Controller::PEEK_DOWN ) ) {
819       peekingY = DOWN;
820     }
821   }
822
823   /* Handle horizontal movement: */
824   if (!backflipping && !stone) handle_horizontal_input();
825
826   /* Jump/jumping? */
827   if (on_ground())
828     can_jump = true;
829
830   /* Handle vertical movement: */
831   if (!stone) handle_vertical_input();
832
833   /* Shoot! */
834   if (controller->pressed(Controller::ACTION) && (player_status->bonus == FIRE_BONUS || player_status->bonus == ICE_BONUS)) {
835     if((player_status->bonus == FIRE_BONUS &&
836       Sector::current()->get_active_bullets() < player_status->max_fire_bullets) ||
837       (player_status->bonus == ICE_BONUS &&
838       Sector::current()->get_active_bullets() < player_status->max_ice_bullets))
839     {
840       Vector pos = get_pos() + ((dir == LEFT)? Vector(0, bbox.get_height()/2) : Vector(32, bbox.get_height()/2));
841       auto new_bullet = std::make_shared<Bullet>(pos, physic.get_velocity_x(), dir, player_status->bonus);
842       Sector::current()->add_object(new_bullet);
843
844       SoundManager::current()->play("sounds/shoot.wav");
845       shooting_timer.start(SHOOTING_TIME);
846     }
847   }
848
849   /* Turn to Stone */
850   if (controller->pressed(Controller::DOWN) && player_status->bonus == EARTH_BONUS && !cooldown_timer.started()) {
851     if (controller->hold(Controller::ACTION) && !ability_timer.started()) {
852       ability_timer.start(player_status->max_earth_time * STONE_TIME_PER_FLOWER);
853       stone = true;
854       physic.set_gravity_modifier(1.0f); // Undo jump_early_apex
855     }
856   }
857
858   if (stone)
859     apply_friction();
860
861   /* Revert from Stone */
862   if (stone && (!controller->hold(Controller::ACTION) || ability_timer.get_timeleft() <= 0.5f)) {
863     cooldown_timer.start(ability_timer.get_timegone()/2.0f); //The longer stone form is used, the longer until it can be used again
864     ability_timer.stop();
865     stone = false;
866     for (int i = 0; i < 8; i++)
867     {
868       Vector ppos = Vector(get_bbox().get_left() + 8 + 16*((int)i/4), get_bbox().get_top() + 16*(i%4));
869       float grey = graphicsRandom.randf(.4f, .8f);
870       Color pcolor = Color(grey, grey, grey);
871       Sector::current()->add_object(std::make_shared<Particles>(ppos, -60, 240, 42, 81, Vector(0, 500),
872                                                                 8, pcolor, 4 + graphicsRandom.randf(-0.4, 0.4),
873                                                                 0.8 + graphicsRandom.randf(0, 0.4), LAYER_OBJECTS+2));
874     }
875   }
876
877   /* Duck or Standup! */
878   if (controller->hold(Controller::DOWN) && !stone) {
879     do_duck();
880   } else {
881     do_standup();
882   }
883
884   /* grabbing */
885   try_grab();
886
887   if(!controller->hold(Controller::ACTION) && grabbed_object) {
888     MovingObject* moving_object = dynamic_cast<MovingObject*> (grabbed_object);
889     if(moving_object) {
890       // move the grabbed object a bit away from tux
891       Rectf grabbed_bbox = moving_object->get_bbox();
892       Rectf dest_;
893       dest_.p2.y = bbox.get_top() + bbox.get_height()*0.66666;
894       dest_.p1.y = dest_.p2.y - grabbed_bbox.get_height();
895       if(dir == LEFT) {
896         dest_.p2.x = bbox.get_left() - 1;
897         dest_.p1.x = dest_.p2.x - grabbed_bbox.get_width();
898       } else {
899         dest_.p1.x = bbox.get_right() + 1;
900         dest_.p2.x = dest_.p1.x + grabbed_bbox.get_width();
901       }
902       if(Sector::current()->is_free_of_tiles(dest_, true)) {
903         moving_object->set_pos(dest_.p1);
904         if(controller->hold(Controller::UP)) {
905           grabbed_object->ungrab(*this, UP);
906         } else {
907           grabbed_object->ungrab(*this, dir);
908         }
909         grabbed_object = NULL;
910       }
911     } else {
912       log_debug << "Non MovingObject grabbed?!?" << std::endl;
913     }
914   }
915
916   /* stop backflipping at will */
917   if( backflipping && ( !controller->hold(Controller::JUMP) && !backflip_timer.started()) ){
918     backflipping = false;
919     backflip_direction = 0;
920     sprite->set_angle(0.0f);
921   }
922 }
923
924 void
925 Player::position_grabbed_object()
926 {
927   MovingObject* moving_object = dynamic_cast<MovingObject*>(grabbed_object);
928   assert(moving_object);
929
930   // Position where we will hold the lower-inner corner
931   Vector pos(get_bbox().get_left() + get_bbox().get_width()/2,
932       get_bbox().get_top() + get_bbox().get_height()*0.66666);
933
934   // Adjust to find the grabbed object's upper-left corner
935   if (dir == LEFT)
936     pos.x -= moving_object->get_bbox().get_width();
937   pos.y -= moving_object->get_bbox().get_height();
938
939   grabbed_object->grab(*this, pos, dir);
940 }
941
942 void
943 Player::try_grab()
944 {
945   if(controller->hold(Controller::ACTION) && !grabbed_object
946      && !duck) {
947     Sector* sector = Sector::current();
948     Vector pos;
949     if(dir == LEFT) {
950       pos = Vector(bbox.get_left() - 5, bbox.get_bottom() - 16);
951     } else {
952       pos = Vector(bbox.get_right() + 5, bbox.get_bottom() - 16);
953     }
954
955     for(Sector::Portables::iterator i = sector->portables.begin();
956         i != sector->portables.end(); ++i) {
957       Portable* portable = *i;
958       if(!portable->is_portable())
959         continue;
960
961       // make sure the Portable is a MovingObject
962       MovingObject* moving_object = dynamic_cast<MovingObject*> (portable);
963       assert(moving_object);
964       if(moving_object == NULL)
965         continue;
966
967       // make sure the Portable isn't currently non-solid
968       if(moving_object->get_group() == COLGROUP_DISABLED) continue;
969
970       // check if we are within reach
971       if(moving_object->get_bbox().contains(pos)) {
972         if (climbing) stop_climbing(*climbing);
973         grabbed_object = portable;
974         position_grabbed_object();
975         break;
976       }
977     }
978   }
979 }
980
981 void
982 Player::handle_input_ghost()
983 {
984   float vx = 0;
985   float vy = 0;
986   if (controller->hold(Controller::LEFT)) {
987     dir = LEFT;
988     vx -= MAX_RUN_XM * 2;
989   }
990   if (controller->hold(Controller::RIGHT)) {
991     dir = RIGHT;
992     vx += MAX_RUN_XM * 2;
993   }
994   if ((controller->hold(Controller::UP)) || (controller->hold(Controller::JUMP))) {
995     vy -= MAX_RUN_XM * 2;
996   }
997   if (controller->hold(Controller::DOWN)) {
998     vy += MAX_RUN_XM * 2;
999   }
1000   if (controller->hold(Controller::ACTION)) {
1001     set_ghost_mode(false);
1002   }
1003   physic.set_velocity(vx, vy);
1004   physic.set_acceleration(0, 0);
1005 }
1006
1007 void
1008 Player::add_coins(int count)
1009 {
1010   player_status->add_coins(count);
1011 }
1012
1013 int
1014 Player::get_coins()
1015 {
1016   return player_status->coins;
1017 }
1018
1019 bool
1020 Player::add_bonus(const std::string& bonustype)
1021 {
1022   BonusType type = NO_BONUS;
1023
1024   if(bonustype == "grow") {
1025     type = GROWUP_BONUS;
1026   } else if(bonustype == "fireflower") {
1027     type = FIRE_BONUS;
1028   } else if(bonustype == "iceflower") {
1029     type = ICE_BONUS;
1030   } else if(bonustype == "airflower") {
1031     type = AIR_BONUS;
1032   } else if(bonustype == "earthflower") {
1033     type = EARTH_BONUS;
1034   } else if(bonustype == "none") {
1035     type = NO_BONUS;
1036   } else {
1037     std::ostringstream msg;
1038     msg << "Unknown bonus type "  << bonustype;
1039     throw std::runtime_error(msg.str());
1040   }
1041
1042   return add_bonus(type);
1043 }
1044
1045 bool
1046 Player::add_bonus(BonusType type, bool animate)
1047 {
1048   // always ignore NO_BONUS
1049   if (type == NO_BONUS) {
1050     return true;
1051   }
1052
1053   // ignore GROWUP_BONUS if we're already big
1054   if (type == GROWUP_BONUS) {
1055     if (!player_status->bonus == NO_BONUS)
1056       return true;
1057   }
1058
1059   return set_bonus(type, animate);
1060 }
1061
1062 bool
1063 Player::set_bonus(BonusType type, bool animate)
1064 {
1065   if((player_status->bonus == NO_BONUS) && (type != NO_BONUS)) {
1066     if (!adjust_height(BIG_TUX_HEIGHT)) {
1067       log_debug << "Can't adjust Tux height" << std::endl;
1068       return false;
1069     }
1070     if(animate) {
1071       growing = true;
1072       sprite->set_action((dir == LEFT)?"grow-left":"grow-right", 1);
1073     }
1074     if (climbing) stop_climbing(*climbing);
1075   }
1076
1077   if (type == NO_BONUS) {
1078     if (does_buttjump) does_buttjump = false;
1079   }
1080
1081   if ((type == NO_BONUS) || (type == GROWUP_BONUS)) {
1082     if ((player_status->bonus == FIRE_BONUS) && (animate)) {
1083       // visually lose helmet
1084       Vector ppos = Vector((bbox.p1.x + bbox.p2.x) / 2, bbox.p1.y);
1085       Vector pspeed = Vector(((dir==LEFT) ? +100 : -100), -300);
1086       Vector paccel = Vector(0, 1000);
1087       std::string action = (dir==LEFT)?"left":"right";
1088       Sector::current()->add_object(std::make_shared<SpriteParticle>("images/objects/particles/firetux-helmet.sprite", action, ppos, ANCHOR_TOP, pspeed, paccel, LAYER_OBJECTS-1));
1089       if (climbing) stop_climbing(*climbing);
1090     }
1091     if ((player_status->bonus == ICE_BONUS) && (animate)) {
1092       // visually lose cap
1093       Vector ppos = Vector((bbox.p1.x + bbox.p2.x) / 2, bbox.p1.y);
1094       Vector pspeed = Vector(((dir==LEFT) ? +100 : -100), -300);
1095       Vector paccel = Vector(0, 1000);
1096       std::string action = (dir==LEFT)?"left":"right";
1097       Sector::current()->add_object(std::make_shared<SpriteParticle>("images/objects/particles/icetux-cap.sprite", action, ppos, ANCHOR_TOP, pspeed, paccel, LAYER_OBJECTS-1));
1098       if (climbing) stop_climbing(*climbing);
1099     }
1100     if ((player_status->bonus == AIR_BONUS) && (animate)) {
1101       // visually lose hat
1102       Vector ppos = Vector((bbox.p1.x + bbox.p2.x) / 2, bbox.p1.y);
1103       Vector pspeed = Vector(((dir==LEFT) ? +100 : -100), -300);
1104       Vector paccel = Vector(0, 1000);
1105       std::string action = (dir==LEFT)?"left":"right";
1106       Sector::current()->add_object(std::make_shared<SpriteParticle>("images/objects/particles/airtux-hat.sprite", action, ppos, ANCHOR_TOP, pspeed, paccel, LAYER_OBJECTS-1));
1107       if (climbing) stop_climbing(*climbing);
1108     }
1109     if ((player_status->bonus == EARTH_BONUS) && (animate)) {
1110       // visually lose hard-hat
1111       Vector ppos = Vector((bbox.p1.x + bbox.p2.x) / 2, bbox.p1.y);
1112       Vector pspeed = Vector(((dir==LEFT) ? +100 : -100), -300);
1113       Vector paccel = Vector(0, 1000);
1114       std::string action = (dir==LEFT)?"left":"right";
1115       Sector::current()->add_object(std::make_shared<SpriteParticle>("images/objects/particles/earthtux-hardhat.sprite", action, ppos, ANCHOR_TOP, pspeed, paccel, LAYER_OBJECTS-1));
1116       if (climbing) stop_climbing(*climbing);
1117     }
1118     player_status->max_fire_bullets = 0;
1119     player_status->max_ice_bullets = 0;
1120     player_status->max_air_time = 0;
1121     player_status->max_earth_time = 0;
1122   }
1123   if (type == FIRE_BONUS) player_status->max_fire_bullets++;
1124   if (type == ICE_BONUS) player_status->max_ice_bullets++;
1125   if (type == AIR_BONUS) player_status->max_air_time++;
1126   if (type == EARTH_BONUS) player_status->max_earth_time++;
1127
1128   player_status->bonus = type;
1129   return true;
1130 }
1131
1132 void
1133 Player::set_visible(bool visible_)
1134 {
1135   this->visible = visible_;
1136   if( visible_ )
1137     set_group(COLGROUP_MOVING);
1138   else
1139     set_group(COLGROUP_DISABLED);
1140 }
1141
1142 bool
1143 Player::get_visible()
1144 {
1145   return visible;
1146 }
1147
1148 void
1149 Player::kick()
1150 {
1151   kick_timer.start(KICK_TIME);
1152 }
1153
1154 void
1155 Player::draw(DrawingContext& context)
1156 {
1157   if(!visible)
1158     return;
1159
1160   // if Tux is above camera, draw little "air arrow" to show where he is x-wise
1161   if (Sector::current() && Sector::current()->camera && (get_bbox().p2.y - 16 < Sector::current()->camera->get_translation().y)) {
1162     float px = get_pos().x + (get_bbox().p2.x - get_bbox().p1.x - airarrow.get()->get_width()) / 2;
1163     float py = Sector::current()->camera->get_translation().y;
1164     py += std::min(((py - (get_bbox().p2.y + 16)) / 4), 16.0f);
1165     context.draw_surface(airarrow, Vector(px, py), LAYER_HUD - 1);
1166   }
1167
1168   std::string sa_prefix = "";
1169   std::string sa_postfix = "";
1170
1171   if (player_status->bonus == GROWUP_BONUS)
1172     sa_prefix = "big";
1173   else if (player_status->bonus == FIRE_BONUS)
1174     sa_prefix = "fire";
1175   else if (player_status->bonus == ICE_BONUS)
1176     sa_prefix = "ice";
1177   else if (player_status->bonus == AIR_BONUS)
1178     sa_prefix = "ice";
1179   else if (player_status->bonus == EARTH_BONUS)
1180     sa_prefix = "earth";
1181   else
1182     sa_prefix = "small";
1183
1184   if(dir == LEFT)
1185     sa_postfix = "-left";
1186   else
1187     sa_postfix = "-right";
1188
1189   /* Set Tux sprite action */
1190   if(dying) {
1191     sprite->set_action("gameover");
1192   }
1193   else if (growing) {
1194     sprite->set_action_continued("grow"+sa_postfix);
1195     // while growing, do not change action
1196     // do_duck() will take care of cancelling growing manually
1197     // update() will take care of cancelling when growing completed
1198   }
1199   else if (stone) {
1200     sprite->set_action(sprite->get_action()+"-stone");
1201   }
1202   else if (climbing) {
1203     sprite->set_action(sa_prefix+"-climbing"+sa_postfix);
1204   }
1205   else if (backflipping) {
1206     sprite->set_action(sa_prefix+"-backflip"+sa_postfix);
1207   }
1208   else if (duck && is_big()) {
1209     sprite->set_action(sa_prefix+"-duck"+sa_postfix);
1210   }
1211   else if (skidding_timer.started() && !skidding_timer.check()) {
1212     sprite->set_action(sa_prefix+"-skid"+sa_postfix);
1213   }
1214   else if (kick_timer.started() && !kick_timer.check()) {
1215     sprite->set_action(sa_prefix+"-kick"+sa_postfix);
1216   }
1217   else if ((wants_buttjump || does_buttjump) && is_big()) {
1218     sprite->set_action(sa_prefix+"-buttjump"+sa_postfix);
1219   }
1220   else if (!on_ground() || fall_mode != ON_GROUND) {
1221     if(physic.get_velocity_x() != 0 || fall_mode != ON_GROUND) {
1222         sprite->set_action(sa_prefix+"-jump"+sa_postfix);
1223     }
1224   }
1225   else {
1226     if (fabsf(physic.get_velocity_x()) < 1.0f) {
1227       // Determine which idle stage we're at
1228       if (sprite->get_action().find("-stand-") == std::string::npos && sprite->get_action().find("-idle-") == std::string::npos) {
1229         idle_stage = 0;
1230         idle_timer.start(IDLE_TIME[idle_stage]/1000.0f);
1231
1232         sprite->set_action_continued(sa_prefix+("-" + IDLE_STAGES[idle_stage])+sa_postfix);
1233       }
1234       else if (idle_timer.check() || (IDLE_TIME[idle_stage] == 0 && sprite->animation_done())) {
1235         idle_stage++;
1236         if (idle_stage >= IDLE_STAGE_COUNT)
1237           idle_stage = 1;
1238
1239         idle_timer.start(IDLE_TIME[idle_stage]/1000.0f);
1240
1241         if (IDLE_TIME[idle_stage] == 0)
1242           sprite->set_action(sa_prefix+("-" + IDLE_STAGES[idle_stage])+sa_postfix, 1);
1243         else
1244           sprite->set_action(sa_prefix+("-" + IDLE_STAGES[idle_stage])+sa_postfix);
1245       }
1246       else {
1247         sprite->set_action_continued(sa_prefix+("-" + IDLE_STAGES[idle_stage])+sa_postfix);
1248       }
1249     }
1250     else {
1251       sprite->set_action(sa_prefix+"-walk"+sa_postfix);
1252     }
1253   }
1254
1255   /* Set Tux powerup sprite action */
1256   if (player_status->bonus == EARTH_BONUS) {
1257     powersprite->set_action(sprite->get_action());
1258     lightsprite->set_action(sprite->get_action());
1259   }
1260
1261   /*
1262   // Tux is holding something
1263   if ((grabbed_object != 0 && physic.get_velocity_y() == 0) ||
1264   (shooting_timer.get_timeleft() > 0 && !shooting_timer.check())) {
1265   if (duck) {
1266   } else {
1267   }
1268   }
1269   */
1270
1271   /* Draw Tux */
1272   if (safe_timer.started() && size_t(game_time*40)%2)
1273     ;  // don't draw Tux
1274   else if (player_status->bonus == EARTH_BONUS){ // draw special effects with earthflower bonus
1275     // shake at end of maximum stone duration
1276     Vector shake_delta = (stone && ability_timer.get_timeleft() < 1.0f) ? Vector(graphicsRandom.rand(-3,3), 0) : Vector(0,0);
1277     sprite->draw(context, get_pos() + shake_delta, LAYER_OBJECTS + 1);
1278     // draw hardhat
1279     powersprite->draw(context, get_pos(), LAYER_OBJECTS + 1);
1280     // light
1281     context.push_target();
1282     context.set_target(DrawingContext::LIGHTMAP);
1283     lightsprite->draw(context, get_pos()/* + Vector(dir==LEFT ? 0 : 32, 0)*/, 0);
1284     context.pop_target();
1285     // give an indicator that stone form cannot be used for a while
1286     if (cooldown_timer.started() && graphicsRandom.rand(0, 4) == 0) {
1287       float px = graphicsRandom.randf(bbox.p1.x, bbox.p2.x);
1288       float py = bbox.p2.y+8;
1289       Vector ppos = Vector(px, py);
1290       Sector::current()->add_object(std::make_shared<SpriteParticle>(
1291         "images/objects/particles/sparkle.sprite", "dark",
1292         ppos, ANCHOR_MIDDLE, Vector(0, 0), Vector(0, 0), LAYER_OBJECTS+1+5));
1293     }
1294   }
1295   else
1296     sprite->draw(context, get_pos(), LAYER_OBJECTS + 1);
1297
1298 }
1299
1300 void
1301 Player::collision_tile(uint32_t tile_attributes)
1302 {
1303   if(tile_attributes & Tile::HURTS)
1304     kill(false);
1305
1306 #ifdef SWIMMING
1307   if( swimming ){
1308     if( tile_attributes & Tile::WATER ){
1309       no_water = false;
1310     } else {
1311       swimming = false;
1312     }
1313   } else {
1314     if( tile_attributes & Tile::WATER ){
1315       swimming = true;
1316       no_water = false;
1317       SoundManager::current()->play( "sounds/splash.ogg" );
1318     }
1319   }
1320 #endif
1321
1322   if(tile_attributes & Tile::ICE) {
1323     ice_this_frame = true;
1324     on_ice = true;
1325   }
1326 }
1327
1328 void
1329 Player::collision_solid(const CollisionHit& hit)
1330 {
1331   if(hit.bottom) {
1332     if(physic.get_velocity_y() > 0)
1333       physic.set_velocity_y(0);
1334
1335     on_ground_flag = true;
1336     floor_normal = hit.slope_normal;
1337
1338     // Butt Jump landed
1339     if (does_buttjump) {
1340       does_buttjump = false;
1341       physic.set_velocity_y(-300);
1342       on_ground_flag = false;
1343       Sector::current()->add_object(std::make_shared<Particles>(
1344                                       Vector(get_bbox().p2.x, get_bbox().p2.y),
1345                                       270+20, 270+40,
1346                                       Vector(280, -260), Vector(0, 300), 3, Color(.4f, .4f, .4f), 3, .8f,
1347                                       LAYER_OBJECTS+1));
1348       Sector::current()->add_object(std::make_shared<Particles>(
1349                                       Vector(get_bbox().p1.x, get_bbox().p2.y),
1350                                       90-40, 90-20,
1351                                       Vector(280, -260), Vector(0, 300), 3, Color(.4f, .4f, .4f), 3, .8f,
1352                                       LAYER_OBJECTS+1));
1353       Sector::current()->camera->shake(.1f, 0, 5);
1354     }
1355
1356   } else if(hit.top) {
1357     if(physic.get_velocity_y() < 0)
1358       physic.set_velocity_y(.2f);
1359   }
1360
1361   if(hit.left || hit.right) {
1362     physic.set_velocity_x(0);
1363   }
1364
1365   // crushed?
1366   if(hit.crush) {
1367     if(hit.left || hit.right) {
1368       kill(true);
1369     } else if(hit.top || hit.bottom) {
1370       kill(false);
1371     }
1372   }
1373 }
1374
1375 HitResponse
1376 Player::collision(GameObject& other, const CollisionHit& hit)
1377 {
1378   Bullet* bullet = dynamic_cast<Bullet*> (&other);
1379   if(bullet) {
1380     return FORCE_MOVE;
1381   }
1382
1383   Player* player = dynamic_cast<Player*> (&other);
1384   if(player) {
1385     return ABORT_MOVE;
1386   }
1387
1388   if(hit.left || hit.right) {
1389     try_grab(); //grab objects right now, in update it will be too late
1390   }
1391   assert(dynamic_cast<MovingObject*> (&other) != NULL);
1392   MovingObject* moving_object = static_cast<MovingObject*> (&other);
1393   if(moving_object->get_group() == COLGROUP_TOUCHABLE) {
1394     TriggerBase* trigger = dynamic_cast<TriggerBase*> (&other);
1395     if(trigger) {
1396       if(controller->pressed(Controller::UP))
1397         trigger->event(*this, TriggerBase::EVENT_ACTIVATE);
1398     }
1399
1400     return FORCE_MOVE;
1401   }
1402
1403   BadGuy* badguy = dynamic_cast<BadGuy*> (&other);
1404   if(badguy != NULL) {
1405     if(safe_timer.started() || invincible_timer.started())
1406       return FORCE_MOVE;
1407     if(stone)
1408       return ABORT_MOVE;
1409
1410     return CONTINUE;
1411   }
1412
1413   return CONTINUE;
1414 }
1415
1416 void
1417 Player::make_invincible()
1418 {
1419   SoundManager::current()->play("sounds/invincible_start.ogg");
1420   invincible_timer.start(TUX_INVINCIBLE_TIME);
1421   Sector::current()->play_music(HERRING_MUSIC);
1422 }
1423
1424 /* Kill Player! */
1425 void
1426 Player::kill(bool completely)
1427 {
1428   if(dying || deactivated || is_winning() )
1429     return;
1430
1431   if(!completely && (safe_timer.started() || invincible_timer.started() || stone))
1432     return;
1433
1434   growing = false;
1435
1436   if (climbing) stop_climbing(*climbing);
1437
1438   physic.set_velocity_x(0);
1439
1440   sprite->set_angle(0.0f);
1441
1442   if(!completely && is_big()) {
1443     SoundManager::current()->play("sounds/hurt.wav");
1444
1445     if(player_status->bonus == FIRE_BONUS
1446       || player_status->bonus == ICE_BONUS
1447       || player_status->bonus == AIR_BONUS
1448       || player_status->bonus == EARTH_BONUS) {
1449       safe_timer.start(TUX_SAFE_TIME);
1450       set_bonus(GROWUP_BONUS, true);
1451     } else if(player_status->bonus == GROWUP_BONUS) {
1452       safe_timer.start(TUX_SAFE_TIME /* + GROWING_TIME */);
1453       adjust_height(SMALL_TUX_HEIGHT);
1454       duck = false;
1455       backflipping = false;
1456       sprite->set_angle(0.0f);
1457       set_bonus(NO_BONUS, true);
1458     } else if(player_status->bonus == NO_BONUS) {
1459       safe_timer.start(TUX_SAFE_TIME);
1460       adjust_height(SMALL_TUX_HEIGHT);
1461       duck = false;
1462     }
1463   } else {
1464     SoundManager::current()->play("sounds/kill.wav");
1465
1466     // do not die when in edit mode
1467     if (edit_mode) {
1468       set_ghost_mode(true);
1469       return;
1470     }
1471
1472     if (player_status->coins >= 25 && !GameSession::current()->get_reset_point_sectorname().empty())
1473     {
1474       for (int i = 0; i < 5; i++)
1475       {
1476         // the numbers: starting x, starting y, velocity y
1477         Sector::current()->add_object(std::make_shared<FallingCoin>(get_pos() +
1478                                                       Vector(graphicsRandom.rand(5), graphicsRandom.rand(-32,18)),
1479                                                       graphicsRandom.rand(-100,100)));
1480       }
1481       player_status->coins -= std::max(player_status->coins/10, 25);
1482     }
1483     else
1484     {
1485       GameSession::current()->set_reset_point("", Vector());
1486     }
1487     physic.enable_gravity(true);
1488     physic.set_gravity_modifier(1.0f); // Undo jump_early_apex
1489     safe_timer.stop();
1490     invincible_timer.stop();
1491     physic.set_acceleration(0, 0);
1492     physic.set_velocity(0, -700);
1493     set_bonus(NO_BONUS, true);
1494     dying = true;
1495     dying_timer.start(3.0);
1496     set_group(COLGROUP_DISABLED);
1497
1498     // TODO: need nice way to handle players dying in co-op mode
1499     Sector::current()->effect->fade_out(3.0);
1500     SoundManager::current()->stop_music(3.0);
1501   }
1502 }
1503
1504 void
1505 Player::move(const Vector& vector)
1506 {
1507   set_pos(vector);
1508
1509   // Reset size to get correct hitbox if Tux was eg. ducked before moving
1510   if(is_big())
1511     set_size(TUX_WIDTH, BIG_TUX_HEIGHT);
1512   else
1513     set_size(TUX_WIDTH, SMALL_TUX_HEIGHT);
1514   duck = false;
1515   backflipping = false;
1516   sprite->set_angle(0.0f);
1517   last_ground_y = vector.y;
1518   if (climbing) stop_climbing(*climbing);
1519
1520   physic.reset();
1521 }
1522
1523 void
1524 Player::check_bounds()
1525 {
1526   /* Keep tux in sector bounds: */
1527   if (get_pos().x < 0) {
1528     // Lock Tux to the size of the level, so that he doesn't fall off
1529     // the left side
1530     set_pos(Vector(0, get_pos().y));
1531   }
1532
1533   if (get_bbox().get_right() > Sector::current()->get_width()) {
1534     // Lock Tux to the size of the level, so that he doesn't fall off
1535     // the right side
1536     set_pos(Vector(Sector::current()->get_width() - get_bbox().get_width(), get_pos().y));
1537   }
1538
1539   /* fallen out of the level? */
1540   if ((get_pos().y > Sector::current()->get_height()) && (!ghost_mode)) {
1541     kill(true);
1542     return;
1543   }
1544 }
1545
1546 void
1547 Player::add_velocity(const Vector& velocity)
1548 {
1549   physic.set_velocity(physic.get_velocity() + velocity);
1550 }
1551
1552 void
1553 Player::add_velocity(const Vector& velocity, const Vector& end_speed)
1554 {
1555   if (end_speed.x > 0)
1556     physic.set_velocity_x(std::min(physic.get_velocity_x() + velocity.x, end_speed.x));
1557   if (end_speed.x < 0)
1558     physic.set_velocity_x(std::max(physic.get_velocity_x() + velocity.x, end_speed.x));
1559   if (end_speed.y > 0)
1560     physic.set_velocity_y(std::min(physic.get_velocity_y() + velocity.y, end_speed.y));
1561   if (end_speed.y < 0)
1562     physic.set_velocity_y(std::max(physic.get_velocity_y() + velocity.y, end_speed.y));
1563 }
1564
1565 Vector
1566 Player::get_velocity()
1567 {
1568   return physic.get_velocity();
1569 }
1570
1571 void
1572 Player::bounce(BadGuy& )
1573 {
1574   if(!(player_status->bonus == AIR_BONUS))
1575     physic.set_velocity_y(controller->hold(Controller::JUMP) ? -520 : -300);
1576   else {
1577     physic.set_velocity_y(controller->hold(Controller::JUMP) ? -580 : -340);
1578     ability_time = player_status->max_air_time * GLIDE_TIME_PER_FLOWER;
1579   }
1580 }
1581
1582 //scripting Functions Below
1583
1584 void
1585 Player::deactivate()
1586 {
1587   if (deactivated)
1588     return;
1589   deactivated = true;
1590   physic.set_velocity_x(0);
1591   physic.set_velocity_y(0);
1592   physic.set_acceleration_x(0);
1593   physic.set_acceleration_y(0);
1594   if (climbing) stop_climbing(*climbing);
1595 }
1596
1597 void
1598 Player::activate()
1599 {
1600   if (!deactivated)
1601     return;
1602   deactivated = false;
1603 }
1604
1605 void Player::walk(float speed)
1606 {
1607   physic.set_velocity_x(speed);
1608 }
1609
1610 void Player::set_dir(bool right)
1611 {
1612   dir = right ? RIGHT : LEFT;
1613 }
1614
1615 void
1616 Player::set_ghost_mode(bool enable)
1617 {
1618   if (ghost_mode == enable)
1619     return;
1620
1621   if (climbing) stop_climbing(*climbing);
1622
1623   if (enable) {
1624     ghost_mode = true;
1625     set_group(COLGROUP_DISABLED);
1626     physic.enable_gravity(false);
1627     log_debug << "You feel lightheaded. Use movement controls to float around, press ACTION to scare badguys." << std::endl;
1628   } else {
1629     ghost_mode = false;
1630     set_group(COLGROUP_MOVING);
1631     physic.enable_gravity(true);
1632     log_debug << "You feel solid again." << std::endl;
1633   }
1634 }
1635
1636 void
1637 Player::set_edit_mode(bool enable)
1638 {
1639   edit_mode = enable;
1640 }
1641
1642 void
1643 Player::start_climbing(Climbable& climbable)
1644 {
1645   if (climbing || !&climbable) return;
1646
1647   climbing = &climbable;
1648   physic.enable_gravity(false);
1649   physic.set_velocity(0, 0);
1650   physic.set_acceleration(0, 0);
1651   if (backflipping) {
1652     backflipping = false;
1653     backflip_direction = 0;
1654     sprite->set_angle(0.0f);
1655   }
1656 }
1657
1658 void
1659 Player::stop_climbing(Climbable& /*climbable*/)
1660 {
1661   if (!climbing) return;
1662
1663   climbing = 0;
1664
1665   if (grabbed_object) {
1666     grabbed_object->ungrab(*this, dir);
1667     grabbed_object = NULL;
1668   }
1669
1670   physic.enable_gravity(true);
1671   physic.set_velocity(0, 0);
1672   physic.set_acceleration(0, 0);
1673
1674   if ((controller->hold(Controller::JUMP)) || (controller->hold(Controller::UP))) {
1675     on_ground_flag = true;
1676     // TODO: This won't help. Why?
1677     do_jump(-300);
1678   }
1679 }
1680
1681 void
1682 Player::handle_input_climbing()
1683 {
1684   if (!climbing) {
1685     log_warning << "handle_input_climbing called with climbing set to 0. Input handling skipped" << std::endl;
1686     return;
1687   }
1688
1689   float vx = 0;
1690   float vy = 0;
1691   if (controller->hold(Controller::LEFT)) {
1692     dir = LEFT;
1693     vx -= MAX_CLIMB_XM;
1694   }
1695   if (controller->hold(Controller::RIGHT)) {
1696     dir = RIGHT;
1697     vx += MAX_CLIMB_XM;
1698   }
1699   if (controller->hold(Controller::UP)) {
1700     vy -= MAX_CLIMB_YM;
1701   }
1702   if (controller->hold(Controller::DOWN)) {
1703     vy += MAX_CLIMB_YM;
1704   }
1705   if (controller->hold(Controller::JUMP)) {
1706     if (can_jump) {
1707       stop_climbing(*climbing);
1708       return;
1709     }
1710   } else {
1711     can_jump = true;
1712   }
1713   if (controller->hold(Controller::ACTION)) {
1714     stop_climbing(*climbing);
1715     return;
1716   }
1717   physic.set_velocity(vx, vy);
1718   physic.set_acceleration(0, 0);
1719 }
1720
1721 /* EOF */