I'm creating a 2D game using the Qt Framework. Although I do have some experience in some other languages, C++ is a kind of new language for me.
My first question is about the monsters. How should I initialize(and store them) ? Every level of my game has a different number of mobs. At this moment I initialize them in this way:
Monster *mobs;
mobs = new Monster[mobsQuantity];
But I am not sure this is the best way to do it. Also, every second, every mob positioned on the map must move by 1 position. This is the function that should move the mobs.
void MainWindow::moveMobs(){
int random[mobsQuantity]; // Different random position move for each monster.
for(int a = 0; a < mobsQuantity; a++){
random[a] = qrand() % 5; // Initialize the moves
}
for(int a = 0; a < mobsQuantity; a++){
int x = mobs[a].x();
int y = mobs[a].y(); // Take the position for each different mob
switch(random[a]){
case NORTH:
// Collision detection and movement
break;
case SOUTH:
// Collision detection and movement
break;
case WEST:
// Collision detection and movement
break;
case EAST:
// Collision detection and movement
break;
}
}
}
Is there any better way to do this?
My 2nd problem is passing the Monster class to a function. Monster is derived from QGraphicsItem. I have a function in the Main Window which sets the right position for each mob and then add it to the QGraphicsScene. My code looks like this:
void MainWindow::createMobs(){
for(int a = 0; a < mobsQuantity; a++){
mobs[a].setPos(/* X pos */ , /* Y pos */);
scene->addItem(mobs[a]);
}
}
The error comes from adding the item to the scene. How should I properly pass an element of a dinamically allocated array as a pointer ?
error: no matching function for call to 'QGraphicsScene::addItem(Monster&)'
I tried adding it like this:
scene->addItem(&mobs[a]);
But my program crashes.
Thanks for everyone who will try to help me.