tags:

views:

378

answers:

2

Can anyone provide an example of a function that returns the cross product of TWO 2d vectors? I am trying to implement this algorithm.

C code would be great. Thanks.


EDIT: found another way todo it that works for 2D and is dead easy.

bool tri2d::inTriangle(vec2d pt) {
    float AB = (pt.y-p1.y)*(p2.x-p1.x) - (pt.x-p1.x)*(p2.y-p1.y);
    float CA = (pt.y-p3.y)*(p1.x-p3.x) - (pt.x-p3.x)*(p1.y-p3.y);
    float BC = (pt.y-p2.y)*(p3.x-p2.x) - (pt.x-p2.x)*(p3.y-p2.y);

    if (AB*BC>0.f && BC*CA>0.f)
        return true;
    return false;    
}
+4  A: 

(Note: The cross-product of 2 vectors is only defined in 3D and 7D spaces.)

The code computes the z-component of 2 vectors lying on the xy-plane:

vec2D a, b;
...
double z = a.x * b.y - b.x * a.y;
return z;
KennyTM
Wow. Would like to give you an extra +1 for that link!
AakashM
Cross product function on here http://www.blackpawn.com/texts/pointinpoly/default.html seems to return a vector. Is this link absolutely not for 2d?
tm1rbrt
@tm1rbrt: That `CrossProduct` should be a full 3D cross-product. You can always add back the two 0 components.
KennyTM
The cross product of two vectors in 3D space is a 3D vector, yet your code only returns a double. What good is one component?
duffymo
The 3-D cross product of two vectors in the x/y plane is always along the z axis, so there's no point in providing two additional numbers known to be zero. Another way to look at it: the closest 2-D equivalent to a 3-D cross product is an operation (the one above) that returns a scalar.
comingstorm
Also, I want to assure you that the above operation will in fact work correctly with the algorithm you link to. If you work it out, the dot product of the resulting cross product vectors simplifies to a simple product of the resulting scalars. Your updated version above could be considered a simplified (and nicely symmetric!) version of this: by reducing the problem to comparing the signs of the resulting scalars, you can determine that the orientation of the original triangle is redundant.
comingstorm
@comingstorm - 2D doesn't necessarily mean in the xy-plane. I understand vectors well enough to know what special case you're talking about, but there's nothing in the original question that spells out that restriction. The updated answer that's provided is the correct, general answer. In spite of the fact that your answer was accepted it's not correct for the general case.
duffymo
Hey, first off, that's not *my* answer; second, it is, in fact, correct. The OQ was specifically about 2D vectors: an answer phrased in terms of 3D vectors would be missing the point, and therefore incorrect. Also, if you take a look at the link in the OQ, you will notice that his update, which you slagged for returning a boolean, is a (correct) implementation of his declared objective -- a point-in-triangle algorithm implemented for 2D vectors.
comingstorm
A: 

Mathworld Cross Product

High Performance Mark