Created
September 8, 2021 14:42
-
-
Save fallengiants/d536b4f59be72a73bb21d52fa2271739 to your computer and use it in GitHub Desktop.
Point math for finding voronoi edges
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Point | |
| attr_accessor :x, :y | |
| def initialize(x,y) | |
| @x = x.to_f | |
| @y = y.to_f | |
| end | |
| def pointize_args(x_or_point, y = nil) | |
| if x_or_point.is_a?(Point) | |
| x_or_point | |
| else | |
| Point[x_or_point, y] | |
| end | |
| end | |
| def distance_from(*args) | |
| pt = pointize_args(*args) | |
| Math.sqrt(((pt.x - @x).abs ** 2) + ((pt.y - @y).abs ** 2)) | |
| end | |
| def midpoint(*args) | |
| pt = pointize_args(*args) | |
| Point[(pt.x + @x)/2, (pt.y+@y)/2] | |
| end | |
| def to_s | |
| "<Point #{@x},#{@y}>" | |
| end | |
| def sort_closest(*points) | |
| points.sort_by {|p,q| distance_from(p) <=> distance_from(q)} | |
| end | |
| class << self | |
| def [](x,y) | |
| new(x,y) | |
| end | |
| def polygonal_midpoint(*points) | |
| dnm = points.length | |
| _x = points.inject(0) {|s,i| s + i.x} / dnm | |
| _y = points.inject(0) {|s,i| s + i.y} / dnm | |
| self[_x, _y] | |
| end | |
| end | |
| end | |
| point_1 = Point[50, 50] | |
| point_2 = Point[30, 30] | |
| point_3 = Point[80, 60] | |
| puts Point.polygonal_midpoint(point_1, point_2, point_3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment