Home > OS >  Using The Dot Product to determine whether an object is on the left hand side or right hand side of
Using The Dot Product to determine whether an object is on the left hand side or right hand side of

Time:05-12

so I currently am trying to create some method which when taking in a simulation vehicles position, direction, and an objects position, Will determine whether or not the object lies on the right and side or left hand side of that vehicles direction. This is what i have implemented so far (Note I am in a 2D co-ord system):

This is the code block that uses the method

void Class::leftOrRight()
{
    // Clearing both _lhsCones and _rhsCones vectors
    _rhsCones.clear();
    _lhsCones.clear();

    for (int i =0; i < _cones.size(); i  )
    {
        if (dotAngleFromYaw(_x, _y, _cones[i].x(), _cones[i].y(), _yaw) > 0)
        {
            _lhsCones.push_back(_cones[i]);
        }
        else
        {
            _rhsCones.push_back(_cones[i]);
        }
    }

    return;
}

This is the code block which computes the angle


double Class::dotAngleFromYaw(double xCar, double yCar, double xCone, double yCone, double yawCar)
{


    double iOne = cos(yawCar);
    double jOne = sin(yawCar);

    double iTwo = xCone - xCar;
    double jTwo = yCone - yCar;

    //ensure to normalise the vector two
    double magTwo = std::sqrt(std::pow(iTwo, 2)   std::pow(jTwo, 2));
    iTwo = iTwo / magTwo;
    jTwo = jTwo / magTwo;

    double theta = acos((iOne * iTwo)   (jOne * jTwo));  // in radians

    return theta;
}




My issue with this is that dotAngleFromYaw(0,0,0,1,0) = pi/2 and dotAngleFromYaw(0,0,0,-1,0) = pi/2 hence the if statements fail to sort the cones.

Any help would be great

CodePudding user response:

If the angle does not matter and you only want to know whether "left or right" I'd go for another approach. Set up a plane that has xCar and yCar on its surface. When setting it up it's up to you how to define the plane's normal i.e. the side its facing to.

After that you can apply the dot-product to determine the 'sign' indicating which side it's on.

CodePudding user response:

Note that dot product does not provide information about left/right position.

Sign of dot product says whether position is ahead or backward.

To get left/right side, you need to check sign of cross product

cross = iOne * jTwo - jOne * iTwo

(note subtraction and i/j alternation)

  • Related