如何在 C++ 中管理一个类的多个实例,为它们提供所有信息然后删除它们?

问题描述 投票:0回答:1

对于我的语言不准确,我深表歉意,我对编程还很陌生。

假设我正在尝试在 SFML 中创建粒子效果。我目前的解决方案是创建我的粒子类的多个实例,然后使用类中的方法更新它们,每一帧将虚拟“相机”的更新位置作为输入,一次可以正常工作.不过,我一次制作多个粒子时遇到了麻烦,因为在我当前的实现中,我必须手动创建并在计数器达到足够高的值后覆盖每个粒子。我如何创建、更新、绘制和整体,同时跟踪多个实例?这是可能的,还是我应该重新考虑我的实施?

我目前拥有的,用英文伪代码表示:

Create a particle object()
while true{

    Update the particle instance's position(given camera position)
    Draw the particle instance

}

我想做什么(伪代码),但我不确定如何在 C++ 中实现:

while true{

    Create a new particle object() // note: the particle objects already delete themselves after they have been updated a certain number of times, so creating new objects does not pose a threat to memory
    Update ALL particle instances' positions(given the camera's updated position)
    Draw ALL particle instances 

}

我在 C++ 中的大致情况:

RenderWindow window(windowSize);
SmokeParticle smokeParticleInstance(cameraX, cameraY);
while true{

    window.draw(smokeParticleInstance.update(cameraX, cameraY)); // the update method returns a sprite object that the RenderWindow object knows how to draw

}
c++ instance sfml multiple-instances
1个回答
0
投票

要同时创建、更新、绘制和跟踪多个粒子实例,您可以使用矢量或列表等容器来容纳所有粒子对象。然后,在您的主循环中,您可以遍历容器,更新每个粒子的位置,并将其绘制在屏幕上。

// create an empty vector to hold particle objects
std::vector<SmokeParticle> particles;

// add some initial particles to the vector
//This will add 10 particles to the vector
for (int i = 0; i < 10; i++) 
    particles.push_back(SmokeParticle());


while (window.isOpen()) {

    sf::Event event;
    ...

    ...

    //update all particles
    for (auto& particle : particles) {
        window.update(time.asSeconds());
    }


    window.clear();
    //draw all particles
    for (auto& particle : particles) {
        window.draw(particle.sprite);
    }

    // display the window
    window.display();
}
© www.soinside.com 2019 - 2024. All rights reserved.