how to make an enemy patrol and chase me
hi, im a newbie in programming and im making a 2D game at the style of Risk of Rain, im trying to make that the enemy patrols around the ground/platform and make chase you when you get close, i got the part of chasing but the enemy doesnt move unless im close, could you tell me how to make him move without me entering its range? here is the code i use:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class enemycontroller : MonoBehaviour
{
private Rigidbody2D rb2D;
public float visionradius;
public float speed;
GameObject player;
void Start()
{
player = GameObject.FindGameObjectWithTag("Player");
rb2D = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
Vector2 target = transform.position;
float dist = Vector2.Distance(player.transform.position,transform.position);
if (dist < visionradius) target = player.transform.position;
float fixedspeed = speed*Time.deltaTime;
transform.position = Vector2.MoveTowards(transform.position, target, fixedspeed);
Debug.DrawLine(transform.position, target, Color.green);
}
void OnDrawGizmos(){
Gizmos.color = Color.yellow;
Gizmos.DrawWireSphere(transform.position, visionradius);
}
private void OnTriggerExit2D(Collider2D other) {
if (other.gameObject.tag == "plataforma") {
speed = -speed;
}
}
}
Comment