Skip to content

Commit 5d23d62

Browse files
author
monkstone
committed
add modules section to basics
1 parent 7b3be60 commit 5d23d62

File tree

2 files changed

+90
-0
lines changed

2 files changed

+90
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# encoding: UTF-8
2+
3+
# module encapsulating run
4+
module Runner
5+
def run
6+
move
7+
render
8+
bounds_collision
9+
end
10+
end
11+
12+
# Euler Ball Class, we include Processing::Proxy module to access PApplet methods
13+
class EulerBall
14+
include Processing::Proxy, Runner
15+
attr_reader :pos, :spd, :radius, :bounds_x, :bounds_y
16+
17+
def initialize(position:, speed:, radius:)
18+
@pos = position
19+
@spd = speed
20+
@radius = radius
21+
@bounds_x = Bounds.new(lower: radius, upper: width - radius)
22+
@bounds_y = Bounds.new(lower: radius, upper: height - radius)
23+
end
24+
25+
def move
26+
@pos += spd
27+
end
28+
29+
def render
30+
ellipse(pos.x, pos.y, radius * 2, radius * 2)
31+
end
32+
33+
def bounds_collision
34+
pos.x = bounds_x.position pos.x
35+
spd.x *= -1 unless bounds_x.inside
36+
pos.y = bounds_y.position pos.y
37+
spd.y *= -1 unless bounds_y.inside
38+
end
39+
end
40+
41+
# Convenient boundary class, we only include MathTool module for constrain
42+
class Bounds
43+
include Processing::MathTool
44+
attr_reader :low, :high, :inside
45+
def initialize(lower:, upper:)
46+
@low = lower
47+
@high = upper
48+
@inside = true
49+
end
50+
51+
# Returns the current position or the limit, sets the `inside` flag
52+
def position(val)
53+
@inside = true
54+
return val if (low..high).cover? val
55+
@inside = false
56+
return constrain(val, low, high)
57+
end
58+
end
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
#
2+
# Euler Integration (v01)
3+
# pos += spd
4+
# sketch after Ira Greenwood
5+
# Features first class keyword arguments, and use of modules
6+
#
7+
require_relative 'euler_ball'
8+
9+
attr_reader :ball
10+
11+
def setup
12+
sketch_title 'Euler Integration'
13+
@ball = EulerBall.new(
14+
position: Vec2D.new(width / 2, height / 2),
15+
# create a random direction vector, scaled by 3
16+
speed: Vec2D.random * 3,
17+
radius: 10
18+
)
19+
end
20+
21+
def draw
22+
background(255)
23+
# fill(255, 2)
24+
# rect(-1, -1, width + 1, height + 1)
25+
fill(0)
26+
ball.run
27+
end
28+
29+
def settings
30+
size(400, 400)
31+
smooth 4
32+
end

0 commit comments

Comments
 (0)