I m designing a game in which , once a character sees the other one it automatically chases it and catch it if the other got stuck without any way to move. Please help me how to make the object to chase and catch the other one.
Lets denote character A as the one which is being chased and Character B as the chaser.
When character A is seen by any other character, it should log its positions few times per second in a list. Then for instance character B reads the positions and interpolates its position to the recorded positions (you can use Vector3.Lerp to do the interpolation). You can play with the third argument, which is time, to manipulate the speed of the chasers.
Other characters can do the same. However, if you don’t want to end up with having all chasers at the same position, you can either have random offsets, or/and use different timing values as mentioned before.
Of course you need to flush or overwrite the list values to avoid having a big list of positions.
When a chaser’s distance is in a specific range to character A, you can conclude that A is caught.
Character2 follows Character1 (I always use the Characters as transform) if you don’t link their transform u will need to replace all “CharacterX”-code with “CharactrerX.transform”
First Character2 always looks at Character1. Doing this by
Character2.LookAt(Character1);
Then to let Character2 follow Character1 do this
Character2.position = Vector3.Lerp(Charactre2.position, Character1.position, TimeTillCatch);
At the end just check if the distance (with Vector3.Distance) is as low as u want and do the stuff you want to. Show a “You lose” or something like this.
Thanks To both of yu guys I need to make my object to chase the other object only when both are near. Using Vector3.distance(charac1,charac2) is enough? can u help me with this logic
You could try something like this below. This is a script that I used in a space game, in which an enemy has to chase the player.
private GameObject player;
private CharacterController controller;
public float speed;
public float chaseRange;
public float dieRange;
void Start()
{
controller = GetComponent<CharacterController>();
player = GameObject.Find("Ship");
}
void Update()
{
if (player == null)
return;
float range = Vector3.Distance(player.transform.position, transform.position);
if (range <= dieRange)
{
//Player looses one life
}
else if (range <= chaseRange)
{
//Enemy chase the player
transform.LookAt(player.transform);
Vector3 moveDirection = transform.TransformDirection(Vector3.forward);
controller.Move(moveDirection * speed * Time.deltaTime);
}
else if (range >= dieRange)
{
//Do something
}
}