public static RayCastResult RayCast(IEnumerable <Polygon> polygons, Vector2 startPoint, float length, float direction, float precision = 0.5f) { //bool flag = false; //float minLen = float.MaxValue; RayCastResult result = new RayCastResult(); result.RayLength = length; result.Collides = false; result.CollisionPoint = GameMath.LengthDir(length, direction) + startPoint; foreach (Polygon poly in polygons) { RayCastResult res = RayCast(poly, startPoint, length, direction, precision); if (res.Collides) { if (res.RayLength < result.RayLength) { result.RayLength = res.RayLength; result.CollisionPoint = res.CollisionPoint; } result.Collides = true; } } return(result); }
public static RayCastResult RayCast(Polygon polygon, Vector2 startPoint, float length, float direction, float precision = 0.5f) { RayCastResult result = new RayCastResult(); result.Collides = true; Vector2 endPoint = GameMath.LengthDir(length, direction) + startPoint; result.CollisionPoint = endPoint; Polygon line = new Polygon(); line.m_isConvex = true; line.m_isConvexNeedUpdate = false; line.AddPoint(startPoint); line.AddPoint(endPoint); if (!polygon.Collision(line) || polygon.Contains(startPoint)) { result.Collides = false; return(result); } float min = 0f; float max = length; float q = length; while (max - min > precision) { q = (min + max) / 2; line[1] = GameMath.LengthDir(q, direction) + startPoint; if (polygon.Collision(line)) { max = q; } else { min = q + precision; } } result.CollisionPoint = line[1]; result.RayLength = q; return(result); }