6276a09187daa2a733725e22c6d24bddd92a37d8
[supertux.git] / lib / math / physic.cpp
1 //  $Id$
2 // 
3 //  SuperTux
4 //  Copyright (C) 2004 Tobias Glaesser <tobi.web@gmx.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
19 //  02111-1307, USA.
20
21 #include <config.h>
22
23 #include <cstdio>
24
25 #include "math/physic.h"
26
27 using namespace SuperTux;
28
29 Physic::Physic()
30     : ax(0), ay(0), vx(0), vy(0), gravity_enabled(true)
31 {
32 }
33
34 Physic::~Physic()
35 {
36 }
37
38 void
39 Physic::reset()
40 {
41     ax = ay = vx = vy = 0;
42     gravity_enabled = true;
43 }
44
45 void
46 Physic::set_velocity_x(float nvx)
47 {
48   vx = nvx;
49 }
50
51 void
52 Physic::set_velocity_y(float nvy)
53 {
54   vy = -nvy;
55 }
56
57 void
58 Physic::set_velocity(float nvx, float nvy)
59 {
60   vx = nvx;
61   vy = -nvy;
62 }
63
64 void Physic::inverse_velocity_x()
65 {
66 vx = -vx;
67 }
68
69 void Physic::inverse_velocity_y()
70 {
71 vy = -vy;
72 }
73
74 float
75 Physic::get_velocity_x()
76 {
77     return vx;
78 }
79
80 float
81 Physic::get_velocity_y()
82 {
83     return -vy;
84 }
85
86 void
87 Physic::set_acceleration_x(float nax)
88 {
89   ax = nax;
90 }
91
92 void
93 Physic::set_acceleration_y(float nay)
94 {
95   ay = -nay;
96 }
97
98 void
99 Physic::set_acceleration(float nax, float nay)
100 {
101     ax = nax;
102     ay = -nay;
103 }
104
105 float
106 Physic::get_acceleration_x()
107 {
108     return ax;
109 }
110
111 float
112 Physic::get_acceleration_y()
113 {
114     return -ay;
115 }
116
117 void
118 Physic::enable_gravity(bool enable_gravity)
119 {
120   gravity_enabled = enable_gravity;
121 }
122
123 Vector
124 Physic::get_movement(float elapsed_time)
125 {
126   float grav = gravity_enabled ? 1000 : 0;
127   
128   Vector result(
129       vx * elapsed_time + ax * elapsed_time * elapsed_time,
130       vy * elapsed_time + (ay + grav) * elapsed_time * elapsed_time
131   );
132   vx += ax * elapsed_time;
133   vy += (ay + grav) * elapsed_time;  
134
135   return result;
136 }
137