PDA

View Full Version : Collision



MongKong
8th March 2020, 12:55
Hello !!!

So I'm making a game in which i have a working player (QGraphicsPixmapItem ) that can move. I implemented rocks and trees into the game that are of QGraphicsPixmapItem type.
What i want to know is if someone knows a better way for me to check for collision when destroying rocks and trees ?

The way i have it right now is like this :


When the player attacks i check if the item (slash which is also a QGraphicsPixmapItem ) has collided with the Tree or the Rock, but the problem appears when i'm trying to access a function inside the collided Tree or Rock
And the only solution i found out on how to that is

- first by checking if the slash item has hit the Tree

QList<QGraphicsItem *> colliding_items = slash->collidingItems();

for(int i=0;i<colliding_items.size();++i){
if(holding == "axe"){
if(typeid (*(colliding_items[i])) == typeid (Tree))
for(int k=0;k<3;k++)
game->tree[k]->checkCollision();
}else if(holding == "pickaxe"){
if(typeid (*(colliding_items[i])) == typeid (Rock))
for(int k=0;k<3;k++)
game->rock[k]->checkCollision();
}
}

- second going through all the created Trees and Rocks and check for collision again inside the Tree or Rock function ( checkCollision() ) in which i go again through another loop to check if it has collided with the slash item

void Rock::checkCollision()
{
QList<QGraphicsItem *> colliding_items = collidingItems();
for(int i=0;i<colliding_items.size();++i){
if(colliding_items[i] == game->player->slash){
hp--;
}
}
}


I made a dynamic table of trees and rocks but i hate doing it like that especially since i plan to have a lot more trees and rocks ( around 60 minimum ), if any1 knows a better more optimized way for me to do it, please share...

MongKong
8th March 2020, 21:04
I figured it out, if anyone else wants to know how i did it, here it is:

QList<QGraphicsItem *> colliding_items = slash->collidingItems();

for(int i=0;i<colliding_items.size();++i){
if(holding == "axe"){
if(Tree* asTree = dynamic_cast<Tree*>(colliding_items[i])){
asTree->collide();
break;
}
}else if(holding == "pickaxe"){
if(Rock* asRock = dynamic_cast<Rock*>(colliding_items[i])){
asRock->collide();
break;
}
}
}

d_stranz
9th March 2020, 17:10
Thanks. Next time I go into the woods with my axe and pickaxe, I'll know which one to use if I come across a tree or a rock...