Search - User list
Full Version: Which ortho axis is closest to this vector?
Root » Technical Discussion » Which ortho axis is closest to this vector?
Mike_A
Seeking your kind help on a VEX question...

I have a vector, and I'd like to find the ortho axis which is nearest to it, and whether it faces in the positive or negative direction on that axis - ie: one of six results.

Can anyone suggest a VEX solution, or point me in the right direction? (pun happily accepted : )


With thanks.
viklc
You could simply compare the distance to each ortho axis:

printf('------------ \n');
vector p =  point(1, 'P', 0);
addpoint(0, 0);
addpoint(0, p);
addprim(0, 'polyline', 0, 1);

vector ort_axis = 0;
float min_dist = 0;

for (int i = 0; i < 6; ++i)
{
    vector tmp = 0;
    tmp[i / 2] = (i % 2 * 2) - 1;
    
    float tmp_dist = distance(p, tmp);
    if (min_dist < tmp_dist)
    {
        min_dist = tmp_dist;
        ort_axis = floor(tmp * -1);
    }
}

printf('%d \n', ort_axis );
animatrix_
Hi,

You can use the dot product to do this:



vector v = normalize ( chv("vec") );
vector dirs [ ] = array ( {1, 0, 0}, {0, 1, 0 }, {0, 0, 1} );

float maxdv = -1;
vector nearestdir = 0;

for ( int i = 0; i < len ( dirs ); ++i )
{
    float dv = dot ( v, dirs[ i ] );
    float adv = abs ( dv );
    if ( adv > maxdv )
    {
        maxdv = adv;
        nearestdir = dv > 0 ? dirs [ i ] : -dirs [ i ];
    }
}

int pt = addpoint ( 0, nearestdir );
setpointattrib ( 0, "N", pt, nearestdir );

tamte
you can also try checking the longest value and that will be your axis
(I know that == with floats is questionable, but seems to work in VEX at least in this case)
vector v = chv("vector");
float longest = max( abs(v) );
vector axis = {0,0,0};
for ( int i=0; i<3; i++){
    if ( abs(v[i]) == longest ) {
        axis[i] = sign( v[i] );
        break;
    }
}
Mike_A
Gents - many thanks for your generosity in offering these thoughtful and top quality answers. I really appreciate it. They're both an excellent solution to the problem at hand - and a learning resource!
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB