補足と実演記録 (基礎プログラミングa 第13回付録)

正方形(長方形)の中心をマウスに合わせる

me.setPosition(mouseX-50,mouseY-50)
//or
me.setPosition(mousePosition-Point(50,50))

yieldで複雑なことをするとき

def genObj={ 
	// 2つのことを行う、その操作に名前をつけた
    s.setFillColor(rancol)
    s.circle(ranp(1000,400),20)
}
// その上で、名前でそれを呼び出す
val cs=for(i<-1 to 20) yield genObj

// これは 名前をつけずに直接ブロックを書いて
val cs=for(i<-1 to 20) yield {
	...
} // でもいい

全部の物体を一斉に右(または左)にスライド

s.loop{
    for(c<-cs) 
	    // マウスの位置(中央より右か左か)で方向を制御
        if(mouseX>0)
            c.translate(1,0)
        else
            c.translate(-1,0)       
}
// for, if, else の右にはそれぞれ単一の式しかないので
// ブレースは省略してある(もちろんブレースがあってもいい)

カーソルに追従する物体群(今回のプログラム片をまとめたもの)

val s = Staging
s.clear
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))
def pol2olt(dist: Double, ang: Double) =
    Point(dist * math.cos(ang), dist * math.sin(ang))
def speed(orgn: Point, tgt: Point): Double = {
    val d = polDist(tgt, orgn)
    if (d < 40) 0 else math.min(3, 300 / d)
}
def rancol =
    color(random(256), random(256), random(256))
def ranp(width: Int, height: Int) =
    Point(random(width) - width / 2,
        random(height) - height / 2)
def gen() = {
    val c = s.circle(ranp(1000, 400), 20)
    c.fill(rancol)
    c
}
val me=s.rectangle(0,0,10,10)
me.fill(black)
val cs = for (i <- 1 to 20) yield gen
s.loop {
val mp = mousePosition
  me.setPosition(mp.x, mp.y) // 6.1 の別の書き方
  for (c <- cs) {
      val p = c.origin+c.offset
      c.translate(pol2olt(speed(p, mp), polDir(mp, p)))
  }
}