How do I make a enemy follow me
Asked Answered
L

6

0

I am making a fps shooter and I need my enemy to follow me when I am with in a certain range of the enemy this is what I have so far.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
  
public class MovetowrdsPlayer : MonoBehaviour
{
    public GameObject Player;
    public bool Speed;
    public void Update()
    {
        rigidbody.velocity = transform.forward * Speed;
    }
}

Is this really the way?

Lilia answered 3/4, 2024 at 21:6 Comment(1)

You can do it, try to do step-by-step: - Find the distance between the enemy and the player position. - Try to rotate the enemy to face the player, it's a nice detail. - Don't forget to assign a Rigidbody to the enemy in order to move it See if you can work it out!

Predation
J
0

Here is a script that might help

//set the values in the inspector
public Transform target; //drag and stop player object in the inspector
public float within_range;
public float speed;
  
public void Update(){
     //get the distance between the player and enemy (this object)
    float dist = Vector3.Distance(target.position, transform.position);
    //check if it is within the range you set
    if(dist <= within_range){
      //move to target(player) 
      transform.position = Vector3.MoveTowards(transform.position, target.transform.position, speed);      
    }
    //else, if it is not in rage, it will not follow player
}

The way you were trying to accomplish wouldn’t work, but I see what you were going for.

Janenejanenna answered 3/4, 2024 at 21:8 Comment(3)

The only problem is that all the enemy's clump together into one big enemy any advice

Lilia

I have 5 enemies? is there any colder I can add

Lilia

Or maybe you could try A* path finding algorithm for this. check it out : [youtube link][1] [1]: https://youtu.be/63zWZ2rJZ68

Ringside
A
0

You can do this in a variety of ways.

One method I recently used was adding a Sphere Collider to the enemy, with a big radius. Then, I created a script that tells the enemy to follow the player if the player collides with the Sphere Collider.

public class EnemyFollow : MonoBehaviour
{
	//I first start getting the transform (position) of my player
        public Transform target;
        //Then I set up the speed of the enemy, that I can edit later
	public float speed = 2f;
        //Lastly, I added the enemy a rigidbody
	public Rigidbody rb;
  
//First thing, I will create a function that follows the player
void FollowPlayer(){
    	//I will create a vector 3 called pos that stores the movement that I want my player to do
         Vector3 pos = Vector3.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
        //I will use these two built-in functions to follow the player
        rb.MovePosition(pos);
       	transform.LookAt(target);
    }
    
//Finally, I add a collider function that calls the FollowPlayer() function when it is within its range
void OnTriggerStay(Collider player){
	  		if(player.tag == "Player"){
	    		FollowPlayer();
	    	}
	    }
}

There are many other ways, but I think this is the simplest one and will work for you. Hope this helps!

Aaren answered 3/4, 2024 at 21:9 Comment(0)
B
0

@Lilia, this is the basic chaser script. Hope this helps !

using UnityEngine;
using System.Collections;

//[RequireComponent(typeof(CharacterController))]

public class Chaser : MonoBehaviour {
	
	public float speed = 20.0f;
	public float minDist = 1f;
	public Transform target;

	// Use this for initialization
	void Start () 
	{
		// if no target specified, assume the player
		if (target == null) {

			if (GameObject.FindWithTag ("Player")!=null)
			{
				target = GameObject.FindWithTag ("Player").GetComponent<Transform>();
			}
		}
	}
	
	// Update is called once per frame
	void Update () 
	{
		if (target == null)
			return;

		// face the target
		transform.LookAt(target);

		//get the distance between the chaser and the target
		float distance = Vector3.Distance(transform.position,target.position);

		//so long as the chaser is farther away than the minimum distance, move towards it at rate speed.
		if(distance > minDist)	
			transform.position += transform.forward * speed * Time.deltaTime;	
	}

	// Set the target of the chaser
	public void SetTarget(Transform newTarget)
	{
		target = newTarget;
	}

}
Bravin answered 10/4, 2024 at 23:13 Comment(0)
G
0

I get weird behavior using this. If I restart the scene a couple of times the enemies fly away from the player. It usually happens after 4th restart, sometimes more. @Bravin

Griqua answered 3/5, 2023 at 17:19 Comment(0)
C
0

I’ve made an small adjustment because it wasn’t functioning in Unity-2017-1

BasicFollower.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BasicFollower : MonoBehaviour
{
    //set the values in the inspector
    public Transform target; //drag and stop player object in the inspector
    public float within_range;
    public float speed;

    void Update ()
    {
        //get the distance between the player and enemy (this object)
        float dist = Vector3.Distance(target.position, transform.position);

        //check if it is within the range you set
        if (dist <= within_range)
        {
            //move to target(player) 
            transform.position = Vector3.MoveTowards(transform.position, target.transform.position, speed);
        }
        //else, if it is not in rage, it will not follow player
    }
}

Corroborate answered 3/4, 2024 at 22:17 Comment(0)
D
0

The easiest way to do this is with a NavMeshAgent like in my case with a sphere collider to trigger it. You also would need to set the walkability of the surfaces (Lots of vids to help)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class enemyAi : MonoBehaviour
{  private Transform player;
   void Start(){
     player = GameObject.FindGameObjectWithTag("Player").transform;
   }
    [SerializeField] private Transform movePositionTransform;
    private NavMeshAgent navMeshAgent;
    private bool isChasingPlayer = false; // Flag to track if the enemy is chasing the player
    public Animator animator;

    private void Awake()
    {
        navMeshAgent = GetComponent<NavMeshAgent>();
    }

    private void Update()
    {
        if (isChasingPlayer)
        {
         
            // If chasing, set the destination to the player's position
            navMeshAgent.destination = movePositionTransform.position;
        }
          float distanceToPlayer = Vector3.Distance(transform.position, player.position);
                  if (distanceToPlayer <= 5.0f)
        {
          void Update()
        {  animator.SetBool("Walk", false);
          isChasingPlayer = false;
          animator.SetTrigger("attack");
            // Handle attack behavior (e.g., deal damage to player)
        }
        }
        else
        { void Update()
          { 
           animator.SetBool("Walk", true);
           isChasingPlayer = true;
          }
        }

    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Player"))
        {
            // If the player enters the sphere collider, start chasing
            isChasingPlayer = true;
             animator.SetBool("idle", false);
             animator.SetBool("Walk", true);
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.CompareTag("Player"))
        {
            // If the player exits the sphere collider, stop chasing
            isChasingPlayer = false;
            animator.SetBool("idle", true);
            animator.SetBool("Walk", false);
        }
    }
}

Overall in my opinion this is probably the best and easiest way to do it. As it has many features to help with these types of things

Diedra answered 4/4, 2024 at 4:57 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.