-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpoints.rb
153 lines (133 loc) · 2.32 KB
/
points.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
#!/usr/bin/env ruby
#require 'gosu' rescue nil
#
# Class to create a array of points (to use with draw_polygon*) in an easy and natural way.
#
# Example of drawing a flat green 10pixel thick terrain with a 20x20 bump on:
#
# points = Points.new(0,0)
# points.up(10).right(100).up(20).right(20).down(20).right(20).down(10).to(0,0)
# surface.draw_polygon_s(points, Color[:green])
#
class Points
attr_reader :points
def initialize(x=nil, y=nil)
@x = x if x
@y = y if y
@points = []
@points = [[@x, @y]] if @x and @y
@width = nil
@height = nil
end
def inspect
@points.inspect
end
def to_x(x)
@x = x
add_current_point
self
end
def to_y(y)
@y = y
add_current_point
self
end
def up(amount)
@y += amount
add_current_point
self
end
def down(amount)
@y -= amount
add_current_point
self
end
def left(amount)
@x -= amount
add_current_point
self
end
def right(amount)
@x += amount
add_current_point
self
end
def move(x, y)
@x += x
@y += y
add_current_point
self
end
def to(x, y)
@x = x
@y = y
add_current_point
self
end
def to_a
@screen_coords
end
def to_screen_coords(screen_height)
@screen_coords = []
@points.each do |x, y|
@screen_coords << [x, (screen_height - y)]
end
@screen_coords
end
def <<(point)
@points << point
end
def center_x
width / 2
end
def width
@width ||= @points.collect { |p| p[0] }.max
end
def center_y
height / 2
end
def height
@height ||= @points.collect { |p| p[1] }.max
end
#
# Returns size as an array [width, height]
#
def size
x,y = 0,0
@points.each do |point|
x = point[0] if point[0] > x
y = point[1] if point[1] > y
end
return [x,y]
end
#
#
#
def normalize!
@points = self.normalize
end
#
#
#
def normalize
lowest_x = lowest_y = nil
@points.each do |point|
lowest_x ||= point[0]
lowest_y ||= point[1]
lowest_x = point[0] if point[0] < lowest_x and point[0] > 0
lowest_y = point[1] if point[1] < lowest_y and point[1] > 0
end
@points.collect { |point| [point[0]-lowest_x, point[1]-lowest_y] }
end
#
# Returns all points in chipmunks vec2-format
#
def to_chipmunk
self.normalize!
@points.collect { |point| vec2(point[0] - self.center_x, point[1] - self.center_y) }
end
private
def add_current_point
@points << [@x, @y]
end
end