Category talk:Wren-polygon: Difference between revisions

m
→‎Source code: Now uses Wren S/H lexer.
m (→‎Source code: Infrastructure changes to enable all polygons to be treated as buttons and to make it easier to track button clicks.)
m (→‎Source code: Now uses Wren S/H lexer.)
 
(3 intermediate revisions by the same user not shown)
Line 1:
===Source code===
 
<langsyntaxhighlight ecmascriptlang="wren">/* Module "polygon.wren" */
 
import "graphics" for Canvas, Color
import "math" for Point, Vector
 
/* Selectable is an abstract class representing the interface needed for an identifiable
Line 20:
/* Polygon represents a polygon in 2 dimensional space. */
class Polygon is Selectable {
 
/* Private static helper methods for 'overlaps' instance method. */
 
static getAxes_(poly) {
var axes = List.filled(poly.sides, null)
var vertices = poly.vertices
for (i in 0...poly.sides) {
var vertex1 = vertices[i]
var vertex2 = vertices[(i+1 == poly.sides) ? 0 : i+1]
var vector1 = Vector.new(vertex1[0], vertex1[1])
var vector2 = Vector.new(vertex2[0], vertex2[1])
var edge = vector1 - vector2
axes[i] = edge.perp
}
return axes
}
 
static projectOntoAxis_(poly, axis) {
var vertices = poly.vertices
var vertex0 = vertices[0]
var vector0 = Vector.new(vertex0[0], vertex0[1])
var min = axis.dot(vector0)
var max = min
for (i in 1...poly.sides) {
var vertex = vertices[i]
var vector = Vector.new(vertex[0], vertex[1])
var p = axis.dot(vector)
if (p < min) {
min = p
} else if (p > max) {
max = p
}
}
return [min, max]
}
 
static projectionsOverlap_(proj1, proj2) {
if (proj1[1] < proj2[0]) return false
if (proj2[1] < proj1[0]) return false
return true
}
 
// Constructs a new Polygon object from its vertices and tag.
construct new(vertices, tag) {
Line 134 ⟶ 176:
}
return contained
}
 
// Returns whether this instance overlaps another Polygon object i.e. they have
// at least one point in common.
overlaps(other) {
if (!(other is Polygon)) Fiber.abort("Argument must be a Polygon.")
var axes1 = Polygon.getAxes_(this)
var axes2 = Polygon.getAxes_(other)
for (axes in [axes1, axes2]) {
for (axis in axes) {
var proj1 = Polygon.projectOntoAxis_(this, axis)
var proj2 = Polygon.projectOntoAxis_(other, axis)
if (!Polygon.projectionsOverlap_(proj1, proj2)) return false
}
}
return true
}
 
Line 239 ⟶ 297:
// Properties.
side { _s }
}</langsyntaxhighlight>
9,476

edits