Check if a polygon overlaps with a rectangle: Difference between revisions

m
Line 479:
 
function axes(poly::Polygon)
result = [(0.0, 0.0) plenfor =_ in lengtheachindex(poly)]
for (i, vertex1) in enumerate(poly)
result = [(0.0, 0.0) for _ in 1:plen]
vertex2 = i == plenlastindex(poly) ? first(poly) : poly[i+1] # wraps around
for (i, vertex1) in enumerate(poly)
edge = (first(vertex1[1]) - first(vertex2[1]), last(vertex1[2]) - last(vertex2[2]))
vertex2 = i == plen ? first(poly) : poly[i+1] # wraps around
result[i] = (-last(edge[2]), first(edge[1]))
edge = (vertex1[1] - vertex2[1], vertex1[2] - vertex2[2])
end
result[i] = (-edge[2], edge[1])
return result
end
return result
end
 
function projectiononaxis(poly::Polygon, axis::Vector2)
resultmin, resultmax = Inf, -Inf
resultmin = Inf
for vertex in poly
resultmax = -Inf
p = fordot(axis, vertex in poly)
p < resultmin && (resultmin = Infp)
p = dot(axis, vertex)
p > resultmax && (resultmax = p)
if p < resultmin
end
resultmin = p
return elseif p >(resultmin, resultmax)
resultmax = p
end
end
return (resultmin, resultmax)
end
 
projectionoverlaps(p1::Projection, p2::Projection) = p1[2] <= p2[1] && p2[2] >= p1[1]
 
Polygon(r::Rectangle) return= [(r.x, r.y), (r.x, r.y + r.h), (r.x + r.w, r.y + r.h), (r.x + r.w, r.y)]
function Polygon(r::Rectangle)
return [(r.x, r.y), (r.x, r.y + r.h), (r.x + r.w, r.y + r.h), (r.x + r.w, r.y)]
end
 
function polygonoverlapsrect(poly1p1::Polygon, rect::Rectangle)
poly2 p2 = Polygon(rect)
return if !any(projectionoverlaps(projectiononaxis(poly1p1, axis), projectiononaxis(poly2p2, axis))
for a in [axes(poly1p1), axes(poly2p2)] for axis in a)
isnothing(a) && continue
for axis in a
if projectionoverlaps(projectiononaxis(poly1, axis), projectiononaxis(poly2, axis))
return false
end
end
end
return true
end
 
const poly = [(0.0, 0.0), (0.0, 2.0), (1.0, 4.0), (2.0, 2.0), (2.0, 0.0)]
let
const polyrect1 = [Rectangle(0.0, 0.0), (04.0, 2.0), (1.0, 4.0), (2.0, 2.0), (2.0, 0.0)]
const rect1rect2 = Rectangle((41.0, 0.0, 28.0, 2.0))
println("poly = a polygon with vertices: ", poly)
rect2 = Rectangle((1.0, 0.0, 8.0, 2.0))
println("polyrect1 = a polygonRectangle with vertices: ", polyrect1)
println("rect1rect2 = Rectangle with ", rect1rect2)
println("rect2\npoly =and Rectanglerect1 withoverlap? ", rect2polygonoverlapsrect(poly, rect1))
println("\npolypoly and rect1rect2 overlap? ", polygonoverlapsrect(poly, rect1rect2))
println("poly and rect2 overlap? ", polygonoverlapsrect(poly, rect2))
end
</syntaxhighlight>{{out}}
<pre>
Line 540 ⟶ 524:
poly and rect1 overlap? false
poly and rect2 overlap? true
&lt;/pre>
 
</pre>
 
4,105

edits