現在、OpenFrameworksを使用して布の物理アプリを構築しています。頭を上げるために、私はC++を初めて使用します。
私のアプリでは、2つの「隣接する」パーティクルオブジェクトがポインタとしてスプリングオブジェクトに渡されます。テストとして、スプリングオブジェクトに2つのパーティクル間(3Dベクトル位置間)に線を描画させます。何らかの理由で、これらの行は、ランダムな値が含まれていなくても、プログラムを実行するたびに異なります。スプリング構造体からパーティクルの位置の値を計算すると、-4.15301e-12のようなばかげた値になることがよくあります。私はサンプルコードをほぼ逐語的にフォローしているので、どこが間違っているのかよくわかりません。
これが私がフォローしているサンプルコードです:
https://sites.google.com/site/ofauckland/examples/17-cloth-physics
これが私のSpring構造体です:
#pragma once
#include "ofMain.h"
#include "Particle.h"
struct Spring {
float k, restLength;
Particle *a, *b;
ofVec3f posA, posB;
Spring(Particle *a, Particle *b, float k = .2) : a(a), b(b), k(k) {
restLength = (b->pos - a->pos).length();
}
void update() {
posA = a->pos;
posB = b->pos;
}
void draw() {
ofSetLineWidth(5);
ofSetColor(0, 255, 0);
ofLine(posA.x, posA.y, posB.x, posB.y);
}
};
粒子構造:
#pragma once
#include "ofMain.h"
struct Particle {
ofVec3f pos;
Particle(ofVec3f pos) : pos(pos) {
}
void update() {
}
void draw() {
ofSetColor(ofRandom(255), 0, 0);
ofFill();
ofCircle(pos.x, pos.y, 3);
}
};
そして、これは私が2つのパーティクルをポインタとしてスプリングに渡す場所です。
#pragma once
#include "ofMain.h"
#include "Particle.h"
#include "Spring.h"
struct Petal {
float maxWidth, spacing;
vector<Particle> particles;
vector<Spring> springs;
Petal(float maxWidth, float spacing) : maxWidth(maxWidth), spacing(spacing) {
setupPoints();
}
void setupPoints() {
float x = 0;
float y = 0;
for(int r = 1; r <= maxWidth; r++) {
x = (int)(r / 2) * -spacing;
y += spacing;
for(int c = 1; c <= r; c++) {
ofVec3f pos = ofVec3f(x, y, 0);
Particle p(pos);
particles.push_back(p);
x+=spacing;
}
}
for(int r = maxWidth; r > 0; r--) {
x = (int)(r / 2) * -spacing;
y += spacing;
for(int c = 1; c <= r; c++) {
ofVec3f pos = ofVec3f(x, y, 0);
Particle p(pos);
particles.push_back(p);
x+=spacing;
}
}
//find neighbors
for(int i = 0; i < particles.size(); i++) {
Spring s(&particles[i], &particles[findNeighbor(i)]);
springs.push_back(s);
}
}
int findNeighbor(int pIndex) {
float leastDist = 0;
float leastDistIndex = 0;
for(int i = 0; i < particles.size(); i++) {
if(i != pIndex) {
float distance = particles[pIndex].pos.distance(particles[i].pos);
if(abs(distance) < abs(leastDist) || leastDist == 0) {
leastDist = distance;
leastDistIndex = i;
}
}
}
return leastDistIndex;
}
void update() {
for(int i = 0; i < particles.size(); i++) {
particles[i].update();
}
for(int s = 0; s < springs.size(); s++) {
springs[s].update();
}
}
void draw() {
for(int i = 0; i < particles.size(); i++) {
particles[i].draw();
}
for(int s = 0; s < springs.size(); s++) {
springs[s].draw();
}
}
};
これが起こることです。奇妙なことに、いくつかのスプリングが正しい位置にあるように見えます。
何か明確にできるかどうか教えてください。
ありがとう!