我在这里有一个有效的回避脚本,但我遇到的唯一问题是它总是试图看着玩家,即使它绕过障碍物导致它抖动。我想知道如果光线投射没有撞到障碍物但让它同时向玩家移动,我怎么能让它只看玩家。任何帮助将不胜感激,目前正在使用 unity3D
using UnityEngine;
using System.Collections;
public class enemyAI : MonoBehaviour
{
public Transform target;
public float moveSpeed;
public float rotationSpeed;
public float minDistance = 0.5f;
public static enemyAI enemyAIself;
RaycastHit hit;
void Awake()
{
enemyAIself = this;
}
void Start ()
{
GameObject goTo = GameObject.FindGameObjectWithTag("Player");
target = goTo.transform;
}
void Update ()
{
Vector3 dir = (target.position - transform.position).normalized;
if (Physics.Raycast(transform.position, transform.forward, out hit, 5.0f, (1<<8)))
{
Debug.DrawRay(transform.position, hit.point, Color.blue);
dir += hit.normal * 50;
}
Vector3 leftR = transform.position;
Vector3 rightR = transform.position;
leftR.x -= 2;
rightR.x += 2;
if (Physics.Raycast(leftR, transform.forward, out hit, 5.0f, (1<<8)))
{
Debug.DrawRay(leftR, hit.point, Color.blue);
dir += hit.normal * 50;
}
if (Physics.Raycast(rightR, transform.forward, 5.0f, (1<<8)))
{
Debug.DrawRay(rightR, hit.point, Color.blue);
dir += hit.normal * 50;
}
Quaternion rot = Quaternion.LookRotation(dir);
transform.rotation = Quaternion.Slerp(transform.rotation, rot, rotationSpeed * Time.deltaTime);
if (Vector3.SqrMagnitude(target.position - transform.position)> (minDistance * minDistance))
{
//move towards the target
transform.position += transform.forward * moveSpeed * Time.deltaTime;
}
}
}