Question by
Vandal16 · Jul 05, 2020 at 04:20 PM ·
2d gamepathfinding
Enemy staying at a certain distance instead attacking
Hi, I've got a problem with my enemyGameObject, whenever the player(target) is in range the enemy runs to him but stops once he is close to the player(enemy tries to not collide with the player even if the player isn't moving). I tried to change the variables NextWaypointDistance and speed of the enemy but it didn't made my problem solved. My enemy has a Enemy AI script attached and I'm using Astral Pathfinding.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Pathfinding;
public class EnemyAI : MonoBehaviour
{
public Transform target;
public Transform EnemyGFX;
public float speed = 200f;
public float nextWaypointDistance = 3f;
Path path;
int currentWaypoint = 0;
bool reachedEndOfPath = false;
Seeker seeker;
Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
seeker = GetComponent<Seeker>();
rb = GetComponent<Rigidbody2D>();
InvokeRepeating("UpdatePath", 0f, .5f);
}
void UpdatePath()
{
if (seeker.IsDone())
seeker.StartPath(rb.position, target.position, OnPathComplete);
}
void OnPathComplete(Path p)
{
if (!p.error)
{
path = p;
currentWaypoint = 0;
}
}
// Fixed used in physics etc.
void FixedUpdate()
{
if (path == null)
return;
if(currentWaypoint >= path.vectorPath.Count)
{
reachedEndOfPath = true;
return;
}else
{
reachedEndOfPath = false;
}
Vector2 direction = ((Vector2)path.vectorPath[currentWaypoint] - rb.position).normalized;
Vector2 force = direction * speed * Time.deltaTime;
rb.AddForce(force);
float distance = Vector2.Distance(rb.position, path.vectorPath[currentWaypoint]);
if (distance < nextWaypointDistance)
{
currentWaypoint++;
}
if(EnemyGFX != null)
{
if (force.x >= 0.01f)
{
EnemyGFX.localScale = new Vector3(-8f, 8f, 1f);
}
else if (force.x <= -0.01f)
{
EnemyGFX.localScale = new Vector3(8f, 8f, 1f);
}
}
}
}
sc.png
(71.4 kB)
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220613002533im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
2d Pathfinding in Unity 5.6, how it works? 0 Answers
How create a Tunnel for gameobject to follow the tunnel path. 0 Answers
Adjusting enemy speed 2 Answers
A* 2D Pathfinding not working with prefabs? 0 Answers
2D platformer AI 0 Answers