TapTapTap!!!(4)~ボタンをランダムに出現させる~

TapTapTap!!!(3)~ボタンをタップして消滅させる~ボタンに対してタップされたときに消滅する処理を加えた。今回はボタンが出現する際にランダムな位置に出現する処理を加える。
今回はスクリプトに修正を加えるだけでいいため、今までのスクリプトを作ったのであれば簡単だろう。
1.出現するボタンの位置をランダムにする
TapTapTap!!!(2)~ボタンを出現・消滅させる~で作成した「ButtonManager」を改良することでランダムな位置にボタンを出現させる事ができる。前回までの「ButtonManager」は以下の通り。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47 using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ButtonManager : MonoBehaviour {
// 作成するボタンオブジェクト
[SerializeField]
public GameObject button;
// ボタンを追加するキャンバス
[SerializeField]
public GameObject canvas;
// 出現/消滅時間
public float timeOut;
// 経過時間
private float timeElapsed;
// 生成したPrefab
private GameObject prefab;
// ゲーム開始時の処理
void Start() {
createButton();
}
// 逐次更新された際の処理
void Update() {
timeElapsed += Time.deltaTime;
if (timeElapsed >= timeOut) {
// ボタンがあるかないかで生成削除を分ける
if (prefab != null) {
GameObject.Destroy(prefab);
} else {
createButton();
}
timeElapsed = 0.0f;
}
}
// ボタンの生成処理
private void createButton() {
prefab = (GameObject)Instantiate(button);
prefab.transform.SetParent(canvas.transform, false);
}
}
StartとcreateButtonそれぞれに以下の処理を加える
Start:画面の高さと幅を取得し、中心を 0 となるように計算する
createButton:画面幅の上下限値からランダムな値を決定し、Prefabのpositionを調整する
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52 using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ButtonManager : MonoBehaviour {
// 作成するボタンオブジェクト
[SerializeField]
public GameObject button;
// ボタンを追加するキャンバス
[SerializeField]
public GameObject canvas;
// 出現/消滅時間
public float timeOut;
// 経過時間
private float timeElapsed;
// 生成したPrefab
private GameObject prefab;
private int screenWidth;
private int screenHeight;
// ゲーム開始時の処理
void Start() {
screenWidth = (Screen.width - 100) - (Screen.width - 100) / 2;
screenHeight = (Screen.height - 100) - (Screen.height - 100) / 2;
createButton();
}
// 逐次更新された際の処理
void Update() {
timeElapsed += Time.deltaTime;
if (timeElapsed >= timeOut) {
createButton();
GameObject.Destroy(prefab, timeOut - 2);
timeElapsed = 0.0f;
}
}
// ボタンの生成処理
private void createButton() {
prefab = (GameObject)Instantiate(button);
// ランダムな位置を決定する
Vector3 position = new Vector3(Random.Range(-screenWidth, screenWidth), Random.Range(-screenHeight, screenHeight), 0);
// prefab の場所を更新する
prefab.transform.position = position;
prefab.transform.SetParent(canvas.transform, false);
}
}
以上の処理を加えることでランダムな位置にボタンが出現するはずだ。