1 /**************************************************************************
2 Ghosts Overboard - a game for Maemo 5
4 Copyright (C) 2011 Heli Hyvättinen
6 This file is part of Ghosts Overboard
8 Ghosts Overboard is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 2 of the License, or
11 (at your option) any later version.
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.
18 You should have received a copy of the GNU General Public License
19 along with this program. If not, see <http://www.gnu.org/licenses/>.
21 **************************************************************************/
23 #include "timercontrolledgraphicspixmapobject.h"
24 #include <QGraphicsScene>
28 TimerControlledGraphicsPixmapObject::TimerControlledGraphicsPixmapObject(QPixmap pixmap, int speed, QGraphicsItem* parent) :
29 QObject(), QGraphicsPixmapItem(pixmap, parent)
34 connect(&timer_,SIGNAL(timeout()),this,SLOT(move()));
37 void TimerControlledGraphicsPixmapObject::startMoving()
39 if (!stoppedBecauseInvalidTime_)
43 void TimerControlledGraphicsPixmapObject::stopMoving()
48 void TimerControlledGraphicsPixmapObject::setSpeed(int speed)
52 timer_.setInterval(1000/(speed/pixelsPerMove_)); //converts from pixels in second to milliseconds per pixels moved at once
53 stoppedBecauseInvalidTime_ = false;
56 stoppedBecauseInvalidTime_ = true;
61 void TimerControlledGraphicsPixmapObject::move()
71 //calculate the new position
73 if (direction_ == E || direction_ == SE || direction_ == NE)
75 newx+= pixelsPerMove_;
78 if (direction_ == W || direction_ == SW || direction_ == NW)
83 if (direction_ == S || direction_ == SE || direction_ == SW)
88 if (direction_ == N || direction_ == NE || direction_ == NW)
95 //Bound the item into the scene and change direction if hitting a boundary
96 //Only works if the old position is inside the boundaries
98 if (!scene()) //no movement if this item does not belong to a scene
101 QRect sceneRectangle = scene()->sceneRect().toRect();
103 if (newx < sceneRectangle.left() || newx > sceneRectangle.right()-pixmap().width())
110 if (newy < sceneRectangle.top() || newy > sceneRectangle.bottom()-pixmap().height())
113 return; //the old x and y values remain intact
117 //Set the new position
123 //check for collisions and handle them (up to subclassess to implement)
124 //return to the old position if requested
126 if (handleCollisions() == false)
135 void TimerControlledGraphicsPixmapObject::changeDirection()
137 // qDebug () << "Supposed to change direction";
139 int direction = (qrand()%8);
140 // qDebug() << direction;
181 bool TimerControlledGraphicsPixmapObject::handleCollisions()