Hi!
I am moving an enemy to a character (enemy finds character and going to attack the character).
So the enemy has a point to walk to, but when it finds a character, it will walk towards the character. For some reason, the enemy has a constant speed until it finds the character. It slows down and moves toward the character but VERY slowly.
I am using transform.translate to move from one point to another, and when the enemy finds the character the target point changes.
Also I made it so that the enemy finds the character if it is 1 unit of distance away, and moves toward the character until it is at least 0.5f away from the character.
This is my code
void Update()
{
if (inAttackRange)
{
enemy.Attack();
return;
}
if (characterFound)
{
randomRange = new Vector3(0f, 0f, 0f);
Debug.Log(Vector2.Distance(transform.position, target.position).ToString());
if (Vector2.Distance(transform.position, target.position) <= enemy.attackRange)
{
inAttackRange = true;
}
}
else
{
randomRange = new Vector3(Random.Range(-0.3f, 0.3f), Random.Range(-0.3f, 0.3f), 0f);
if (target != currentNodeDestiny)
{
target = currentNodeDestiny;
}
if (Vector3.Distance(transform.position, target.position) <= 0.2f)
{
GetNextWayPoint();
}
}
Vector3 dir = (target.position + randomRange) - transform.position;
Debug.Log("direction: " + dir.ToString());
transform.Translate(dir.normalized * enemy.enemyMovementSpeed * Time.deltaTime, Space.World);
}
Is it because the values are too small? I tested using bigger values and it seems to work. Or maybe is it because with the Vector3 comparisons? To check the distance I am using Vector2 because in Vector3 it never finds it.
Also used Debug.log to see the dir and to see the distance. For some reason, the code skips the “Debug.Log(“direction:” + dir.ToString())” a random amount of frames, the debug.log that shows the distance is not skipped, but the distance is changing really slow.
edit. it’s in 2d