■コライダーを二つ持たせる
今回は空からアイテムが降ってくるようにした。この場合、物理挙動用のコライダーと、プレイヤーとの接触判定用のコライダーの二つを持たせる必要がある。(公式チュートリアルのSurvival Shooterを参考にした)- 物理挙動用コライダー
- 床をすり抜けないようにするためのコライダー
- よってIsTriggerにはチェックを入れないし、RigidBodyのIsKinematicにもチェックを入れることはできない
- このコライダーがプレイヤーにぶつかるほど大きいと、アイテムを取れなくなったり、壁に体を押し付けるような不快な挙動になる
- 落下はするが、他のコライダーにぶつかって倒れたり転がっていくことは望んでいないため、RigidBodyのConstrainsはY以外フリーズしてある
- ただ、「条件を満たしていないため取れないアイテム」を再現したい場合、この接触判定が残るのでイマイチ。IsTriggerにチェックを入れて、スクリプトで床を判定させたほうがいいかもしれない。
- 接触判定用コライダー
- プレイヤーとの接触判定用のコライダー
- プレイヤーがこのコライダーの内部に入ったとき、アイテム取得の処理をしたいのでIsTriggerにチェックを入れる
■スクリプト(コインのプレハブにアタッチ)
- 色々とアイテムを作ったが、ここではゲームの肝であるコインについて紹介
- コインのプレハブには、子オブジェクトにパーティクルシステムを持たせている
- Startで取得できるキャラをランダムで決定し、そのキャラに対応してパーティクルの色を変更している
- ステージ上にはアイテムのスポーンポイントが4つある。アイテムを生成できる数に上限を設けたかったので、アイテムとスポーン管理クラスは紐付けしている。
This file contains 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
using UnityEngine; | |
using System.Collections; | |
public class CoinBehaviour : MonoBehaviour { | |
public ParticleSystem parSys; | |
public int score = 10;//<! コインによる獲得スコア | |
private SpawnManager spawn; //<! SpawnManagerで設定 | |
private string [] objectNames = {"SunnySD","LunaSD","StarSD"};//<! Hierarchy上のオブジェクト名を変更の際は注意 | |
private int gettableIndex = 0;//<! コインを入手できるキャラクターのindex。objectNamesに対応。 | |
private ScoreManager scoreManager; | |
void Start(){ | |
//HierarchyからScoreManagerを見つけ、管理クラスをscoreManagerに代入 | |
GameObject manager = GameObject.FindWithTag("Manager"); | |
scoreManager = manager.GetComponent<ScoreManager>(); | |
//コインを入手できるキャラクターをランダムで決定 | |
gettableIndex = Random.Range (0, objectNames.Length); | |
//パーティクルの色を変える | |
SetCollor(gettableIndex); | |
} | |
// Update is called once per frame | |
void Update () { | |
//回転の演出 | |
transform.Rotate(Vector3.up, 5, Space.World); | |
} | |
//このコインをInstantiateしたSpawnManagerを受け取る | |
public void SetSpawnManager(SpawnManager spaMan){ | |
spawn = spaMan; | |
} | |
void SetCollor(int index){ | |
//インデックスに応じてパーティクルの色を変更 | |
switch(index){ | |
case 0: | |
parSys.startColor = Color.red; | |
break; | |
case 1: | |
parSys.startColor = Color.white; | |
break; | |
case 2: | |
parSys.startColor = Color.blue; | |
break; | |
} | |
} | |
void OnTriggerEnter(Collider other){ | |
//Playerタグを持っているか確認 | |
if(other.tag == "Player"){ | |
//このコインを入手可能なキャラが現在アクティブか確認 | |
Transform chaTra = other.transform.Find("Character"); | |
GameObject obj = chaTra.Find (objectNames [gettableIndex]).gameObject; | |
if (obj.activeSelf) { | |
//コインの入手 | |
GetCoin(); | |
} | |
} | |
} | |
void GetCoin(){ | |
//対応するスポーンのカウンターを減らす | |
spawn.counter--; | |
//スコアの処理 | |
scoreManager.GetScore(score); | |
//このオブジェクトを破壊 | |
Destroy (gameObject); | |
} | |
} |
0 件のコメント:
コメントを投稿