Timercontrolledtursas bounding and collision detection changes
[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
65     if (!scene()) //no movement if this item does not belong to a scene
66         return;
67
68     QRect sceneRectangle = scene()->sceneRect().toRect();
69
70     if (newx < sceneRectangle.left() || newx > sceneRectangle.right())
71     {
72         changeDirection();
73         return;
74     }
75
76
77     if (newy < sceneRectangle.top() || newy > sceneRectangle.bottom())
78     {
79         changeDirection();
80         return;     //the old x and y values remain intact
81     }
82
83
84     //Set the new position
85
86     setX(newx);
87     setY(newy);
88
89
90     //If the new position would collide with anything, go back to the old position and change direction
91
92     QList<QGraphicsItem*>  collidesList = collidingItems();
93     if (!collidesList.isEmpty())
94     {
95         setX(oldx);
96         setY(oldy);
97         changeDirection();
98     }
99
100
101 }
102
103 void TimerControlledTursas::changeDirection()
104 {
105    // direction_ = rand()/8;
106
107 }
108