Balls now bounce off each other

Co-authored-by: sigonasr2 <sigonasr2@gmail.com>
master
sigonasr2, Sig, Sigo 2 years ago
parent 3ad7d5a725
commit c2214e1d33
  1. BIN
      C++ProjectTemplate.wasm
  2. 34
      main.cpp

Binary file not shown.

@ -20,6 +20,7 @@ class MiniGolfPro : public olc::PixelGameEngine
public:
std::vector<Ball>balls;
Ball*selectedBall;
std::vector<std::pair<Ball*,Ball*>>collidingPairs;
MiniGolfPro()
{
@ -109,6 +110,39 @@ public:
}
}
for(Ball&b:balls){
for(Ball&b2:balls){
if(&b!=&b2){
if(DoCirclesOverlap(b.pos,b.radius,b2.pos,b2.radius)){
collidingPairs.push_back({&b,&b2});
float dist=sqrtf((b.pos.x-b2.pos.x)*(b.pos.x-b2.pos.x)+(b.pos.y-b2.pos.y)*(b.pos.y-b2.pos.y));
float overlap=0.5f*(dist-b.radius-b2.radius);
b.pos.x-=overlap*(b.pos.x-b2.pos.x)/dist;
b.pos.y-=overlap*(b.pos.y-b2.pos.y)/dist;
b2.pos.x+=overlap*(b.pos.x-b2.pos.x)/dist;
b2.pos.y+=overlap*(b.pos.y-b2.pos.y)/dist;
}
}
}
}
for(std::pair<Ball*,Ball*>&pair:collidingPairs){
Ball*b1=pair.first;
Ball*b2=pair.second;
float dist=sqrtf((b1->pos.x-b2->pos.x)*(b1->pos.x-b2->pos.x)+(b1->pos.y-b2->pos.y)*(b1->pos.y-b2->pos.y));
vf2d normal={(b2->pos.x-b1->pos.x)/dist,(b2->pos.y-b1->pos.y)/dist};
vf2d tangent={-normal.y,normal.x};
vf2d dpTangent={tangent.dot(b1->vel),tangent.dot(b2->vel)};
vf2d dpNormal={normal.dot(b1->vel),normal.dot(b2->vel)};
vf2d momentum={(dpNormal.x*(b1->mass-b2->mass)+2.f*b2->mass*dpNormal.y)/(b1->mass+b2->mass),(dpNormal.y*(b2->mass-b1->mass)+2.f*b1->mass*dpNormal.x)/(b1->mass+b2->mass)};
b1->vel.x=tangent.x*dpTangent.x+normal.x*momentum.x;
b1->vel.y=tangent.y*dpTangent.x+normal.y*momentum.x;
b2->vel.x=tangent.x*dpTangent.y+normal.x*momentum.y;
b2->vel.y=tangent.y*dpTangent.y+normal.y*momentum.y;
}
collidingPairs.clear();
for(Ball&b:balls){
if(selectedBall==&b){
FillCircle(b.pos,b.radius,YELLOW);

Loading…
Cancel
Save