Ruby 2Dで手書き風の円

December 13, 2019

前回知った(思い出した)Ruby 2Dを早速使ってみます。

公式のチュートリアルはここにあります。

https://www.ruby2d.com/learn/get-started/

Window

さてまずはウィンドウを表示します。

1
2
3
4
5
6
7
8
9
10
11
12
# frozen_string_literal: true

require 'bundler/inline'

gemfile do
  source 'https://rubygems.org'

  gem 'ruby2d'
end

set(width: 300, height: 300)
show

bundler/inline、サンプルを示すときに1ファイルにまとめられるので便利ですね。

これをcircle.rbなどの名前で保存して実行します。

1
$ ruby circle.rb 

無事、300x300の画面が表示されました。

次に円を表示します。 と言っても用意されたCircleクラスをただ使ってもつまらないので、自分で円を描きます。

三角関数はこういうことに使えると中学生の頃に知りたかったです。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Point = Struct.new(:x, :y)

center = Point.new(150, 150)
radius = 100

points = 0.upto(360).map do |degrees|
  radians = degrees * Math::PI / 180
  Point.new(
    center.x + Math.cos(radians) * radius,
    center.y + Math.sin(radians) * radius
  )
end

(points + [points[0]]).each_cons(2) do |point1, point2|
  Line.new(
    x1: point1.x, y1: point1.y,
    x2: point2.x, y2: point2.y,
    width: 2,
    color: 'white'
  )
end

set(width: 300, height: 300)
show

描けました。

手書き風

自分で座標を計算しているので、加工するのも簡単です。 手書き風にしてみましょう。

手書きと言えばノイズ、ノイズと言えばパーリンノイズです。 (こいつの名前だけは覚えている)

Rubyのことです、どうせgemがあるでしょう……ありました!

https://github.com/junegunn/perlin_noise

Gemの追加を合わせて5行変更するだけです。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
   source 'https://rubygems.org'
 
   gem 'ruby2d'
+  gem 'perlin_noise'
 end
 
 Point = Struct.new(:x, :y)
 
 center = Point.new(150, 150)
 radius = 100
+n1d = Perlin::Noise.new 1
 
 points = 0.upto(360).map do |degrees|
   radians = degrees * Math::PI / 180
+  noise = 1 + n1d[radians] * 0.3
   Point.new(
-    center.x + Math.cos(radians) * radius,
-    center.y + Math.sin(radians) * radius
+    center.x + Math.cos(radians) * radius * noise,
+    center.y + Math.sin(radians) * radius * noise
   )
 end

手書き風になりました。

Ruby 2D、いいですね。 Rubyでもクリエイティブコーディング的なことができる気がしてきました。

コードはGitHubに置いてあります。

https://github.com/tnantoka/ruby.tnantoka.com/blob/8d578e0bf9c128977143e95f5030fb1fd3fb53d8/circle.rb