Im working on adding ai to a game Im working on and I cant get it to work as I want and the ai's rotation and stuff is very weird. I want it to chase the player when in a certain radius and I deleted the non working if near part so thanks.
Heres my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class follow : MonoBehaviour
{
public float moveSpeed = 2f;
public float changeDirectionInterval = 2f;
public int radius;
private Vector2 moveDirection;
private float timeSinceLastDirectionChange;
public GameObject player;
public Rigidbody2D body;
public bool IsChasing;
void Start()
{
moveDirection = new Vector2(Random.Range(-1f, 1f), Random.Range(-1f, 1f));
}
void Update()
{
if (IsChasing == true)
{
Debug.Log("Chase");
transform.LookAt(player.transform.position);
transform.Translate(transform.forward * moveSpeed * Time.deltaTime);
}
if(IsChasing == false)
{
timeSinceLastDirectionChange += Time.deltaTime;
if (timeSinceLastDirectionChange > changeDirectionInterval)
{
moveDirection = new Vector2(Random.Range(-1f, 1f), Random.Range(-1f, 1f));
timeSinceLastDirectionChange = 0;
}
transform.position += new Vector3(moveDirection.x, moveDirection.y, 0) * moveSpeed * Time.deltaTime;
}
if (timeSinceLastDirectionChange > changeDirectionInterval)
{
IsChasing = false ;
}
}
}
↧