Timercontrolledtursas bounding and collision detection changes
authorHeli Hyvättinen <heli.hyvattinen@kymp.net>
Tue, 17 May 2011 16:48:54 +0000 (19:48 +0300)
committerHeli Hyvättinen <heli.hyvattinen@kymp.net>
Tue, 17 May 2011 16:48:54 +0000 (19:48 +0300)
Bounding to scene now includes calling changeDirection(). (Which is
empty for now). Collision detection/prevention (which also calls
changeDirection()) added.

mainwindow.cpp
timercontrolledtursas.cpp
timercontrolledtursas.h

index 968ebeb..c508710 100644 (file)
@@ -48,7 +48,7 @@ MainWindow::MainWindow(QWidget *parent)
 
     TimerControlledTursas * pMustekala = new TimerControlledTursas (QPixmap(":/pix/tursas.png"),100);
     pScene_->addItem(pMustekala);
-
+    pMustekala->moveBy(100,100);
     pMustekala->startMoving();
 
 
index 187d5f1..520b94c 100644 (file)
@@ -29,15 +29,15 @@ void TimerControlledTursas::setSpeed(int speed)
 void TimerControlledTursas::move()
 {
 
-    if (!scene()) //no movement if this item does not belong to a scene
-        return;
-
     int oldx = x();
     int oldy = y();
 
     int newx = oldx;
     int newy = oldy;
 
+
+    //calculate the new position
+
     if (direction_ == E || direction_ == SE || direction_ == NE)
     {
         newx++;
@@ -59,14 +59,50 @@ void TimerControlledTursas::move()
     }
 
 
-    //These three lines are identical with the orientationcontrolled version - should there be a common base class with a function to handle this?
+
+    //Bound the item into the scene and change direction if hitting a boundary
+
+    if (!scene()) //no movement if this item does not belong to a scene
+        return;
 
     QRect sceneRectangle = scene()->sceneRect().toRect();
-    setX(qBound(sceneRectangle.left(),newx,sceneRectangle.right()-pixmap().width()));
-    setY(qBound(sceneRectangle.top(),newy,sceneRectangle.bottom()-pixmap().height()));
 
+    if (newx < sceneRectangle.left() || newx > sceneRectangle.right())
+    {
+        changeDirection();
+        return;
+    }
+
+
+    if (newy < sceneRectangle.top() || newy > sceneRectangle.bottom())
+    {
+        changeDirection();
+        return;     //the old x and y values remain intact
+    }
+
+
+    //Set the new position
+
+    setX(newx);
+    setY(newy);
+
+
+    //If the new position would collide with anything, go back to the old position and change direction
+
+    QList<QGraphicsItem*>  collidesList = collidingItems();
+    if (!collidesList.isEmpty())
+    {
+        setX(oldx);
+        setY(oldy);
+        changeDirection();
+    }
 
 
 }
 
+void TimerControlledTursas::changeDirection()
+{
+   // direction_ = rand()/8;
+
+}
 
index f82d22c..12316b1 100644 (file)
@@ -29,7 +29,9 @@ public slots:
     void setSpeed(int speed);
 
 
- private:
+ protected:
+
+    void changeDirection();
 
     QTimer timer_;