Hi,
I am working on an FPS game and I want the enemy to follow the character if it sees the player. I used Vector3.MoveTowards but for some reason it is not working. Here is my code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Distance : MonoBehaviour
{
public float Distance_;
public float Range;
public Transform player;
public Transform enemy;
public float followSpeed;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void FixedUpdate()
{
Distance_ = Vector3.Distance(player.position, enemy.position);
if(Distance_ <= Range)
{
Distance_ = Range;
var ray = new Ray(enemy.position, player.position);
RaycastHit hit;
if(Physics.Raycast(ray, out hit))
{
if(hit.collider.tag == "player")
{
Debug.DrawLine(enemy.position, player.position, Color.red);
enemy.position = Vector3.MoveTowards(enemy.position, player.position, followSpeed * Time.deltaTime);
}
}
}
}
}