オリジナルの関数を作成して、呼び出してみる。#2 processing

processingで関数を使う方法を説明します。
そもそも関数って
関数とは簡単に言うと便利な道具と思ってもらえればOKです。
例えば大きな穴を開けたいとします。
素手で掘るのは労力もかかりますし、時間もかかりますよね。
そんなときにシャベル使ったらどうでしょう。あっという間に穴を掘ることができますよね。
関数とはそんな穴を簡単に掘ることができる「便利な道具」であり、
ずっと頭が良い人たちが作ってくれたものです。
例えば円を描きたいという場合には、ellipseを使いますよね。
ellipse();
このellipseも関数のひとつで、ここには書かれていませんが、
他の場所に「円を描く」という処理が書かれており、「ellipse();」を呼び出すことによって円を簡単に描けるようになっています。
[colwrap] [col2][/col2] [col2]
[/col2] [/colwrap]
関数は自分で作れる。
voidはすでに下記のような形式ですでに見慣れているかもしれません。
実はsetupも関数で「一度だけ実行してください」という処理・関数を呼び出しています。
processingの場合「〇〇();」という書かれているものはほぼ関数と思ってもらってOKです。
void setup(){ } void draw(){ background(255); }
関数自体は呼び出すだけではなく、自分で作れる!
たくさん処理を書いたものの、長くなってしまい読みにくいなって経験ありませんか。
例えばこんな感じ。(私の最初のころ)
float starx; float stary; float stara; float starb; float starc; float stard; float stare; float starf; float starg; float starh; float stari; float starj; int star; void setup(){ size (1280,720); frameRate(15); } void draw (){ //宇宙背景 fill(20,20,30); //fill(0,209,251); noStroke(); rect(0,0,width,height); int i = 0; while (i < 200) { starx= random(1500); stary= random(750); stara= random(0,3); starb= random(0,3); starc= random(1500); stard= random(750); stare= random(0,3); starf= random(0,3); starc= random(1500); stard= random(750); stare= random(0,3); starf= random(0,3); fill(255,255,255); ellipse(starx,stary,stara,starb); fill(179,96,83); ellipse(starc,stard,stare,starf); fill(180,216,177); ellipse(starg,starh,stari,starg); i = i + 1; } } }
どんな処理が書いてあるのかわかりますが、
もし長い処理がたくさん描くとなれば読みにくくなります。
そこで新しく自分で下記のように描くことでオリジナルの関数を作成することができます。
//自分で「名称」に名前を決定 void 名称(){ //ここに処理を描く }
関数作成後↓
float starx; float stary; float stara; float starb; float starc; float stard; float stare; float starf; float starg; float starh; float stari; float starj; int star; void setup(){ size (1280,720); frameRate(15); } void draw (){ background(); } //宇宙背景 void background(){ fill(20,20,30); //fill(0,209,251); noStroke(); rect(0,0,width,height); int i = 0; while (i < 200) { starx= random(1500); stary= random(750); stara= random(0,3); starb= random(0,3); starc= random(1500); stard= random(750); stare= random(0,3); starf= random(0,3); starc= random(1500); stard= random(750); stare= random(0,3); starf= random(0,3); fill(255,255,255); ellipse(starx,stary,stara,starb); fill(179,96,83); ellipse(starc,stard,stare,starf); fill(180,216,177); ellipse(starg,starh,stari,starg); i = i + 1; } }
voidで作成した関数は void setupの下に描き、その関数をsetupの中で
background();
このような形で呼び出しています。
次回では「引数」というものを使ってさらに関数への理解を深めていきます。
[colwrap] [col2][/col2] [col2]
[/col2] [/colwrap]

この記事を書いた人
Takahiro
平日はIT企業で務める側で、フロントエンド開発を学習中。デザインやプログラミングに関することを呟いてます。