-
Notifications
You must be signed in to change notification settings - Fork 0
/
ball.rb
executable file
·81 lines (65 loc) · 1.3 KB
/
ball.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
class Ball
SIZE = 16
attr_reader :x, :y, :angle, :speed
def initialize
@x = Pong::WIDTH/2
@y = Pong::HEIGHT/2
@angle = rand(120) + 30
@angle *= -1 if rand > 0.5
@speed = 6
end
def dx; Gosu.offset_x(angle, speed); end
def dy; Gosu.offset_y(angle, speed); end
def move!
@x += dx
@y += dy
if @y < 0
@y = 0
bounce_off_edge!
end
if @y > Pong::HEIGHT
@y = Pong::HEIGHT
bounce_off_edge!
end
end
def bounce_off_edge!
@angle = Gosu.angle(0, 0, dx, -dy)
end
def x1; @x - SIZE/2; end
def x2; @x + SIZE/2; end
def y1; @y - SIZE/2; end
def y2; @y + SIZE/2; end
def draw(window)
color = Gosu::Color::RED
window.draw_quad(
x1, y1, color,
x1, y2, color,
x2, y2, color,
x2, y1, color,
)
end
def off_left?
x1 < 0
end
def off_right?
x2 > Pong::WIDTH
end
def intersect?(paddle)
x1 < paddle.x2 &&
x2 > paddle.x1 &&
y1 < paddle.y2 &&
y2 > paddle.y1
end
def bounce_off_paddle!(paddle)
case paddle.side
when :left
@x = paddle.x2 + SIZE/2
when :right
@x = paddle.x1 - SIZE/2
end
ratio = (y - paddle.y) / Paddle::HEIGHT
@angle = ratio * 120 + 90
@angle *= -1 if paddle.side == :right
@speed *= 1.1
end
end