Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity3D Check if a point is to the left or right of a vector

I am working on a game that has a target point following a spline. For the AI I am making to turn toward the target I need to know if the target is to the left or right of the front of the vehicle. How would I acomplish this. (I don't need specific numbers, just a returned boolean from a function would be fine). Bellow is sort of a visualization.

A visualization of what I need

Because of this being vehicle AI, the vehicle's rotation can be any rotation or any position, so positive vs negitave coordinates wouldn't really help. If you guys know how to acomplish this I would be very appreciative.

like image 791
Saber Robotics Avatar asked Sep 02 '25 02:09

Saber Robotics


2 Answers

Option 1: use the cross product.

Vector3 delta = (targetPoint - vehiclePosition).normalized;
Vector3 cross = Vector3.Cross(delta, vehicleForward);

if (cross == Vector3.zero) {
    // Target is straight ahead
} else if (cross.y > 0) {
    // Target is to the right
} else {
    // Target is to the left
}

A major benefit of this is that the result of the cross product is the axis you need to rotate on to reach the target! You can then use this to rotate:

float angle = Vector3.AngleBetween(vehicleForward, delta);
angle = Mathf.Min(angle, maxTurnSpeed);
transform.Rotate(angle * Time.deltaTime, cross);

You may need to set the Y values of "delta" and "vehicleForward" to zero if you want to limit rotation to the Y axis/ground plane.

Option 2: Use the vehicle's transform to transform the point into local space.

Vector3 localPos = vehicle.transform.InverseTransformPoint(targetPoint);

if (localPos.x > 0) {
    // Target is to the left
} else if (localPos.x < 0) {
    // Target is to the right
} else if (localPos.z > 0) {
    // Target is in front
} else {
    // Target is behind
} 
like image 173
Kalle Halvarsson Avatar answered Sep 04 '25 16:09

Kalle Halvarsson


Thanks, and I just forgot to add some code in my question. It turns out I was using the Vector3.Cross function incorrectly, by not putting in the right values for the parameters in the function. Thank you everyone and Kalle Halvarsson for realizing my mistake.

like image 32
Saber Robotics Avatar answered Sep 04 '25 16:09

Saber Robotics