Je construis un jeu d'astéroïdes pour une assignation de classe. Pour finir, j'ai besoin d'un algorithme/code d'intersection de lignes . J'en ai trouvé un qui fonctionne, mais je ne comprends pas les maths derrière ça. Comment cela marche-t-il?Comment fonctionne cette ligne-intersection?
point* inter(point p1, point p2, point p3, point p4)
{
point* r;
//p1-p2 is the first edge.
//p3-p4 is the second edge.
r = new point;
float x1 = p1.x, x2 = p2.x, x3 = p3.x, x4 = p4.x;
float y1 = p1.y, y2 = p2.y, y3 = p3.y, y4 = p4.y;
//I do not understand what this d represents.
float d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
// If d is zero, there is no intersection
if (d == 0) return NULL;
// I do not understand what this pre and pos means and
// how it's used to get the x and y of the intersection
float pre = (x1*y2 - y1*x2), pos = (x3*y4 - y3*x4);
float x = (pre * (x3 - x4) - (x1 - x2) * pos)/d;
float y = (pre * (y3 - y4) - (y1 - y2) * pos)/d;
// Check if the x and y coordinates are within both lines
if (x < min(x1, x2) || x > max(x1, x2) ||
x < min(x3, x4) || x > max(x3, x4)) return NULL;
if (y < min(y1, y2) || y > max(y1, y2) ||
y < min(y3, y4) || y > max(y3, y4)) return NULL;
cout << "Inter X : " << x << endl;
cout << "Inter Y : " << y << endl;
// Return the point of intersection
r->x = x;
r->y = y;
return r;
}
'point de r *.;/* ... */r = nouveau point;/* ... */if (d == 0) renvoie NULL; 'Pouvez-vous repérer la fuite de mémoire? Si vous utilisiez des pointeurs intelligents, vous n'auriez pas à vous en préoccuper. (En outre, vous ne devriez généralement pas comparer les valeurs à virgule flottante calculées pour l'égalité, vous devriez vérifier l'égalité approximative pour permettre une erreur dans les calculs). –
Pour référence, vous fuyez un «point» chaque fois que vos lignes ne se croisent pas. – cHao
Ou mieux encore, au lieu d'allouer 'point' via' new', juste allouer un 'point' sur la pile et le renvoyer. Il sera beaucoup plus rapide d'allouer un 'point' sur la pile que d'allouer un' point' via 'new', surtout si' inter() 'va être appelé fréquemment. –