• QQ
  • nahooten@sina.com
  • 常州市九洲新世界花苑15-2

游戏开发

U3D协同程序实现游戏中AI(自动行走和发现目标)

原创内容,转载请注明原文网址:http://homeqin.cn/a/wenzhangboke/jishutiandi/youxikaifa/2018/1007/46.html

现在大多数游戏都有AI的身影,例如说人机模式中,机器就是依靠AI实现自动行走,追击玩家,下面要分享的教程也是关于此,利用利用协同程序实现游戏中的AI。
 
协同程序:主程序运行时同时开启另外一段逻辑处理,来协同当前的执行;同一时刻只有一个协同程序在运行,并且协同程序会影响到主线程的运行;
 
开启方法:(方法2可以传递多个参数,并且性能消耗略小)
  1. StartCorourine(string methodName)
  2. StartCorourine(IEnumerator routine)
 
如下图所示,AI(黑球)沿着5个黄色方块(Cube)所连接的绿色路径(使用Gizmos绘制)行走,当Mage(Hero)接近AI一定范围的时候,AI将会追击Mage,Mage离开范围时,AI继续之前的行走。

 
挂载在Cube上的绘制路径的脚本:WayPoint类

using UnityEngine;

using System.Collections;

public class WayPoint : MonoBehaviour

#region

public WayPoint nextWayPoint;

#endregion

void OnDrawGizmosSelected()

Gizmos.color = Color.green;

Gizmos.DrawLine(transform.position, nextWayPoint.gameObject.transform.position);

 

挂载在AI上的脚本:

using UnityEngine;

using System.Collections;

public class AI : MonoBehaviour

#region variable

[SerializeField] //保护封装性

private float speed = 3f;

[SerializeField]

private WayPoint targetPoint, startPoint;

[SerializeField]

private Hero mage;

#endregion

// Use this for initialization

void Start ()

if (Vector3.Distance(transform.position, startPoint.transform.position) < 1e-2f)

targetPoint = startPoint.nextWayPoint;

else

targetPoint = startPoint;

StartCoroutine(AINavMesh());

IEnumerator AINavMesh()

while(true)

if (Vector3.Distance(transform.position, targetPoint.transform.position) < 1e-2f)

targetPoint = targetPoint.nextWayPoint;

yield return new WaitForSeconds(2f);

if (mage != null && Vector3.Distance(transform.position, mage.gameObject.transform.position) <= 6f)

Debug.Log("侦测到敌人,开始追击!!!");

yield return StartCoroutine(AIFollowHero());

Vector3 dir = targetPoint.transform.position - transform.position;

transform.Translate(dir.normalized * Time.deltaTime * speed);

yield return new WaitForEndOfFrame();

IEnumerator AIFollowHero()

while (true)

if (mage != null && Vector3.Distance(transform.position, mage.gameObject.transform.position) > 6f)

Debug.Log("敌人已走远,放弃攻击!!!");

yield break;

Vector3 dir = mage.transform.position - transform.position;

transform.Translate(dir.normalized * Time.deltaTime * speed * 0.8f);

yield return new WaitForEndOfFrame();

 

挂载在Mage上的脚本:

using UnityEngine;

using System.Collections;

//在本实例中起到标记的作用

public class Hero : MonoBehaviour

 


上篇:上一篇:unity动态加载Resources.Load方法
下篇:下一篇:U3D用单例创建并永久化游戏对象