Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/trunk/src/modules/pong/PongBall.cc @ 10685

Last change on this file since 10685 was 9945, checked in by landauf, 11 years ago

replaced tabs with spaces. no changes in code

  • Property svn:eol-style set to native
File size: 12.6 KB
Line 
1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *                    > www.orxonox.net <
4 *
5 *
6 *   License notice:
7 *
8 *   This program is free software; you can redistribute it and/or
9 *   modify it under the terms of the GNU General Public License
10 *   as published by the Free Software Foundation; either version 2
11 *   of the License, or (at your option) any later version.
12 *
13 *   This program is distributed in the hope that it will be useful,
14 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 *   GNU General Public License for more details.
17 *
18 *   You should have received a copy of the GNU General Public License
19 *   along with this program; if not, write to the Free Software
20 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 *
22 *   Author:
23 *      Fabian 'x3n' Landau
24 *   Co-authors:
25 *      ...
26 *
27 */
28
29/**
30    @file PongBall.cc
31    @brief Implementation of the PongBall class.
32*/
33
34#include "PongBall.h"
35
36#include "core/CoreIncludes.h"
37#include "core/GameMode.h"
38
39#include "gametypes/Gametype.h"
40
41#include "PongBat.h"
42
43#include "sound/WorldSound.h"
44#include "core/XMLPort.h"
45
46namespace orxonox
47{
48    RegisterClass(PongBall);
49
50    const float PongBall::MAX_REL_Z_VELOCITY = 1.5;
51
52    /**
53    @brief
54        Constructor. Registers and initializes the object.
55    */
56    PongBall::PongBall(Context* context)
57        : MovableEntity(context)
58    {
59        RegisterObject(PongBall);
60
61        this->speed_ = 0;
62        this->accelerationFactor_ = 1.0f;
63        this->bat_ = 0;
64        this->bDeleteBats_ = false;
65        this->batID_ = new unsigned int[2];
66        this->batID_[0] = OBJECTID_UNKNOWN;
67        this->batID_[1] = OBJECTID_UNKNOWN;
68        this->relMercyOffset_ = 0.05f;
69
70        this->registerVariables();
71
72        //initialize sound
73        if (GameMode::isMaster())
74             {
75                 this->defScoreSound_ = new WorldSound(this->getContext());
76                 this->defScoreSound_->setVolume(1.0f);
77                 this->defBatSound_ = new WorldSound(this->getContext());
78                 this->defBatSound_->setVolume(0.4f);
79                 this->defBoundarySound_ = new WorldSound(this->getContext());
80                 this->defBoundarySound_->setVolume(0.5f);
81             }
82             else
83             {
84                 this->defScoreSound_ = 0;
85                 this->defBatSound_ = 0;
86                 this->defBoundarySound_ = 0;
87             }
88    }
89
90    /**
91    @brief
92        Destructor.
93    */
94    PongBall::~PongBall()
95    {
96        if (this->isInitialized())
97        {
98            if (this->bDeleteBats_)
99                delete[] this->bat_;
100
101            delete[] this->batID_;
102        }
103    }
104
105    //xml port for loading sounds
106    void PongBall::XMLPort(Element& xmlelement, XMLPort::Mode mode)
107    {
108        SUPER(PongBall, XMLPort, xmlelement, mode);
109        XMLPortParam(PongBall, "defScoreSound",  setDefScoreSound,  getDefScoreSound,  xmlelement, mode);
110        XMLPortParam(PongBall, "defBatSound",  setDefBatSound,  getDefBatSound,  xmlelement, mode);
111        XMLPortParam(PongBall, "defBoundarySound",  setDefBoundarySound,  getDefBoundarySound,  xmlelement, mode);
112    }
113
114    /**
115    @brief
116        Register variables to synchronize over the network.
117    */
118    void PongBall::registerVariables()
119    {
120        registerVariable( this->fieldWidth_ );
121        registerVariable( this->fieldHeight_ );
122        registerVariable( this->batlength_ );
123        registerVariable( this->speed_ );
124        registerVariable( this->relMercyOffset_ );
125        registerVariable( this->batID_[0] );
126        registerVariable( this->batID_[1], VariableDirection::ToClient, new NetworkCallback<PongBall>( this, &PongBall::applyBats) );
127    }
128
129    /**
130    @brief
131        Is called every tick.
132        Handles the movement of the ball and its interaction with the boundaries and bats.
133    @param dt
134        The time since the last tick.
135    */
136    void PongBall::tick(float dt)
137    {
138        SUPER(PongBall, tick, dt);
139
140        // Get the current position, velocity and acceleration of the ball.
141        Vector3 position = this->getPosition();
142        Vector3 velocity = this->getVelocity();
143        Vector3 acceleration = this->getAcceleration();
144
145        // If the ball has gone over the top or bottom boundary of the playing field (i.e. the ball has hit the top or bottom delimiters).
146        if (position.z > this->fieldHeight_ / 2 || position.z < -this->fieldHeight_ / 2)
147        {
148            defBoundarySound_->play(); //play boundary sound
149            // Its velocity in z-direction is inverted (i.e. it bounces off).
150            velocity.z = -velocity.z;
151            // And its position is set as to not overstep the boundary it has just crossed.
152            if (position.z > this->fieldHeight_ / 2)
153                position.z = this->fieldHeight_ / 2;
154            if (position.z < -this->fieldHeight_ / 2)
155                position.z = -this->fieldHeight_ / 2;
156
157            this->fireEvent();
158        }
159
160        // If the ball has crossed the left or right boundary of the playing field (i.e. a player has just scored, if the bat isn't there to parry).
161        if (position.x > this->fieldWidth_ / 2 || position.x < -this->fieldWidth_ / 2)
162        {
163            float distance = 0;
164
165            if (this->bat_ != NULL) // If there are bats.
166            {
167                // If the right boundary has been crossed.
168                if (position.x > this->fieldWidth_ / 2 && this->bat_[1] != NULL)
169                {
170                    // Calculate the distance (in z-direction) between the ball and the center of the bat, weighted by half of the effective length of the bat (with additional 10%)
171                    distance = (position.z - this->bat_[1]->getPosition().z) / (this->fieldHeight_ * (this->batlength_ * 1.10f) / 2);
172                    if (fabs(distance) <= 1) // If the bat is there to parry.
173                    {
174                        defBatSound_->play(); //play bat sound
175                        // Set the ball to be exactly at the boundary.
176                        position.x = this->fieldWidth_ / 2;
177                        // Invert its velocity in x-direction (i.e. it bounces off).
178                        velocity.x = -velocity.x;
179                        // Adjust the velocity in the z-direction, depending on where the ball hit the bat.
180                        velocity.z = distance * distance * sgn(distance) * PongBall::MAX_REL_Z_VELOCITY * this->speed_;
181                        acceleration = this->bat_[1]->getVelocity() * this->accelerationFactor_ * -1;
182
183                        this->fireEvent();
184                    }
185                    // If the left player scores.
186                    else if (GameMode::isMaster() && position.x > this->fieldWidth_ / 2 * (1 + this->relMercyOffset_))
187                    {
188                        defScoreSound_->play();//play score sound
189                        if (this->getGametype() && this->bat_[0])
190                        {
191                            this->getGametype()->playerScored(this->bat_[0]->getPlayer());
192                            return;
193                        }
194                    }
195                }
196                // If the left boundary has been crossed.
197                else if (position.x < -this->fieldWidth_ / 2 && this->bat_[0] != NULL)
198                {
199                    // Calculate the distance (in z-direction) between the ball and the center of the bat, weighted by half of the effective length of the bat (with additional 10%)
200                    distance = (position.z - this->bat_[0]->getPosition().z) / (this->fieldHeight_ * (this->batlength_ * 1.10f) / 2);
201                    if (fabs(distance) <= 1) // If the bat is there to parry.
202                    {
203                        defBatSound_->play(); //play bat sound
204                        // Set the ball to be exactly at the boundary.
205                        position.x = -this->fieldWidth_ / 2;
206                        // Invert its velocity in x-direction (i.e. it bounces off).
207                        velocity.x = -velocity.x;
208                        // Adjust the velocity in the z-direction, depending on where the ball hit the bat.
209                        velocity.z = distance * distance * sgn(distance) * PongBall::MAX_REL_Z_VELOCITY * this->speed_;
210                        acceleration = this->bat_[0]->getVelocity() * this->accelerationFactor_ * -1;
211
212                        this->fireEvent();
213                    }
214                    // If the right player scores.
215                    else if (GameMode::isMaster() && position.x < -this->fieldWidth_ / 2 * (1 + this->relMercyOffset_))
216                    {
217                        defScoreSound_->play();//play score sound
218                        if (this->getGametype() && this->bat_[1])
219                        {
220                            this->getGametype()->playerScored(this->bat_[1]->getPlayer());
221                            return;
222                        }
223                    }
224                }
225            }
226        }
227
228        // Set the position, velocity and acceleration of the ball, if they have changed.
229        if (acceleration != this->getAcceleration())
230            this->setAcceleration(acceleration);
231        if (velocity != this->getVelocity())
232            this->setVelocity(velocity);
233        if (position != this->getPosition())
234            this->setPosition(position);
235    }
236
237    /**
238    @brief
239        Set the speed of the ball (in x-direction).
240    @param speed
241        The speed to be set.
242    */
243    void PongBall::setSpeed(float speed)
244    {
245        if (speed != this->speed_) // If the speed changes
246        {
247            this->speed_ = speed;
248
249            // Set the speed in the direction of the balls current velocity.
250            Vector3 velocity = this->getVelocity();
251            if (velocity.x != 0)
252                velocity.x = sgn(velocity.x) * this->speed_;
253            else // If the balls current velocity is zero, the speed is set in a random direction.
254                velocity.x = this->speed_ * sgn(rnd(-1,1));
255
256            this->setVelocity(velocity);
257        }
258    }
259
260    /**
261    @brief
262        Set the bats for the ball.
263    @param bats
264        An array (of size 2) of weak pointers, to be set as the new bats.
265    */
266    void PongBall::setBats(WeakPtr<PongBat>* bats)
267    {
268        if (this->bDeleteBats_) // If there are already some bats, delete them.
269        {
270            delete[] this->bat_;
271            this->bDeleteBats_ = false;
272        }
273
274        this->bat_ = bats;
275        // Also store their object IDs, for synchronization.
276        this->batID_[0] = this->bat_[0]->getObjectID();
277        this->batID_[1] = this->bat_[1]->getObjectID();
278    }
279
280    /**
281    @brief
282        Get the bats over the network.
283    */
284    void PongBall::applyBats()
285    {
286        // Make space for the bats, if they don't exist, yet.
287        if (this->bat_ == NULL)
288        {
289            this->bat_ = new WeakPtr<PongBat>[2];
290            this->bDeleteBats_ = true;
291        }
292
293        if (this->batID_[0] != OBJECTID_UNKNOWN)
294            this->bat_[0] = orxonox_cast<PongBat*>(Synchronisable::getSynchronisable(this->batID_[0]));
295        if (this->batID_[1] != OBJECTID_UNKNOWN)
296            this->bat_[1] = orxonox_cast<PongBat*>(Synchronisable::getSynchronisable(this->batID_[1]));
297    }
298
299    void PongBall::setDefScoreSound(const std::string &pongSound)
300    {
301        if( defScoreSound_ )
302            defScoreSound_->setSource(pongSound);
303        else
304            assert(0); // This should never happen, because soundpointer is only available on master
305    }
306
307    const std::string& PongBall::getDefScoreSound()
308    {
309        if( defScoreSound_ )
310            return defScoreSound_->getSource();
311        else
312            assert(0);
313        return BLANKSTRING;
314    }
315
316    void PongBall::setDefBatSound(const std::string &pongSound)
317    {
318        if( defBatSound_ )
319            defBatSound_->setSource(pongSound);
320        else
321            assert(0); // This should never happen, because soundpointer is only available on master
322    }
323
324    const std::string& PongBall::getDefBatSound()
325    {
326        if( defBatSound_ )
327            return defBatSound_->getSource();
328        else
329            assert(0);
330        return BLANKSTRING;
331    }
332
333    void PongBall::setDefBoundarySound(const std::string &pongSound)
334    {
335        if( defBoundarySound_ )
336            defBoundarySound_->setSource(pongSound);
337        else
338            assert(0); // This should never happen, because soundpointer is only available on master
339    }
340
341    const std::string& PongBall::getDefBoundarySound()
342    {
343        if( defBoundarySound_ )
344            return defBoundarySound_->getSource();
345        else
346            assert(0);
347        return BLANKSTRING;
348    }
349}
Note: See TracBrowser for help on using the repository browser.