我正在使用用 C++ 编写的粒子物理库来开发游戏。
为了绘制粒子,我必须像这样获得所有粒子位置的数组..
b2Vec2* particlePositionBuffer = world->GetParticlePositionBuffer();
这将返回 b2Vec2 对象的数组(表示物理引擎中的二维 vector )。
我还可以使用获取和设置它们的颜色
b2ParticleColor* particleColourBuffer = world->GetParticleColorBuffer();
我想获取 10% 具有最高 Y 值的粒子(然后更改其颜色)
我的想法是..
1. 制作一个与articlePositionBuffer数组大小相同的结构体数组,该结构体只包含一个int(粒子位置缓冲区数组中的粒子索引)和一个float(粒子y位置)
2.然后我按 y 位置对数组进行排序。
3.然后,我使用结构体数组中前 10% 的结构体中的 int 来对它们在 ParticleColourBuffer 数组中的颜色进行处理。
有人可以告诉我如何像 C++ 中那样对结构进行排序和数组吗?
您还认为这是解决此问题的好方法吗?我只需要执行一次(不是每一帧)
最佳答案
以下内容可能会有所帮助:
// Functor to compare indices according to Y value.
struct comp
{
explicit comp(b2Vec2* particlePositionBuffer) :
particlePositionBuffer(particlePositionBuffer)
{}
operator (int lhs, int rhs) const
{
// How do you get Y coord ?
// note that I do rhs < lhs to have higher value first.
return particlePositionBuffer[rhs].getY() < particlePositionBuffer[lhs].getY();
}
b2Vec2* particlePositionBuffer;
};
void foo()
{
const std::size_t size = world->GetParticleCount(); // How do you get Count ?
const std::size_t subsize = size / 10; // check for not zero ?
std::vector<std::size_t> indices(size);
for (std::size_t i = 0; i != size; ++i) {
indices[i] = i;
}
std::nth_element(indices.begin(), indices.begin() + subsize, indices.end(),
comp(world->GetParticlePositionBuffer()));
b2ParticleColor* particleColourBuffer = world->GetParticleColorBuffer();
for (std::size_t i = 0; i != subsize; ++i) {
changeColor(particleColourBuffer[i])
}
}
关于c++ - 在 C++ 中对结构体数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21762317/