me.setPosition(mouseX-50,mouseY-50)
//or
me.setPosition(mousePosition-Point(50,50))
数学で扱うベクトルと同様
Point(30,40)+Point(70,80) //=> Point(100, 120) {:.language-scala]
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 の右にはそれぞれ単一の式しかないので
// ブレースは省略してある(もちろんブレースがあってもいい)
マウスの位置で速度も制御するなら以下のような方法もある
s.loop {
for(c<-cs)
c.translate(mouseX/100,0)
} {:.language-scala]
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)))
}
}