Created
March 9, 2014 15:18
-
-
Save anonymous/9449297 to your computer and use it in GitHub Desktop.
Unity 以Collider+Rigdbody達成攻擊物件偵測
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; | |
using System.Collections.Generic; | |
public class AttackColliderController : MonoBehaviour { | |
// 宣告公開變數 touchEnemy 為 TestEnemyHP List | |
public List<GameObject> touchEnemyObject; | |
public string targetEnemyTag = "Enemy"; | |
// 委託監聽 | |
public delegate void AttackEventHandler(GameObject go); | |
public event AttackEventHandler onAttackEnemy; | |
// 當 標籤為 目標敵人 物件 進入 碰撞區,將之加入 touchEnemy List | |
void OnTriggerEnter (Collider otherEnemy) { | |
if (otherEnemy.tag == targetEnemyTag) { | |
// 判斷List中是否已有重複元素 | |
if (!touchEnemyObject.Contains(otherEnemy.gameObject) ) | |
{ | |
touchEnemyObject.Add( otherEnemy.gameObject ); | |
OnAttackEnemy( otherEnemy.gameObject ); | |
} | |
} | |
} | |
// 當 標籤為 目標敵人 物件 進入 碰撞區,將之移除 touchEnemy List | |
/*void OnTriggerExit(Collider otherEnemy) { | |
if (otherEnemy.tag == targetEnemyTag) { | |
touchEnemyUnderAttackScript.Remove(otherEnemy.GetComponent<TestEnemyHP>()); | |
} | |
}*/ | |
// 委託監聽的 攻擊函數,傳入要攻擊的敵人物件 | |
void OnAttackEnemy (GameObject go) | |
{ | |
if (onAttackEnemy != null){ | |
onAttackEnemy (go); | |
} | |
} | |
void ClearEnemyList(){ | |
touchEnemyObject.Clear (); | |
} | |
// 當 碰撞物件停用,清除 touchEnemy List | |
void OnDisable(){ | |
ClearEnemyList (); | |
} | |
} |
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 ListenAttackEvent : MonoBehaviour { | |
public GameObject attackColliderController; | |
void Awake () { | |
// 註冊監聽並呼叫OnAttack | |
attackColliderController.GetComponent<AttackColliderController>().onAttackEnemy += OnAttack; | |
} | |
void OnAttack (GameObject go) { | |
print (go.name); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment