LoginSignup
4
4

More than 5 years have passed since last update.

Ruby-Processing 視界内の円に色づけする(2D)

Posted at

視界内の円に色づけするサンプルです。
視界内にある円のうち、右側の円には赤く、左側の円には緑に色づけしています。

angle-of-view.gif

angle-of-view.rb
load_library :vecmath

# Y 軸上方向が正として計算しています。
# (描画時には y 座標の符号を判定しています)

def setup
  size 400, 400

  n = 100 # 点の個数
  @vecs = (1..n).map { Vec2D.new(rand(width)-width/2, rand(height)-height/2) }
end

# 二つのベクトルのなす角を求める
def calc_angle(a, b)
  cos_theta = a.dot(b) / (a.mag * b.mag)
  Math::acos(max(0, min(1, cos_theta)))
end

def draw
  background 255
  translate width/2, height/2 # 原点を画面中央にする

  m = Vec2D.new(mouse_x - width/2, -(mouse_y - height/2))# マウス位置

  angle_of_view = 30 # 視野角
  left  = m.rotate(-angle_of_view.radians)
  right = m.rotate( angle_of_view.radians)

  # ウィンドウ外までベクトルを伸ばす
  m *= 100; left *= 100; right *= 100

  line(0, 0, m.x, -m.y)
  line(0, 0, left.x, -left.y)
  line(0, 0, right.x, -right.y)

  @vecs.each {|v|
    # ベクトルの内積を計算して、angle_of_view 以下か調べる
    if calc_angle(m, v) <= angle_of_view.radians
      # マウス位置のベクトルに対して v ベクトルが左右どちらの方向か調べる
      sign = m.cross(v)
      if sign < 0 # m の右側
        fill 255, 0, 0
      else # m の左側
        fill 0, 255, 0
      end
    else
      no_fill
    end
    ellipse(v.x, -v.y, 8, 8)
  }
end

コマンドラインから次のように実行します。

$ rp5 run angle-of-view.rb
4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4