![]() |
ベクトル |
origin:Point
と offSet:Point
の値を
加算することで得られる。![]() |
極座標 |
![]() |
直交座標 |
極座標から直交座標への変換は以下のように行う。
def pol2ort(dist:Double, ang:Double) =
Point(dist*math.cos(ang), dist*math.sin(ang))
![]() |
pol2ort関数 |
また、直交座標から極座標(を構成する各々の値)は以下のように計算できる。
def polDir(to:Point, from:Point):Double=
math.atan2(to.y-from.y, to.x-from.x)
def polDist(p1:Point, p2:Point):Double=
math.sqrt(math.pow(p2.x-p1.x, 2) + math.pow(p2.y-p1.y, 2))
![]() |
距離の計算 |
距離(distance -> dist) は、ピタゴラスの定理に基いて 求めることができる(右図)。
![]() |
![]() |
![]() |
tanの定義 | tanのグラフ | atan2 |
![]() |
追跡 |
以下の例は 3. に沿って計算したもの。
def speed(orgn:Point, tgt:Point):Double= {
val d = polDist(tgt, orgn)
if(d < 40) 0 else math.min(3, 300/d)
}
loop の中で、以下のような処理を行うことになる。
val mp = mousePosition
me.setPosition(mp.x, mp.y) // 6.1 の別の書き方
for (c <- cs) {
val p = c.origin+c.offset
c.translate(pol2ort(speed(p, mp), polDir(mp, p)))
}
内包表記: map に変換される
for(i<-1 to 20) yield s.circle(...)
// ↑ と ↓ は 同じ意味
(1 to 20).map{(i)=>s.circle(...)}
(1 to 20).map((i)=>s.circle(...))
(1 to 20).map(i=>s.circle(...))
1.to(20).map(i=>s.circle(...))
// ちなみに 以下の2つも同じ意味
1 to 20
1.to(20)
// だが、
1 to 20.map(...) // これは使えない(括弧がないと意味が変わるため)
繰り返し実行: foreach に変換される
for(c<-cs) { ... }
// ↑ と ↓ は 同じ意味
cs.foreach(c=>{...})
四角い枠を作る
val trap = s.rectangle(-50, -30, 100, 60)
trap.fill(rancol)
その中に入る物体を検出する
cs.filter(c=>{
val p=c.origin+c.offset
p.x<50 && p.x>-50 && p.y<30 && p.y>-30
})
Collectionに含まれる要素の数は、以下の方法で求められる。
cs.length
(参考1)ある条件を満たす要素の数を求めるには、 以下のように書くことになる。
cs.filter(c=>{...}).length
(参考2)要素の数を求める書き方は他にもある cs.reduce((r,v)=>r+1)