Reputation: 125275
You can rotate any visual Object in Unity with the Transform property. One exception is the LineRenderer
. You can't move or rotate it with the transform property.
LineRenderer
is moved with the SetPosition
or SetPositions
function so I managed to make it movable by the transform position property but I can't make make it rotate too.
Below is the code I am using to make it movable.
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 - diagLine.GetPosition(0);
endPosOffset = transform.position - diagLine.GetPosition(1);
}
void Update()
{
//Calculate new postion with offset
Vector3 newBeginPos = transform.position + beginPosOffset;
Vector3 newEndPos = transform.position + endPosOffset;
//Apply new position with offset
diagLine.SetPosition(0, newBeginPos);
diagLine.SetPosition(1, newEndPos);
}
I tried to use the-same method I used to make it able to rotate but I am stuck in the first step of getting the offset because there is no way to access the rotation variable for LineRenderer
but there is one for accessing the position GetPosition
.
How can I get the LineRenderer
rotation or how can I also make LineRenderer
be rotated from the Transform property?
Below is an image that shows the behavior of LineRenderer
with and without the script above. Position is now working with the script above enabled but rotation is not.
Upvotes: 6
Views: 12240
Reputation: 297
You can set useWorldSpace
attribute of LineRenderer to false, Then LineRenderer can be controlled using its transform component.
https://answers.unity.com/questions/39391/line-renderer-position.html
Upvotes: 3
Reputation: 4061
You can use the transform's localToWorldMatrix
:
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);
}
void Update()
{
//Calculate new postion
Vector3 newBeginPos = transform.localToWorldMatrix * new Vector4(beginPos.x, beginPos.y, beginPos.z, 1);
Vector3 newEndPos = transform.localToWorldMatrix * new Vector4(endPos.x, endPos.y, endPos.z, 1);
//Apply new position
diagLine.SetPosition(0, newBeginPos);
diagLine.SetPosition(1, newEndPos);
}
Upvotes: 5