- Home /
Question by
Forever061 · Jun 18, 2021 at 06:27 AM ·
ainavmeshagentraycasting
My navmesh agent isn't updating correctly?
When the player enters the view cone the navmesh agent will go to where it is, however The navmesh agent doesn't update the target location until it finishes it's path here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class Sight : MonoBehaviour
{
public Camera Eyes;
Transform target;
NavMeshAgent Agent;
public float ANGEL;
public float range;
public float turnSpeed;
private bool insight;
private void Start()
{
target = PlayerManager.instance.player.transform;
Agent = GetComponent<NavMeshAgent>();
}
private void OnDrawGizmos()
{
Gizmos.color = Color.red;
GizmosExtensions.DrawWireArc(transform.position, transform.forward, ANGEL, range, 20);
}
private void Update()
{
RaycastHit hit;
Vector3 origin = transform.position;
Vector3 direction = target.position - transform.position;
Ray ray = new Ray(origin, direction);
if (Physics.Raycast(origin, direction, out hit))
{
if (hit.collider.gameObject.tag == "Player" && Vector3.Angle(direction, Eyes.transform.forward) <= ANGEL && Vector3.Distance(direction, Eyes.transform.forward) <=range)
{
Agent.SetDestination(target.position);
float distance = Vector3.Distance(target.position, transform.position);
if (distance <= Agent.stoppingDistance)
{
FaceTarget();
}
}
}
void FaceTarget()
{
Vector3 dir = (target.position - transform.position).normalized;
Quaternion lookrotation = Quaternion.LookRotation(new Vector3(direction.x, 0, direction.z));
transform.rotation = Quaternion.Slerp(transform.rotation, lookrotation, Time.deltaTime * turnSpeed);
}
}
}
Comment
Your answer
Follow this Question
Related Questions
Checking name from hit from Raycast in array 2 Answers
NavMesh Agent Obstacle Avoidance Ignore 1 Answer
How to add variables to Components (Nav Mesh Agent)? 0 Answers
raycast hit not detecting && Nav mesh agent ai stealth 1 Answer
Modify NavMeshPath for Tactical FPS (slicing the pie/sweeping maneuver) 0 Answers