【发布时间】:2017-04-05 03:28:28
【问题描述】:
我开始为我正在使用 C++ 和 sfml 开发的游戏编写自己的粒子效果系统。 在我的更新方法中,我在迭代向量时删除了生命周期已过期的粒子。 正如您在方法底部看到的那样,我想我小心不要在删除元素后使迭代器无效,但我得到了 exec_bad_access 代码=1 或代码=2。 异常总是指向擦除(它)行。 有什么想法可能是错的吗?
void ParticlesNode::updateCurrent(sf::Time dt)
{
for(particleIterator it = _mParticles.begin(), end = _mParticles.end(); it != end;)
{
// calculate new color RGBA
float nr = it->color.r + it->colorDis.r * dt.asSeconds();
float ng = it->color.g + it->colorDis.g * dt.asSeconds();
float nb = it->color.b + it->colorDis.b * dt.asSeconds();
float na = it->color.a + it->colorDis.a * dt.asSeconds();
it->color = sf::Color{static_cast<Uint8>(nr),static_cast<Uint8>(ng),static_cast<Uint8>(nb),static_cast<Uint8>(na)};
// new position
it->pos = sf::Vector2f(it->pos.x + it->vel.x * dt.asSeconds(), it->pos.y + it->vel.y * dt.asSeconds());
// new velocity by linear accelaration.
float length = getLength(it->vel);
float newLength = length + _mPData.accel * dt.asSeconds();
float radians = cartesianToPolar(it->vel).y;
it->vel = polarToCartesian(newLength, radians);
// new velocity by gravity
// new velocity by radial acceleration.
// new remaining life time
it->lifeSpan -= dt.asSeconds();
if (it->lifeSpan <= 0)
_mParticles.erase( it );
else
++it;
}
}
【问题讨论】: