Skip to content

Instantly share code, notes, and snippets.

@delonnewman
Created August 15, 2022 14:30
Show Gist options
  • Save delonnewman/c49cbbd57322745741988152d5e893cd to your computer and use it in GitHub Desktop.
Save delonnewman/c49cbbd57322745741988152d5e893cd to your computer and use it in GitHub Desktop.
require 'ruby2d'
class Pt
attr_reader :x, :y
def self.[](x, y)
raise TypeError, "no implicit conversion of #{x.class} to Numeric" unless x.is_a?(Numeric)
raise TypeError, "no implicit conversion of #{y.class} to Numeric" unless y.is_a?(Numeric)
obj = allocate
obj.instance_variable_set(:@x, x)
obj.instance_variable_set(:@y, y)
obj
end
def *(other)
Pt[other * x, other * y]
end
def +(other)
Pt[x + other.x, y + other.y]
end
def inspect
"(#{format("%1.2f", x)}, #{format("%1.2f", y)})"
end
alias to_s inspect
def draw(color: 'red', size: 1)
Circle.new(x: x, y: y, radius: size, color: color)
self
end
end
class Ln
attr_reader :p0, :p1
def self.[](p0, p1)
obj = allocate
obj.instance_variable_set(:@p0, p0)
obj.instance_variable_set(:@p1, p1)
obj
end
def inspect
"#{p0.inspect} #{p1.inspect}"
end
alias inspect to_s
def draw(width: 1, color: 'blue')
Line.new(x1: p0.x, y1: p0.y, x2: p1.x, y2: p1.y, width: width, color: color)
self
end
def lerp(t)
(p0 * (1 - t)) + p1 * t
end
end
# A = Ln[Pt[ 0, 0], Pt[0.25, 0.65]]
# B = Ln[Pt[0.25, 0.65], Pt[ 0.5, 0]]
# C = Ln[Pt[ 0.5, 0], Pt[0.75, 1]]
# D = Ln[Pt[0.75, 1], Pt[ 1, 0]]
def bounce1(t)
Ln[A.lerp(t), B.lerp(t)].lerp(t)
end
def bounce2(t)
Ln[C.lerp(t), D.lerp(t)].lerp(t)
end
def animate(method)
points = (0..1).step(0.0125).map(&method)
points.each do |p|
bar = "x" * (p.y * 50)
puts "#{p}: #{bar}"
end
end
# animate(method(:bounce1))
# animate(method(:bounce2))
w = get(:width)
h = get(:height)
P0 = Pt[ 0, h].draw(size: 5, color: 'brown')
P1 = Pt[w * 0.35, h * 0.35].draw(size: 5, color: 'brown')
P2 = Pt[w * 0.5, h].draw(size: 5, color: 'brown')
P3 = Pt[w * 0.85, 0].draw(size: 5, color: 'brown')
P4 = Pt[ w, h].draw(size: 5, color: 'brown')
A = Ln[P0, P1].draw(color: 'gray')
B = Ln[P1, P2].draw(color: 'gray')
C = Ln[P2, P3].draw(color: 'gray')
D = Ln[P3, P4].draw(color: 'gray')
Ball = Circle.new(x: w - 100, y: h - 100, radius: 50, color: 'red')
t = 0
t_ = 0
phase = :bounce1
update do
if t > 0.5
t_ = (t - 0.5) * 2
phase = :bounce2
else
t_ = t * 2
end
p = send(phase, t_)
Ball.y = p.y - 50
t += 0.00625
# close if t >= 1
end
# t = 0
# t_ = 0
# phase = :bounce1
#
# update do
# if t > 0.5
# t_ = (t - 0.5) * 2
# phase = :bounce2
# else
# t_ = t * 2
# end
#
# send(phase, t_).draw(size: 2)
#
# t += 0.00625
# close if t >= 1
# end
show
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment