Daniel Lip
Daniel Lip

Reputation: 11319

How can I use LineRenderer to draw a circle depending on radius size around an object?

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(LineRenderer))]
public class DrawRadiusAround : MonoBehaviour
{
    [Range(0, 50)]
    public int segments = 50;
    [Range(0, 5)]
    public float xradius = 5;
    [Range(0, 5)]
    public float yradius = 5;
    LineRenderer line;

    void Start()
    {
        line = gameObject.GetComponent<LineRenderer>();

        line.positionCount = segments + 1;
        line.useWorldSpace = false;
        CreatePoints();
    }

    void CreatePoints()
    {
        float x;
        float y;
        float z;

        float angle = 20f;

        for (int i = 0; i < (segments + 1); i++)
        {
            x = Mathf.Sin(Mathf.Deg2Rad * angle) * xradius;
            y = Mathf.Cos(Mathf.Deg2Rad * angle) * yradius;

            line.SetPosition(i, new Vector3(x, y, 0));

            angle += (360f / segments);
        }
    }
}

Some problems :

This screen show is showing the start point or the line renderer in pink near the object before running the game :

Small pink of the line renderer before running the game, How to make that it will not show it ?

This screenshot is showing the drawn circle of the radius and the linerenderer the script settings in run time :

Drawn circle of radius in run time

Upvotes: 1

Views: 2314

Answers (1)

Ruzihm
Ruzihm

Reputation: 20249

To make the circle horizontal, vary the Z coordinate instead of the Y coordinate:

// ...
x = Mathf.Sin(Mathf.Deg2Rad * angle) * xradius;
y = Mathf.Cos(Mathf.Deg2Rad * angle) * yradius;

line.SetPosition(i, new Vector3(x, 0f, y));
// ..

To change the line width, vary the value of line.widthMultiplier:

line.widthMultiplier = 2f;

To change the radius, alter xradius and yradius then call CreatePoints again:

xradius = yradius = 10f;
CreatePoints();

The circle appears "incomplete" because the ends of the line renderer don't overlap sufficiently. To fix this, go further than 360 degrees by changing the 360f in the last line to something greater. For instance:

// ...
x = Mathf.Sin(Mathf.Deg2Rad * angle) * xradius;
y = Mathf.Cos(Mathf.Deg2Rad * angle) * yradius;

line.SetPosition(i, new Vector3(x, 0f, y));

angle += (380f / segments);
// ...

Upvotes: 1

Related Questions