我正在处理基类Entity,我希望它的派生类(Player,Enemy,Bullet)有collideWith()调用
我试图让Entity的collideWith()的派生函数起作用,但是,总是调用基本版本,即使我删除了关键字virtual
,它也是空的。基类实体
virtual void collideWith(Entity*);
// Right now the derived classes of collideWIth are not being called,
// even with the virtual removed
及其功能,在碰撞检查期间始终调用
void Entity::collideWith(Entity*){
}
带有collideWith函数的派生类,没有虚拟关键字 这些永远不会在碰撞检查期间被调用
void Player::collideWith(Bullet*)
void Player::collideWith(Enemy*)
void Enemy::collideWith(Bullet*)
void Enemy::collideWith(Player*)
void Bullet::collideWith(Player*)
void Bullet::collideWith(Enemy*)
检查碰撞的功能 p和q指向来自EntityList的Entity *,它包含其派生类 球员,敌人和子弹
void SceneGame::checkCollisions(){
populateGrid();
// Right now I am unable to get the collision detection to work!
for (auto i = 0; i < gridBox.slicesX; ++i){
for (auto j = 0; j < gridBox.slicesY; ++j){
if (gridBox.cell[i][j].nEntities < 2) continue;
for (auto k = 0; k < gridBox.cell[i][j].nEntities; ++k){
for (auto l = 0; l < gridBox.cell[i][j].nEntities; ++l){
// Set up the pointers and compare them
auto p = gridBox.cell[i][j].items[k];
auto q = gridBox.cell[i][j].items[l];
if (p == q) continue; // we do not want the same pointer
if (p->getGlobalBounds().
intersects(q->getGlobalBounds() )){
// Do a series of collisions depending on the specific entities
/*
However, I end up always calling the BASE function of collideWith
instead of the derived types (Player, Enemy, Bullet, etc.)
*/
p->collideWith(q);
}
}
}
}
}
}
答案 0 :(得分:2)
问题在于,你正试图让C ++为你做multiple dispatch,而不是那么简单。
对于所有意图和目的,具有相同名称但不同参数类型的方法是完全不同的方法,因此不会相互覆盖。由于您的q
变量可能属于Entity *
类型,因此方法调用将静态解析为对Entity::collideWith(Entity *)
的调用,并且所有其他方法将被完全忽略。