My units got strange starting points, because the NavmeshCut rectange has different side lengths. Most of the vehicles ar longer then wider, for them I got a start point for the path right side or left side, because that is the closest point to the walkable area. The cutted mesh part under the vehicle is not a walkable area. The following code calculates a point on the NavmeshCut rectange based on the target position.
Advantage: In most cases this gives you a better start point.
Disadvantage: If there is a non walkable area between target and vehicle, then the start point may not always the best start point.
Is there any better solution to calculate the best start point around the NavmeshCut rectange?
protected Vector2 CenterOffset = new Vector2(2, 4);
void Avake() {
NavmeshCut nc = GetComponent<NavmeshCut>();
if (nc) {
// Just need the range to the side.
CenterOffset = new Vector2(nc.rectangleSize.x / 2, nc.rectangleSize.y/2);
}
}
public void SearchPath() {
// Get point on the NavmeshCut rect.
Vector3 dir = (this.TargetPosition - transform.position).normalized;
float angleDir = MetadescUtils.AngleDir(transform.forward, dir, Vector3.up);
float angle = Vector3.Angle(transform.forward, dir) * angleDir;
Vector3 dirRot = Quaternion.AngleAxis(angle, Vector3.up) * Vector3.forward;
Vector3 offset = new Vector3(dirRot.x * CenterOffset.x, dirRot.y, dirRot.z * CenterOffset.y);
Vector3 pos = transform.TransformPoint(offset);
seeker.StartPath(pos, this.TargetPosition, OnPathComplete, GRIDMASK);
}
// Utility function to get the angle direction.
static public float AngleDir(Vector3 fwd, Vector3 targetDir, Vector3 up) {
Vector3 perp = Vector3.Cross(fwd, targetDir);
float dir = Vector3.Dot(perp, up);
if (dir > 0.0f) {
return 1.0f;
} else if (dir < 0.0f) {
return -1.0f;
} else {
return 1.0f;
}
}