- Home /
Use trail renderer for path following?
Hey guys, I'm pretty new to C# and still am learning the basics. Would really appreciate some guidance. Had this idea of flying opponents chasing players spaceship in environment with obstacles. Is there a way for a gameobject to follow other gameobjects trajectory using its trail renderer component? I suppose it would involve setpositons or getpositions functions and storing the vertices on to temporary array for the chasing object to follow and destructing them afterwards. I though this would be a better way for the chasing vehicles to get destroyed in collision with obstacles (if the chasers would have different speed and delayed "reaction time" or offset target position) instead of using path finding.
Answer by Klarax · Feb 10, 2020 at 02:02 PM
kinda, i expect create ab array or something that records every few seconds its position and rotation.
and then have the object use that to transform to each transform in the array over a given amount of time
Answer by Bitcore · Feb 11, 2020 at 11:17 AM
Thanks for the hint @Klarax , it did help out a lot!
Last night came up with this, works just how intended, at least for now.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class followp : MonoBehaviour
{
//public Transform targetP;
public Vector3 LastTargetPoint;
//public Vector3 target_Offset;
public GameObject target;
public int Current_Position = 0;
const int MAX_POSITIONS = 10000;
public Vector3[] TrailRecorded = new Vector3[MAX_POSITIONS];
public float speed = 20f;
private void Start()
{
// target_Offset = transform.position - targetP.position;
}
void Update()
{
int numberOfPositions = target.GetComponent<TrailRenderer>().GetPositions(TrailRecorded);
speed += 0.25f * Time.deltaTime;
if (Current_Position < this.TrailRecorded.Length)
{
if (LastTargetPoint == null)
LastTargetPoint = TrailRecorded[Current_Position];
follow();
}
}
void follow()
{
transform.forward = Vector3.RotateTowards(transform.forward, LastTargetPoint - transform.position, speed * Time.deltaTime, 4.0f);
transform.position = Vector3.MoveTowards(transform.position, LastTargetPoint, speed * Time.deltaTime);
if (transform.position == LastTargetPoint)
{
Current_Position++;
LastTargetPoint = TrailRecorded[Current_Position];
}
}
}
Your answer
Follow this Question
Related Questions
Make an NPC follow player? 1 Answer
How to make characters follow player like Earthbound? 0 Answers
Want to make GameObject follow another GameObject's path Unity3D 1 Answer
How to make this trail? 1 Answer
Making objects follow each other in a line, and objects ignoring minimum follow distance. 2 Answers