Created
July 14, 2011 10:55
-
-
Save etrepat/1082264 to your computer and use it in GitHub Desktop.
Check if a given point is inside a triangle
This file contains 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
# encoding: utf-8 | |
require 'pp' | |
class Point | |
attr_accessor :x, :y | |
def initialize(x=0.0, y=0.0) | |
@x = x | |
@y = y | |
end | |
end | |
class Triangle | |
attr_accessor :points | |
def initialize(points=[]) | |
@points = points | |
end | |
def area | |
compute_area(@points) | |
end | |
def inside?(point) | |
pab = compute_area([point, @points[0], @points[1]]) | |
pbc = compute_area([point, @points[1], @points[2]]) | |
pac = compute_area([point, @points[0], @points[2]]) | |
(pab + pbc + pac) == area | |
end | |
private | |
# Finds the area of a polygon | |
# From: http://en.wikipedia.org/wiki/Polygon#Area_and_centroid | |
def compute_area(points) | |
c = points.last | |
area = 0 | |
points.each do |point| | |
area += c.x * point.y - point.x * c.y | |
c = point | |
end | |
area.abs / 2.0 | |
end | |
end | |
t = Triangle.new([Point.new(0,0), Point.new(10,10), Point.new(10, 0)]) | |
pp t | |
pp t.inside?(Point.new(5,5)) # => true | |
pp t.inside?(Point.new(3,8)) # => false | |
t = Triangle.new([Point.new(0,0), Point.new(10, 0), Point.new(0, 0)]) | |
pp t | |
pp t.inside?(Point.new(5,5)) # => false | |
pp t.inside?(Point.new(3,8)) # => false | |
pp t.inside?(Point.new(2,0)) # => true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment