I’m using a Line Renderer to draw a prediction of the trajectory of an object.
This trajectory is physic based, but with custom behaviours (some planets or whatsoever are attracting the object).
The drawing of the trajectory works pretty fine, but for some odd reason the line jitters, as you can see on this gif: jittery-line-renderer hosted at ImgBB — ImgBB
Here is my code for this line:
private void FixedUpdate() => DrawLine();
private void DrawLine()
{
for (var i = 0; i < _positionCount; i++) _lineRenderer.SetPosition(i, GetPosition(i));
}
private Vector2 GetPosition(int index)
{
var position = GetPreviousPosition(index);
foreach (var attractor in _attractors)
{
_velocity += attractor.GetForce(position, _mass, out var insideCollider) * Time.deltaTime;
if (insideCollider) return position;
}
return position + _velocity * Time.deltaTime;
}
private Vector2 GetPreviousPosition(int index) => index == 0 ? _startPosition : (Vector2) _lineRenderer.GetPosition(index - 1);
Let me explain this a little:
For each position of the line, I retrieve the position of the previous point of the line. If I’m dealing with the first point, I take the _startPosition
which is the position of my player.
With this position, I calculate the force that every Attractors (the planets and stuff) will apply when an object of a certain mass is at a certain position (I won’t show this code, it’s a basic implementation of the universal law of gravity, and it works just as expected).
Then for each attractors, I add the calculated force multiplied by deltaTime
to my _velocity
.
The initially value of _velocity
is set by the slingshot thing, it’s the actual force my player will have when you release the mouse button.
Then I return the previous position + the _velocity
time Time.deltaTime
.
Also, if my current position is inside the collider of an attractor, I set all the next points of my line to this current position (to avoid going through objects with the trajectory line).
All this code seems to work really well, if I release the mouse, the player will indeed follow the drawn trajectory.
But this line is jittery, and I can’t find why…
I tried to put all this code in Update, and even in LateUpdate, but it did nothing good.
So if anyone have any idea, I’ll gladly accept your help.
Thanks for your attention.
EDIT:
I just realize that maybe it could be useful to know the settings of my line renderer, so here’s a screenshot: image hosted at ImgBB — ImgBB