Question by
Ondrak500 · Sep 07, 2019 at 12:32 PM ·
rigidbody2dmovement scriptenemy airangeenemy damage
Enemy AI: Stop distance
Hello i was trying to make my enemy stop in front of player using if(Vector2.Distance(transform.position, player.position) > minDistance)
. But that doesnt work as i intended. Enemy should start following the player in certain range that worked fine with if(Vector2.Distance(transform.position, player.position) <= range)
.
Here is full code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
public int Health;
public Transform player;
public float range;
public float speed;
public Animator anim;
public Transform goblinRange;
public float attackRangeGoblin;
public LayerMask whatIsPlayer;
public int damage;
private float timeBtwAttack;
public float startTimeBtwAttack;
// Start is called before the first frame update
private void Start()
{
}
// Update is called once per frame
void Update()
{
if (Vector2.Distance(transform.position, player.position) <= range)
{
anim.SetBool("GWalking", true);
transform.position = Vector2.MoveTowards(transform.position, player.position, speed * Time.deltaTime);
Collider2D[] playerToDamage = Physics2D.OverlapCircleAll(goblinRange.position, attackRangeGoblin, whatIsPlayer);
for (int i = 0; i < playerToDamage.Length; i++)
{
playerToDamage[i].GetComponent<PlayerMovement>().TakeDamage(damage);
}
}
else
{
Idle();
}
}
private void FixedUpdate()
{
if (Health <= 0)
{
Destroy(gameObject);
}
}
private void Idle()
{
anim.SetBool("GWalking", false);
}
public void TakeDamage(int Damage)
{
Health -= Damage;
Debug.Log("Damage Taken");
}
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(goblinRange.position, attackRangeGoblin);
}
private void Attack()
{
anim.SetTrigger("goblinAttack");
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612211825im_/https://answers.unity.com/themes/thub/images/avi.jpg)