PDA

View Full Version : Collision detect in QGraphicsScene



sophister
3rd December 2009, 15:11
Hello,
I am using QGraphicsScene , QGraphicsView and QGraphicsPixmapItem to write a game like Tank.
I have wrote a class Tank inherriting from QGraphicsPixmapItem, and when I press some key, like Space, it's function shoot() is called. And I want to new some bullet in this function, then let the bullet go straight along the current direction.
The class Bullet is inherriting from QGraphicsPixmapItem too.
The problem is, I do not know how to detect whether the bullet reaches the border or hit the enemy tank, if it hits some enemy tank, how to destroy that tank.

I am using Qt4.5
Thanks in advance!!

jano_alex_es
3rd December 2009, 18:15
QGraphicsItem::collidesWithItem, QGraphicsScene:: collidingItems

aamer4yu
4th December 2009, 06:33
You can also have a look at colliding mice example in Qt Demos under Graphics View section

sophister
4th December 2009, 17:19
Yes, I have read the mice example.
It uses a QTimer to check the collisions among the mice.
But I think the case is a little different, in my case, if I use a QTimer, and if many tanks are shooting, I can not imagine how to write those codes. And even if I use a QTimer, I haven't found any way to destroy the tank hit by one bullet.
It seems a long way to go...

You are right, but these two functions need to be called every time I want to know whether the bullet hit some tank during its lifetime.
If there is someway like, event loop, i.e, when the bullet hits a tank, an event is sent to both the bullet and that tank, then I can destroy the bullet and the tank.
But, it seems there is no such event as far as I can see.

aamer4yu
4th December 2009, 18:42
But, it seems there is no such event as far as I can see.
Even if there was such event, it would internally need to monitor items movement at regular intervals...
By the way in 4.6 theres also sub attack example...but I gues thats done using animation framework..dont know how collision detection is used in it..
may be u can check and let us know :)

wysota
4th December 2009, 19:37
The easiest way is to reimplement QGraphicsScene::advance(). It's called periodically (if you make it to be called of course) and you can easily detect collisions there, provided you have pointers to appropriate items.

sophister
5th December 2009, 02:38
Ok, I downloaded the QT4.6 just now.
I will study that sub attack example.
Thanks a lot!!

Hmm, I think I will set up a timer in my view and call the QGraphicsScene::advance() periodically.
Thanks a lot!!