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.
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.
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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With