chronos
chronos

Reputation: 537

How to move a Line Renderer as its game object moves

I created an empty game object and added a Line Renderer component to it through a script. I thought that once I adjust the position of the game object, it would do likewise for the line rendeder, but that is not the case.

I tried useWorldSpace = false but it totally changed the positions making the following points a straight line, though I was able to move the game object to to the line.

public Vector3 beginPos = new Vector3 (-1.0f, -1.0f, 0);
public Vector3 endPos = new Vector3 (1.0f, 1.0f, 0);

Is there a way I can convert points to input what I am more familiar with (so that points like the above points don't create a straight line) or should I be approaching the problem in a different way? I am open to a different approach.

UPDATE

I think I left an import detail. I'll be using lines made with line renderer to create shapes. So I need to be able to be able to move the lines around to move the shapes so I don't have to always recalculate the start and end points for the lines.

Upvotes: 0

Views: 3551

Answers (2)

Programmer
Programmer

Reputation: 125255

You just need to apply an offset to it. Get the line renderer position + the current position of the GameObject in the Start function. Apply that offset to the LineRender in the Update function.

public Vector3 beginPos = new Vector3(-1.0f, -1.0f, 0);
public Vector3 endPos = new Vector3(1.0f, 1.0f, 0);

Vector3 beginPosOffset;
Vector3 endPosOffset;

LineRenderer diagLine;

void Start()
{
    diagLine = gameObject.AddComponent<LineRenderer>();
    diagLine.material = new Material(Shader.Find("Sprites/Default"));
    diagLine.startColor = diagLine.endColor = Color.green;
    diagLine.startWidth = diagLine.endWidth = 0.15f;

    diagLine.SetPosition(0, beginPos);
    diagLine.SetPosition(1, endPos);

    //Get offset
    beginPosOffset = transform.position - beginPos;
    endPosOffset = transform.position - endPos;
}

void Update()
{

    //Calculate new postion with offset
    Vector3 newBeginPos = transform.position + beginPosOffset;
    Vector3 newEndPos = transform.position + endPosOffset;

    //Apppy new position with offset
    diagLine.SetPosition(0, newBeginPos);
    diagLine.SetPosition(1, newEndPos);
}

Upvotes: 4

Julian Declercq
Julian Declercq

Reputation: 1596

The problem is in your assumption of how the line renderer works.

Both Vector3 objects that you posted are not points, but directions instead.

Have a look at the difference between Debug.DrawLine(), which is how you assume the line renderer works, and Debug.DrawRay() which is how it actually works.

Upvotes: 0

Related Questions