编译和库
首先,出现编译和库安装的问题根据这篇教程解决:
【GAMES101】作业8 库安装问题_ycr的帐号的博客-CSDN博客
我自己的话,除了upgrade之外,还换了阿里云的下载源,并且安装了gl库(libgl1),感受是比较麻烦...
运行之后,程序出现黑色界面,无报错,此时即为编译成功,可以开始写代码了!
Rope构造函数
此函数的主要功能是:初始化成员变量vector<*Mass>和vector<*Spring>,具体代码如下:
Rope::Rope(Vector2D start, Vector2D end, int num_nodes, float node_mass, float k, vector<int> pinned_nodes)
{
for (int i = 0; i < num_nodes; ++i)
{
this->masses.emplace_back(new Mass(start+i*(end-start)/(num_nodes-1), node_mass, false));
}
for (int i = 0; i < num_nodes - 1; ++i)
{
this->springs.emplace_back(new Spring(masses[i], masses[i+1], k));
}
// Comment-in this part when you implement the constructor
for (auto &i : pinned_nodes)
{
masses[i]->pinned = true;
}
}
simulateEuler函数(显示欧拉、半隐式欧拉)
需要注意:
1)spring中的rest_length即为弹簧的原长度
2)弹簧力需要自己亲手画一下图来确定正负方向
void Rope::simulateEuler(float delta_t, Vector2D gravity)
{
for (auto &s : springs)
{
Vector2D dir = (s->m2->position - s->m1->position).unit();
double dis = (s->m2->position - s->m1->position).norm();
Vector2D res = s->k * (dis - s->rest_length) * dir; // rest_length即为原长
s->m1->forces += res;
s->m2->forces -= res;
}
double damping_factor = 8e-4;
for (auto &m : masses)
{
if (!m->pinned)
{
m->forces += damping_factor * m->velocity;
Vector2D a = m->forces/m->mass + gravity;
Vector2D v_next = m->velocity + a * delta_t;
// Vector2D x_next = m->position + m->velocity * delta_t; // 显示欧拉
Vector2D x_next = m->position + v_next * delta_t; // 半隐式欧拉
m->position = x_next;
m->velocity = v_next;
}
// Reset all forces on each mass
m->forces = Vector2D(0, 0);
}
}
simulateVerlet函数(显式Verlet)
这里的话根据PDF教程上的公式来就行了。
void Rope::simulateVerlet(float delta_t, Vector2D gravity)
{
for (auto &s : springs)
{
Vector2D dir = (s->m2->position - s->m1->position).unit();
double dis = (s->m2->position - s->m1->position).norm();
Vector2D res = s->k * (dis - s->rest_length) * dir; // s->rest_length is the original length!
s->m1->forces += res;
s->m2->forces -= res;
}
double damping_factor = 8e-4;
for (auto &m : masses)
{
if (!m->pinned)
{
Vector2D a = m->forces/m->mass + gravity;
// 无damping
// Vector2D x_next = m->position + (m->position - m->last_position) + a * delta_t * delta_t;
// 有damping
Vector2D x_next = m->position + (1 - damping_factor) * (m->position - m->last_position) + a * delta_t * delta_t;
m->last_position = m->position;
m->position = x_next;
}
m->forces = Vector2D(0, 0);
}
}
结果
最终运行的结果如下:
这篇博客讲述了在完成Games101作业8时如何模拟绳子,包括解决编译和库安装问题,如使用阿里云源和安装libgl1。接着详细介绍了Rope构造函数用于初始化Mass和Spring,以及两种模拟方法:simulateEuler(显示欧拉和半隐式欧拉)和simulateVerlet(显式Verlet)的实现细节。最终展示了程序运行的结果。

3085

被折叠的 条评论
为什么被折叠?



