1. 程式人生 > >unity3d 隨機範圍內生成怪物

unity3d 隨機範圍內生成怪物

  1. using UnityEngine;

  2. using System.Collections;

  3. public class BarrackManager : MonoBehaviour {

  4. public Transform[] address;

  5. public GameObject[] prefabs;

  6. // Use this for initialization

  7. void Start () {

  8. InvokeRepeating ("setBarrack",1,3f);

  9. }

  10. // Update is called once per frame

  11. void Update () {

  12. }

  13. void setBarrack(){

  14. Transform tf = address [Random.Range (0, address.Length)];

  15. Bound bound = getBound (tf);

  16. Vector3 pos = new Vector3 (bound.getRandomX(),bound.y,bound.getRandomZ());

  17. Instantiate (prefabs[0],pos,Quaternion.identity);

  18. }

  19. Bound getBound(Transform tf){

  20. Vector3 center = tf.collider.bounds.center;

  21. Vector3 extents = tf.collider.bounds.extents;

  22. Vector3 dL = new Vector3 (center.x - extents.x,center.y,center.z - extents.z);

  23. Vector3 dR = new Vector3 (center.x + extents.x,center.y,center.z - extents.z);

  24. Vector3 sR = new Vector3 (center.x + extents.x,center.y,center.z + extents.z);

  25. Vector3 sL = new Vector3 (center.x - extents.x,center.y,center.z + extents.z);

  26. Bound bound = new Bound (dL,dR,sR,sL,center.y);

  27. return bound;

  28. }

  29. class Bound{

  30. public Vector3 dL;

  31. public Vector3 dR;

  32. public Vector3 sR;

  33. public Vector3 sL;

  34. public float y;

  35. public Bound(Vector3 dL,Vector3 dR, Vector3 sR, Vector3 sL,float y){

  36. this.dL = dL;

  37. this.dR = dR;

  38. this.sR = sR;

  39. this.sL = sL;

  40. this.y = y;

  41. }

  42. public float getRandomX(){

  43. float num = Random.Range (dL.x,dR.x);

  44. return num;

  45. }

  46. public float getRandomZ(){

  47. float num = Random.Range (dL.z,sL.z);

  48. return num;

  49. }

  50. }

  51. }