LoginSignup
2
1

More than 1 year has passed since last update.

ruby-sketchの基本的記法

Last updated at Posted at 2021-12-04

最初に

これはruby-sketchの記法メモ。
ruby-sketchが入っていない場合こちらの情報が役に立つ。
使ったことのない人でAppleユーザーの人ならこのアプリのExamples/Basicsの方が
この記事よりもずっとわかりやすい。
ドキュメントがここから見られる。

コード内にrequire 'rubysketch-processing'が必要。(2022年2月27日現在)

よく使うメソッド

point x, y
点を描く。

line x1, y1, x2, y2
直線を描く。

rect x, y, width, height
左上の座標を指定して長方形(矩形)を描く。

square x, y, expand
正方形を描く。

ellipse x, y, width, height
楕円のようなものを描く。

circle x, y, expand
円を描く。

triangle x1, y1, x2, y2, x3, y3
三角形を描く。

text str, x, y
文字を表示する。

文字

最初に内容である文字列を渡してから座標を指定する。
文字の大きさはStrokeWeightではなくtextSizeで指定するので注意。

text "Hello world!", w, h

イメージ

イメージをmyImage = loadImage "#{location}"で読み込んでからimage myImage, x, y で表示させる。

myImage = loadImage "hogehoge.png"
image myImage, 100,200

イベント

Draw

drawの中にあるものは一秒間に60回描画される。
frameCountにはそれまでに描画されたフレーム数が保存される。

draw do
  green = frameCount % 256
  #greenが時間によって変わる
  fill 222, 222, green
  text "#{frameCount}", 100, 100
end

Mouse

MouseEventには3種類あり、

  • 押したときに反応するmousePressed
  • 離したときに反応するmouseReleased
  • ドラッグしたら反応するmouseDraggedがある。
    mouseX,mouseY = 現在のマウスのx, y
    pmouseX,pmouseY = 直近のマウスのx, y
mousePressed do 
  ellipse mouseX, mouseY, 100, 100
end

mousePressed do 
  line mouseX, mouseY, mouseX + 200, mouseY + 100
end

mouseDragged do 
  rect pmouseX, pmouseY, 400, 300
end

Key

KeyEventには2種類あり、押したときに反応するkeyPressed・離したときに反応するkeyReleased
ある。
keyCode = 何のキーが押されたか

keyPressed do 
  char = keyCode
  if char == RIGHT then
    text "You should go there", 500, 500
end

keyReleased do
  char = keyCode
  if char == SPACE then
    text "You pressed space key!", 200, 200
  end
end

その他

回転

rotate angleで回転させる。単位はラジアンなので注意。radians #{角度}で角度をラジアンに変換できる。

draw do
  angle = radians (frameCount % 50)
  rotate angle
  fill 0, 0, 0
  ellipse 200, 200, 200, 200
end

移動

translate x, yで移動させる。x, yが正の値で右上に向かうわけではなくxが右に、yが下に向かう
drawEventでフレームが変わると元の位置に戻されるので注意。

draw do 
  x = frameCount
  x %= width #widthは画面の横幅
  translate x, width / 2
  fill 0, 0, 0
  rect 0, 0, 100, 100
end

拡大・縮小

scale w, hで横方向と縦方向を別々に拡大縮小できる。

rate = 50
rectMode CENTER
rect 50, 50, 100, 100
mousePressed do
  rate+=10
  scale rate, rate

スタック

pushで現在の座標と属性を保存でき、popで復元する。
pushEvent?ではブロックが終わったら自動でpopしてくれる。

ellipse 0, 0, 200, 200
push do #黒色の円が保存される
  translate 0, 100
  fill 255, 0, 0 #円を移動させて赤色にする
end #黒色の円が復元される。

便利関数

background R, G, B 背面をその色で塗る。drawイベントと合わせると、ウィンドウのサイズを変えても大丈夫になる。

2
1
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
2
1