我有一个类Block
Block::Block(const Block& p_block):Drawable(p_block) {
}
继承自班级Drawable
Drawable::Drawable(const Drawable& p_drawable) {
sprite = p_drawable.sprite;
texture = p_drawable.texture;
x = p_drawable.x;
y = p_drawable.y;
}
我使用指针来存储对象,但是试图切换到不使用指针,现在精灵和纹理都丢失了。我非常确定我对引用/指针的使用是非常错误的。
绘制方法:
void Room::draw(sf::RenderWindow &p_window) {
for(auto& block : blocks) {
block.draw(p_window);
}
...
}
可以包含任何其他必要的代码。只是想知道我是否在复制构造函数中做错了什么,或者我是否应该使用指针。
我也将此用于碰撞,不确定此处的某些内容是否可能导致问题。
struct sortBlocksByDistance {
Drawable *drawable;
sortBlocksByDistance(Drawable* p_drawable) {
this->drawable = p_drawable;
}
bool operator () (Block* a, Block* b) {
float adx = a->x - drawable->x,
ady = a->y - drawable->y,
adist = adx * adx + ady * ady;
float bdx = b->x - drawable->x,
bdy = b->y - drawable->y,
bdist = bdx * bdx + bdy * bdy;
return adist < bdist;
}
};
std::vector<Block*> Room::detectCollisions(Drawable *p_drawable) {
std::vector<Block*> hitBlocks;
for(auto& block : blocks) {
if(block.collidesWith(p_drawable)) {
hitBlocks.push_back(&block);
}
}
std::sort(hitBlocks.begin(), hitBlocks.end(), sortBlocksByDistance(p_drawable));
return hitBlocks;
};
std::vector<Block*> collisions = detectCollisions(player);
player->solveCollisions(collisions);
void Drawable::solveCollisions(std::vector<Block*> p_blocks) {
while(p_blocks.size()) {
Block &block = *p_blocks.front();
// x/y manipulation
// pop front
p_blocks.front() = std::move(p_blocks.back());
p_blocks.pop_back();
}
};