落砂模拟碰撞检测C++和SFML

Falling sand simulation collision detection C++ and SFML

本文关键字:SFML C++ 碰撞检测 模拟      更新时间:2023-10-16

我真的需要一些帮助。我正在尝试做一个落沙模拟,并编写一些基本代码,但我不知道如何进行碰撞检测。这是我到目前为止的代码:

//SFML Include
#include <SFML/Graphics.hpp>
//Include Vectors
#include <vector>
//Main Loop
int main()
{
//Window Init
sf::RenderWindow window(sf::VideoMode(720, 480, 32), "Yip Yip Physics", sf::Style::Default);
//Global Envoirmental Variables
static float gravity = 0.25;
static float frict = 3;
//Particle Structures
struct Particle
{
//Shape
sf::RectangleShape rect;
//Cell Position
sf::Vector2f cell_pos;
//Vel and frict
float slide_vel = 3;
float grv_vel = 0;
//Init Particle (size, color and origin)
void init()
{
rect.setSize(sf::Vector2f(3, 3));
rect.setFillColor(sf::Color::Green);
rect.setOrigin(rect.getSize());
}
};
//Particle Setup
std::vector<Particle> particles;
//Window Loop
while (window.isOpen())
{
//Update
if (sf::Mouse::isButtonPressed(sf::Mouse::Button::Left))
{
//Make and Position Particle
Particle part;
part.rect.setPosition(sf::Vector2f(sf::Mouse::getPosition(window)));
//Initalize the Particle and add to vector
part.init();
particles.push_back(part);

}
//Pixel Update
for (auto& p : particles)
{
//Draw in window
window.draw(p.rect);
}
//Display
window.display();
//Event Variable
sf::Event event;
//Window Event System 
while (window.pollEvent(event))
{
//Close Window
if (event.type == sf::Event::Closed)
{
window.close();
}

}
//Window Clear
window.clear(sf::Color::Black);
}
//Return 0
return 0;
}

代码的工作原理是制作粒子,将它们放在向量中,并将它们绘制到屏幕上,但我不知道该去哪里进行碰撞。我不知道该在哪里找,我真的很感激在哪里找到它的帮助或指导。我听过一些关于细胞自动机的知识,但不知道如何做,也不知道这是否是最好的选择。

落沙模拟通常不是这样做的!它们与细胞自动机非常相似。通常,您可以通过将世界存储在2d阵列中来实现它们,并通过在帧缓冲区上绘制像素来绘制粒子
这可以防止模拟的性能下降(而不是O(n^2(,得到O(n((,还可以提高渲染性能(而不是0(n(,得到了O(1((闪电传输帧缓冲区是一种恒定时间操作((

只需在谷歌上搜索主题,你就可以获得很多有用的信息!