unity AI寻路

最近在在学习AI寻路中,找到了一些比较实用的干货,就是用Physic.RayCast 让敌人AI绕过障碍物找到玩家。
看到了别人的总结,所以分享一下,Physic.RayCast是一种能解决AI绕过障碍物的方法,但并不是一个完美的解决方法,同时里面一些参数需要根据游戏场景稍微进行调整。代码来源转自:http://www.theappguruz.com/blog/unity-3d-enemy-obstacle-awarness-ai-code-sample
代码:
Enemy AI
using UnityEngine;
using System.Collections;

public class EnemyAI: MonoBehaviour {
// Fix a range how early u want your enemy detect the obstacle.
private int range;
private float speed;
private bool isThereAnyThing = false;

// Specify the target for the enemy.
public GameObject target;
private float rotationSpeed;
private RaycastHit hit;
// Use this for initialization
void Start() {
range = 80;
speed = 10 f;
rotationSpeed = 15 f;
}

// Update is called once per frame
void Update() {
//Look At Somthly Towards the Target if there is nothing in front.
if (!isThereAnyThing) {
Vector3 relativePos = target.transform.position - transform.position;
Quaternion rotation = Quaternion.LookRotation(relativePos);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime);
}

// Enemy translate in forward direction.
transform.Translate(Vector3.forward * Time.deltaTime * speed);

//Checking for any Obstacle in front.
// Two rays left and right to the object to detect the obstacle.
Transform leftRay = transform;
Transform rightRay = transform;

//Use Phyics.RayCast to detect the obstacle

if (Physics.Raycast(leftRay.position + (transform.right * 7), transform.forward, out hit, range) || Physics.Raycast(rightRay.position - (transform.right * 7), transform.forward, out hit, range)) {

if (hit.collider.gameObject.CompareTag(“Obstacles”)) {
isThereAnyThing = true;
transform.Rotate(Vector3.up * Time.deltaTime * rotationSpeed);
}
}

// Now Two More RayCast At The End of Object to detect that object has already pass the obsatacle.
// Just making this boolean variable false it means there is nothing in front of object.
if (Physics.Raycast(transform.position - (transform.forward * 4), transform.right, out hit, 10) ||
Physics.Raycast(transform.position - (transform.forward * 4), -transform.right, out hit, 10)) {
if (hit.collider.gameObject.CompareTag(“Obstacles”)) {

isThereAnyThing = false;

}
}

// Use to debug the Physics.RayCast.
Debug.DrawRay(transform.position + (transform.right * 7), transform.forward * 20, Color.red);

Debug.DrawRay(transform.position - (transform.right * 7), transform.forward * 20, Color.red);

Debug.DrawRay(transform.position - (transform.forward * 4), -transform.right * 20, Color.yellow);

Debug.DrawRay(transform.position - (transform.forward * 4), transform.right * 20, Color.yellow);

}
}


版权声明:本文为ykdmx原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。