Fixed crashes when restrating level
[ghostsoverboard] / timercontrolledtursas.cpp
1 #include "timercontrolledtursas.h"
2 #include <QGraphicsScene>
3 #include <QDebug>
4
5
6 TimerControlledTursas::TimerControlledTursas(QPixmap pixmap, int speed, QGraphicsItem* parent) :
7     QObject(), QGraphicsPixmapItem(pixmap, parent)
8 {
9     setSpeed(speed);
10     direction_ = S;
11     connect(&timer_,SIGNAL(timeout()),this,SLOT(move()));
12 }
13
14 void TimerControlledTursas::startMoving()
15 {
16     timer_.start();
17 }
18
19 void TimerControlledTursas::stopMoving()
20 {
21     timer_.stop();
22 }
23
24 void TimerControlledTursas::setSpeed(int speed)
25 {
26     timer_.setInterval(1000/speed); //converts from pixels in second to milliseconds per pixel
27 }
28
29 void TimerControlledTursas::move()
30 {
31
32     int oldx = x();
33     int oldy = y();
34
35     int newx = oldx;
36     int newy = oldy;
37
38
39     //calculate the new position
40
41     if (direction_ == E || direction_ == SE || direction_ == NE)
42     {
43         newx++;
44     }
45
46     if (direction_ == W || direction_ == SW || direction_ == NW)
47     {
48         newx--;
49     }
50
51     if (direction_ == S || direction_ == SE || direction_ == SW)
52     {
53         newy++;
54     }
55
56     if (direction_ == N || direction_ == NE || direction_ == NW)
57     {
58         newy--;
59     }
60
61
62
63     //Bound the item into the scene and change direction if hitting a boundary
64     //Only works if the old position is inside the boundaries
65
66     if (!scene()) //no movement if this item does not belong to a scene
67         return;
68
69     QRect sceneRectangle = scene()->sceneRect().toRect();
70
71     if (newx < sceneRectangle.left() || newx > sceneRectangle.right())
72     {
73         changeDirection();
74         return;
75     }
76
77
78     if (newy < sceneRectangle.top() || newy > sceneRectangle.bottom())
79     {
80         changeDirection();
81         return;     //the old x and y values remain intact
82     }
83
84
85     //Set the new position
86
87     setX(newx);
88     setY(newy);
89
90
91     //If the new position would collide with anything, go back to the old position and change direction
92
93     QList<QGraphicsItem*>  collidesList = collidingItems();
94     if (!collidesList.isEmpty())
95     {
96         setX(oldx);
97         setY(oldy);
98         changeDirection();
99     }
100
101
102 }
103
104 void TimerControlledTursas::changeDirection()
105 {
106    // direction_ = rand()/8;
107
108 }
109