1 using UnityEngine;
2 using System.Collections;
3
4 public class AIRandMove : MonoBehaviour
5 {
6 float stopTime;
7 float moveTime;
8 float vel_x, vel_y, vel_z;//速度
9 /// <summary>
10 /// 最大、最小飞行界限
11 /// </summary>
12 float maxPos_x = 500;
13 float maxPos_y = 300;
14 float minPos_x = -500;
15 float minPos_y = -300;
16 int curr_frame;
17 int total_frame;
18 float timeCounter1;
19 float timeCounter2;
20 // int max_Flys = 128;
21 // Use this for initialization
22 void Start()
23 {
24 Change();
25 }
26
27 // Update is called once per frame
28 void Update()
29 {
30 timeCounter1 += Time.deltaTime;
31 if (timeCounter1 < moveTime)
32 {
33 transform.Translate(vel_x, vel_y, 0, Space.Self);
34 }
35 else
36 {
37 timeCounter2 += Time.deltaTime;
38 if (timeCounter2 > stopTime)
39 {
40 Change();
41 timeCounter1 = 0;
42 timeCounter2 = 0;
43 }
44 }
45 Check();
46 }
47 void Change()
48 {
49 stopTime = Random.Range(1, 5);
50 moveTime = Random.Range(1, 20);
51 vel_x = Random.Range(1, 10);
52 vel_y = Random.Range(1, 10);
53 }
54 void Check()
55 {
56 //如果到达预设的界限位置值,调换速度方向并让它当前的坐标位置等于这个临界边的位置值
57 if (transform.localPosition.x > maxPos_x)
58 {
59 vel_x = -vel_x;
60 transform.localPosition = new Vector3(maxPos_x, transform.localPosition.y, 0);
61 }
62 if (transform.localPosition.x < minPos_x)
63 {
64 vel_x = -vel_x;
65 transform.localPosition = new Vector3(minPos_x, transform.localPosition.y, 0);
66 }
67 if (transform.localPosition.y > maxPos_y)
68 {
69 vel_y = -vel_y;
70 transform.localPosition = new Vector3(transform.localPosition.x, maxPos_y, 0);
71 }
72 if (transform.localPosition.y < minPos_y)
73 {
74 vel_y = -vel_y;
75 transform.localPosition = new Vector3(transform.localPosition.x, minPos_y, 0);
76 }
77 }
78 }