For collision I check first if Ball is in collision with the right :
- Code: Select all
boolean CollisionDroite(Droite d1,Circle C)
{
Vecteur u;
u.x = d1.x2 - d1.x1;
u.y = d1.y2 - d1.y1;
Vecteur AC;
AC.x = (C.x+2) - d1.x1;
AC.y = (C.y+2) - d1.y1;
float numerateur = u.x*AC.y - u.y*AC.x; // norme du vecteur v
if (numerateur <0)
numerateur = -numerateur ; // valeur absolue ; si c'est négatif, on prend l'opposé.
float denominateur = sqrt(u.x*u.x + u.y*u.y); // norme de u
float CI = numerateur / denominateur;
if (CI<2)//ma balle a un rayon de deux PX
return true;
else
return false;
}
After this i check if the Ball is in the segment :
- Code: Select all
boolean CollisionSegment(Droite d1,Circle C)
{
if (CollisionDroite(d1,C) == false)
return false; // si on ne touche pas la droite, on ne touchera jamais le segment
Vecteur AB,AC,BC;
AB.x = d1.x2 - d1.x1;
AB.y = d1.y2 - d1.y1;
AC.x = (C.x+2) - d1.x1;
AC.y = (C.y+2) - d1.y1;
BC.x = (C.x+2) - d1.x2;
BC.y = (C.y+2) - d1.y2;
float pscal1 = AB.x*AC.x + AB.y*AC.y; // produit scalaire
float pscal2 = (-AB.x)*BC.x + (-AB.y)*BC.y; // produit scalaire
if (pscal1>=0 && pscal2>=0)
return true; // I entre A et B, ok.
// dernière possibilité, A ou B dans le cercle
if (CollisionBallExtremiter(d1,C))
return true;
return false;
}
end I calculate the rebond :
- Code: Select all
void rebond(Droite obst)
{
Vecteur N = GetNormale(obst,Ball);
Vecteur ptImpact = ProjectionI(obst,Ball);
Ball.x = ptImpact.x-2;
Ball.y = ptImpact.y-2;
Vecteur rebond =CalculerVecteurV2(Ball,N);
Ball.vx = rebond.x;
Ball.vy = rebond.y;
Ball.vx *= FROTTEMENT;
Ball.vy *= FROTTEMENT;
}
//d1 right collide , C is the ball
Vecteur GetNormale(Droite d1,Circle C)
{
Vecteur AC,u,N;
u.x = d1.x2 - d1.x1;
u.y = d1.y2 - d1.y1;
AC.x = C.x - d1.x1;
AC.y = C.y - d1.y1;
float parenthesis = u.x*AC.y-u.y*AC.x; // calcul une fois pour les deux
N.x = -u.y*(parenthesis);
N.y = u.x*(parenthesis);
// normalisons
float norme = sqrt(N.x*N.x + N.y*N.y);
N.x/=norme;
N.y/=norme;
return N;
}
//Vector of rebound
Vecteur CalculerVecteurV2(Circle v,Vecteur N)
{
Vecteur v2;
float pscal = (v.vx*N.x + v.vy*N.y);
v2.x = v.vx -2*pscal*N.x;
v2.y = v.vy -2*pscal*N.y;
return v2;
}
I have find the code here :
http://jeux.developpez.com/tutoriels/theorie-des-collisions/formes-complexes/ (in french)
I don't know if is the best and optimised method, but it 's work.
I have bug if the ball move fast, they can cross the segment with no collision.
hoping my English is understandable ...