How to make object follow line vectors
I'm using the below code to create a line which shows an objects intended path of travel. It works really well, but I can't for the life of me figure out how to use the vectors created to have an abject follow that path at a set speed. Would really appreciate someone pointing me in the right direction.
void DrawQuadraticBezierCurve(Vector3 point0, Vector3 point1, Vector3 point2)
{
lr.positionCount = 200;
float t = 0f;
B = new Vector3(0, 0, 0);
for (int i = 0; i < lr.positionCount; i++)
{
B = (1 - t) * (1 - t) * point0 + 2 * (1 - t) * t * point1 + t * t * point2;
lr.SetPosition(i, B);
t += (1 / (float)lr.positionCount);
}
}
Answer by tadadosi · Jun 01, 2020 at 01:22 AM
Really dirty attempt to do it. Stored the points on a Vector3[] array and used a simple logic on Update to switch between each vector, passing its position to the gameobject transform.position. There should be a better way of doing this, this is just a simple test that could give you a clue to come up with a better answer.
public float stepDuration = 0.01f;
public bool isActive;
private Vector3 B;
private Vector3[] BPoints;
private int index;
private float t;
private void Update()
{
if (isActive)
{
t += Time.deltaTime;
if (t / stepDuration >= 1)
{
index++;
t = 0.0f;
}
if (index <= BPoints.Length - 1)
{
Vector3 targetPosition = new Vector3(BPoints[index].x, transform.position.y, BPoints[index].z);
transform.position = targetPosition;
}
}
}
void DrawQuadraticBezierCurve(Vector3 point0, Vector3 point1, Vector3 point2)
{
BPoints = new Vector3[200];
lr.positionCount = 200;
float t = 0f;
B = new Vector3(0, 0, 0);
for (int i = 0; i < lr.positionCount; i++)
{
t += (1 / (float)lr.positionCount);
B = (1 - t) * (1 - t) * point0 + 2 * (1 - t) * t * point1 + t * t * point2;
lr.SetPosition(i, B);
BPoints[i] = B;
}
}
That worked! Thanks much. I'd been banging my head against that for hours. Any ideas on how I could adjust the travel speed? I tried changing stepDuration but it seemed to have no effect.
Possibilities that I can think of:
A variable to change the amount of positions in your bezier curve, by increasing or reducing that amount, it should move slower or faster.
A variable to change the index added value, like index += step; (a bigger value should make it go faster)
$$anonymous$$ix both things to have more control.
$$anonymous$$ore great advice, Tadadosi. $$anonymous$$uch appreciated! increasing the index value did the trick. You've saved me a lot of time.
Your answer
Follow this Question
Related Questions
How can you make a path with a switch in it? 2 Answers
How to move an Object in a path? 0 Answers
Doing an Update Function only once 1 Answer
How to draw a path from players's position to the target position where i touch? 0 Answers
2D NPC Movement 0 Answers