C++で基本的に円を動かし、2つの円が衝突したときにビリヤードボールと同じようにリコシートする小さな物理シミュレーションを作成しています。円がお互いに衝突すると、ほとんどの場合、無限に実際に減速するか、お互いにくっついて静止しているように見えます。場合によっては、1つのボールのみが衝突でリバウンドし、他のボールは軌道を保持することがあります。これは単なる2Dシミュレーションです。円周衝突リバウンドが正しく機能しない
だからここに私は検出/跳ね返るロジックを持っているものです。
bool Ball::BallCollision(Ball &b2)
{
if (sqrt(pow(b2.x - x, 2) + pow(b2.y - y, 2)) <= b2.radius + radius) // Test for collision
{
normal[0] = (x - (x + b2.x)/2)/radius; // Finds normal vector from point of collision to radius
normal[1] = (y - (y + b2.y)/2)/radius;
xvel = xvel - 2 * (xvel * normal[0]) * normal[0]; // Sets the velocity vector to the reflection vector
yvel = yvel - 2 * (yvel * normal[1]) * normal[1];
////x = xprev; // These just move the circle back a 'frame' so the collision
////y = yprev; // detection doesn't detect collision more than once.
// Not sure if working?
}
}
私は私の機能と間違っているかを把握することはできません。事前に助けてくれてありがとう!
編集:
void Ball::Move()
{
xprev = x;
yprev = y;
x += xvel;
y += yvel;
}
void Ball::DrawCircle()
{
glColor3ub(100, 230, 150);
glBegin(GL_POLYGON);
for (int i = 0; i < 10; i++)
{
angle = i * (2*3.1415/10);
newx = x + r*cos(angle);
newy = y + r*sin(angle);
glVertex2f(newx, newy);
}
glEnd();
}
ループ: すべての変数は、フロート
関数として宣言されている
run_prev.clear(); // A vector, cleared every loop, that holds the Ball objects that collided
for (int i = 0; i < num_balls; i++)
{
b[i].Move();
}
for (int i = 0; i < num_balls; i++)
{
b[i].WallCollision(); // Just wall collision detecting, that is working just fine
}
//The loop that checks for collisions... Am I executing this properly?
for (int i = 0; i < num_balls; i++)
{
for (int j = 0; j < num_balls; j++)
{
if (i == j) continue;
if (b[i].BallCollision(b[j]) == true)
{
run_prev.push_back(b[i]);
}
}
}
for (int i = 0; i < num_balls; i++)
{
b[i].DrawCircle();
}
//xprev and yprev are the x and y values of the frame before for each circle
for (int i = 0; i < run_prev.size(); i++)
{
run_prev[i].x = run_prev[i].xprev;
run_prev[i].y = run_prev[i].yprev;
}
丸めなどのキャストエラーを除外できるかどうかを知るために、変数のタイプを通知する必要があります。 – vsz
私はあなたがそのような普通を計算する理由を理解していません。彼らはユニットの長さを持っていますか? –
私は彼らがそうだと思った。私がどこにいなくても私を修正してください。 – Christian