以下是一个使用C++和OpenGL库的示例代码,绘制了一个基于物理模拟的弹簧系统,展示了弹簧的振动和碰撞效果:文章来源:https://www.toymoban.com/news/detail-536926.html
#include <GL/glut.h>
#include <vector>
struct Particle {
float x, y;
float vx, vy;
float radius;
bool fixed;
Particle(float _x, float _y, float _radius, bool _fixed)
: x(_x), y(_y), radius(_radius), fixed(_fixed)
{
vx = 0.0f;
vy = 0.0f;
}
void update(float dt)
{
if (!fixed) {
x += vx * dt;
y += vy * dt;
}
}
void draw() const
{
glColor3f(1.0f, 1.0f, 1.0f);
glBegin(GL_TRIANGLE_FAN);
glVertex2f(x, y);
for (int i = 0; i <= 360; i += 10) {
float angle = static_cast<float>(i) / 180.0f * 3.14159f;
glVertex2f(x + radius * cos(angle), y + radius * sin(angle));
}
glEnd();
}
};
struct Spring {
int particle1Idx, particle2Idx;
float restLength;
float k;
Spring(int idx1, int idx2, float length, float stiffness)
: particle1Idx(idx1), particle2Idx(idx2), restLength(length), k(stiffness)
{}
void applyForce(std::vector<Particle>& particles)
{
Particle& p1 = particles[particle1Idx];
Particle& p2 = particles[particle2Idx];
float dx = p2.x - p1.x;
float dy = p2.y - p1.y;
float d = sqrt(dx * dx + dy * dy);
float force = k * (d - restLength);
p1.vx += force * dx / d;
p1.vy += force * dy / d;
p2.vx -= force * dx / d;
p2.vy -= force * dy / d;
}
};
const int NUM_PARTICLES = 10;
std::vector<Particle> particles;
std::vector<Spring> springs;
void init()
{
particles.push_back(Particle(-0.5f, 0.0f, 0.05f, true));
for (int i = 1; i < NUM_PARTICLES - 1; i++) {
particles.push_back(Particle(-0.5f + i * 0.1f, 0.0f, 0.05f, false));
}
particles.push_back(Particle(0.5f, 0.0f, 0.05f, true));
for (int i = 0; i < NUM_PARTICLES - 1; i++) {
springs.push_back(Spring(i, i + 1, 0.1f, 100.0f));
}
}
void update(float dt)
{
for (auto& p : particles)
p.update(dt);
for (auto& s : springs)
s.applyForce(particles);
}
void draw()
{
for (const auto& p : particles)
p.draw();
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
update(0.01f);
draw();
glutSwapBuffers();
}
void reshape(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-1.0, 1.0, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
glutInitWindowSize(800, 600);
glutCreateWindow("Spring System");
init();
glutDisplayFunc(display);
glutIdleFunc(display);
glutReshapeFunc(reshape);
glutMainLoop();
return 0;
}
以上代码通过使用OpenGL库创建了一个基于物理模拟的弹簧系统。系统中的粒子通过弹簧相互连接文章来源地址https://www.toymoban.com/news/detail-536926.html
到了这里,关于用C++模拟的弹簧系统,可展示弹簧的振动和碰撞效果的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!