3d模式下 让敌人拥有自动移动的AI
1 using UnityEngine; 2 using System.Collections; 3 4 public class troll : MonoBehaviour 5 { 6 7 private bool isIdel=true; 8 public float timer = 2; 9 public int speed = 1; 10 // private Rigidbody rigidbody; 11 private Animator anim; 12 private CharacterController controller; 13 private float angle = 0;//旋转的角度 14 15 void Start () 16 { 17 // rigidbody = this.GetComponent<Rigidbody>(); 18 anim = this.GetComponent<Animator>(); 19 controller = GetComponent<CharacterController>(); 20 } 21 22 // Update is called once per frame 23 void Update () 24 { 25 timer -= Time.deltaTime; 26 if (timer<=0) 27 { 28 if (isIdel) 29 { 30 //行走方法 31 TransformToWalk(); 32 } 33 else 34 { 35 36 //进行站立状态 37 TransformToIdel(); 38 } 39 } 40 if (!isIdel) 41 { 42 43 44 TransformToRotate(); 45 //进行位移 46 //transform.position += transform.forward*Time.deltaTime*speed; 47 Move(); 48 } 49 50 } 51 52 public void Move() 53 { 54 controller.SimpleMove(transform.forward * speed); 55 } 56 57 public void TransformToRotate()//平滑旋转的方法 58 { 59 float temp = angle * 0.05f;//旋转的角度乘以20分之1帧 60 transform.Rotate(new Vector3(0, temp, 0)); 61 angle -= temp;//总的旋转角度减去已旋转的角度 62 } 63 64 public void TransformToIdel() 65 { 66 timer = 2f; 67 isIdel = true; 68 AnimationToIdel(); 69 } 70 71 public void TransformToWalk() 72 { 73 isIdel = false; 74 timer = 5f; 75 angle = Random.Range(-90, 90); 76 77 AnimationToWalk(); 78 } 79 80 public void AnimationToWalk() 81 { 82 anim.SetFloat("walk",1.0f); 83 anim.SetFloat("idle",0f); 84 anim.SetFloat("run",0f); 85 } 86 87 public void AnimationToIdel() 88 { 89 anim.SetFloat("walk", 0f); 90 anim.SetFloat("idle", 1.0f); 91 anim.SetFloat("run", 0f); 92 } 93 }