スクリプトファイルを作る
スクリプトを使うと、やりたいことがもっと出来るようになる。
unityのスクリプトは、javascript と C# で書くことができるが、
スクリプトについてネット上で調べた時、C#で書いている人が多いのでC#で。
メニューバーから、Assets > Create > C# Script を選択。
プロジェクト内にスクリプトファイルが作成されるので、名前をつける。
スクリプトファイルをダブルクリックすると、エディタのアプリケーションが開くので、そこで編集を行っていく。
スクリプトを書く
using UnityEngine;
using System.Collections;
public class rotate_translate : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//↓の2行を書き足してみる
transform.Rotate(1, 1, 0); //X軸、Y軸で1ずつ回転
transform.Translate(0.01f, 0, 0); //X 方向に0.01 ずつ移動
}
}
まず、public class rotate_translate:とあるが、さっきスクリプトファイルを作成した際につけた名前がクラス名になっている。 unityのスクリプトは、MonoBehaviourを継承したクラスなので、 スクリプトファイルの名前と、このクラス名が一致していないとエラーになるので注意。
Start()とUpdate()は、processing や openFrameworksの setup() と draw() と同じ。
Start()はゲーム実行時に最初の一度だけ実行されるので、諸々の設定など初期化などを行う。
Update()はゲーム実行時、毎フレーム繰り返し実行されるので、ものを動かしたり、インタラクティブにしたり、いろいろ出来る。
あと、C#は、float型を扱う時に「 0.01f 」のように最後にfを明示的につけないといけないので注意。
上記のコードでは、対象オブジェクトの座標、回転、スケールなどの情報をもった
transformに対して、
回転させるRotate()と移動させるTranslate()を書いてみた例。
とりあえず、さっき作成したrotate_translateというスクリプトを上記のように書きたして保存。
スクリプトを適用する
スクリプトのエディタの再生ボタンを押して、エラーがないことを確認したら、
cubeなどのオブジェクトをシーンに配置して、スクリプトをドラッグ&ドロップして適用する。
実行すると、草原に浮いたオブジェクトがふんわりと回転しながら移動していく。いい感じ。
スクリプトの応用
using UnityEngine;
using System.Collections;
public class rotate_cubes : MonoBehaviour {
private GameObject g_obj;
private GameObject cube1;
private Renderer rend;
private GameObject[] objarr = new GameObject[5];
private Vector3 defpos = new Vector3 (0,0,0);
// Use this for initialization
void Start () {
print("test");
g_obj = GameObject.Find("code_obj");
defpos = g_obj.transform.localPosition;
for (int i = 0; i < objarr.Length; i++) {
objarr[i] = GameObject.CreatePrimitive(PrimitiveType.Cube);
objarr[i].transform.localScale = new Vector3 (5,5,5);
objarr[i].transform.localPosition = g_obj.transform.localPosition;
objarr[i].transform.Rotate(i, i, 0);
}
}
float c_rot = 0;
void Update () {
c_rot += 0.05f;
for (int i = 0; i < objarr.Length; i++) {
objarr[i].transform.localPosition = new Vector3 (defpos.x+Mathf.Sin(c_rot)*2, defpos.y+Mathf.Cos(c_rot)*2, defpos.z);
objarr[i].transform.Rotate((i+1)*0.1f, (i+1)*0.2f, (i+1)*0.3f);
}
}
}
プリミティブを配置して、そこにスクリプトを配置するのではなく、スクリプトの側からプリミティブを生成して配置する例。
空のオブジェクトを作って、"code_obj"という名前にする。そこに上記のスクリプトを貼り付けると、5つのcubeが重なりながら回転する。
カメラの映像を取り込む
using UnityEngine;
using System.Collections;
public class webcam : MonoBehaviour {
public int Width = 1920;
public int Height = 1080;
public int FPS = 30;
void Start () {
WebCamDevice[] devices = WebCamTexture.devices;
// display all cameras
for (var i = 0; i < devices.Length; i++) {
Debug.Log (devices [i].name);
}
WebCamTexture webcamTexture = new WebCamTexture(devices[0].name, Width, Height, FPS);
GetComponent<Renderer> ().material.mainTexture = webcamTexture;
webcamTexture.Play();
}
}
webカメラなどの映像をテクスチャとして取り込む。
1人称視点で没入することが出来ていた、ゲームの世界のリアリティが多層化する。