how to make a character follow another characther unity c# code example
Example 1: how to make a follow script in unity
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowPlayer : MonoBehaviour
{
public float attackSpeed = 4;
public float attackDistance;
public float bufferDistance;
public GameObject player;
Transform playerTransform;
void GetPlayerTransform()
{
if (player != null)
{
playerTransform = player.transform;
}
else
{
Debug.Log("Player not specified in Inspector");
}
}
// Start is called before the first frame update
void Start()
{
GetPlayerTransform();
}
// Update is called once per frame
void Update()
{
var distance = Vector3.Distance(playerTransform.position, transform.position);
// Debug.Log("Distance to Player" + distance);
if (distance <= attackDistance)
{
if (distance >= bufferDistance)
{
transform.position += transform.forward * attackSpeed * Time.deltaTime;
}
}
}
}
Example 2: how to make a follow script in unity
var target : Transform; //the enemy's target var moveSpeed = 3; //move speed var rotationSpeed = 3; //speed of turning var range : float=10f; var range2 : float=10f; var stop : float=0; var myTransform : Transform; //current transform data of this enemy function Awake() { myTransform = transform; //cache transform data for easy access/preformance } function Start() { target = GameObject.FindWithTag("Player").transform; //target the player } function Update () { //rotate to look at the player var distance = Vector3.Distance(myTransform.position, target.position); if (distance<=range2 && distance>=range){ myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime); } else if(distance<=range && distance>stop){ //move towards the player myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime); myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime; } else if (distance<=stop) { myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime); } }