Last active
June 14, 2016 08:44
-
-
Save s2kw/733e972af7d9ed05774a02c6d4e507cd to your computer and use it in GitHub Desktop.
毎日出題の2日目第三問の答え 亜種 description:http://wp.me/p5rxnz-hQ
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MakeCubeOnWorld : MonoBehaviour { | |
/// <summary> | |
/// 1スクリプトで対処する場合 | |
/// </summary> | |
/// 生成したキューブを格納するList | |
List<GameObject> instances = new List<GameObject>(); | |
void Update() | |
{ | |
// クリックしたフレームだけ動作焦る場合あ Input.GetMouseButtonDown() で取得する。 | |
// 以下の場合 ( Input.GetMouseButton() ) はクリック中だと毎フレーム処理される。 | |
if (Input.GetMouseButton(0)) | |
{ | |
// マウスのクリック位置を取得 | |
var screenpos = Input.mousePosition; | |
// スクリーン座標からワールド座標空間で飛ばす 線 を生成 | |
var ray = Camera.main.ScreenPointToRay(screenpos); | |
// 当たり判定の情報を以って帰ってくれる変数を宣言。宣言さえしておけばスコープ内で参照可能 | |
RaycastHit hit; | |
// Physics.Raycastで当たり判定お行う。 | |
// out が付くと、関数終了後に変数の中身が変わる可能性ああることを理解すべし | |
if (Physics.Raycast(ray, out hit, float.MaxValue)) | |
{ | |
// このブロックあヒットした場合のみ駆動する。 | |
// キューブを生成 | |
var cube = GameObject.CreatePrimitive(PrimitiveType.Cube); | |
// キューブ同士の当たりがあると吹っ飛ぶので削除 | |
var col = cube.GetComponent<Collider>(); | |
if (col != null) | |
{ | |
Destroy(col); | |
} | |
// 自由落下させるためにrigidbodyを追加 | |
cube.AddComponent<Rigidbody>(); | |
// 画面外に出たら消滅する自作スクリプトを追加 | |
// cube.AddComponent<DestroyWhenInvisible>(); | |
this.instances.Add(cube); | |
// ヒット位置は読み取り専用なのでコピー | |
var p = hit.point; | |
// カメラから10m離れた位置を代入 | |
p.z = Camera.main.transform.position.z + 10f; | |
// キューブの位置を渡す | |
cube.transform.position = p; | |
} | |
} | |
} | |
// 決まったタイミングで定期実行される関数 | |
void FixedUpdate(){ | |
for (int i = this.instances.Count -1; i >= 0; i-- ) | |
{ | |
var target = this.instances[i]; | |
if (!target.GetComponent<Renderer>().isVisible) | |
{ | |
this.instances.Remove(target); | |
Destroy(target); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment