Adventure Creator Wikia
Advertisement

AC's Character: NPC follow Action can be used to make an NPC follow the Player, but this works by having the NPC stay within a certain distance - regardless of direction.  The script below allows for movement that's similar to JRPGs, where companions stick more rigidly behind the Player, following the Player's exact motion.

To use it:

  1. Create a C# script named RigidFollow, and paste in the code below.
  2. Add the new Rigid Follow component to an empty GameObject in the scene.
  3. Fill in its Inspector, assigning both an NPC, and the distance they should keep from the Player.
  4. To stop/start following in-game, use the Object: Call event or Object: Send message Actions to trigger the component's StartFollowing and StopFollowing functions.

RigidFollow.cs:

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

[RequireComponent (typeof (Paths))]
public class RigidFollow : MonoBehaviour
{

	public NPC npc;
	public float distance = 2f;
	public bool followPlayer;
	private Paths path;

	private List<Vector3> lastPositions = new List<Vector3> ();
	private const int MaxPositions = 100;
	private const float MinSqrDistThreshold = 0.1f;

	public void StartFollowing () { followPlayer = true; }
	public void StopFollowing () { followPlayer = false; }

	void Start ()
	{
		path = GetComponent<Paths> ();
		if (path == null)
		{
			gameObject.AddComponent<Paths> ();
			path = GetComponent<Paths> ();
		}
	}

	void Update ()
	{
		Vector3 position = KickStarter.player.transform.position;
		if (lastPositions.Count == 0 || (position - lastPositions[lastPositions.Count - 1]).sqrMagnitude > MinSqrDistThreshold)
		{
			lastPositions.Add (position);
			if (lastPositions.Count > MaxPositions)
			{
				lastPositions.RemoveAt (0);
			}

			path.nodes = lastPositions;
			path.transform.position = lastPositions[0];
			while (path.GetTotalLength () > distance)
			{
				path.nodes.RemoveAt (0);
				path.transform.position = path.nodes[0];
			}

			if (!followPlayer) return;

			if (path.nodes.Count > 1)
			{
				npc.MoveToPoint (path.transform.position);
			}
			else
			{
				Vector3 relativePosition = npc.transform.position - KickStarter.player.transform.position;
				if (relativePosition.magnitude > distance)
				{
					Vector3 newPosition = KickStarter.player.transform.position + (relativePosition.normalized * distance);
					npc.MoveToPoint (newPosition);
				}
			}
		}
	}

}
Advertisement