How to make “Friend Follows Player” in Unity Game Development

This is a video tutorial showing you how to make a friendly object/character that will follow the player object anywhere it goes. For example in this game I have FPS character controller, and wherever I go I can make that friendly object walks following me (the player).

This is the script that I used in this video, I call it FriendMover.cs

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

public class FriendMover : MonoBehaviour
{
	
	public string playerName = "PlayerName";
	public float speed = 3f;
	public float distance = 5f;
    GameObject player;
    Animator anim;
    // Start is called before the first frame update
    void Start()
    {
        player = GameObject.Find(playerName);
        anim = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
		
		if(Vector3.Distance(transform.position, player.transform.position) < distance){
			anim.SetBool("isMoving", false);
		}else{
			anim.SetBool("isMoving", true);
			Quaternion targetRotation = Quaternion.LookRotation(player.transform.position - transform.position);
            transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, 3 * Time.deltaTime);
            transform.position += transform.forward * speed * Time.deltaTime;
		}
		
    }

}

Leave a Reply

Your email address will not be published. Required fields are marked *