简体   繁体   中英

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:

  • The circle is standing vertical and not like it should be horizontal.

  • How can I make that I will be able to change in run time the radius size and the circle width?

  • How can I make that in the editor mode before running the game it will not show the line renderer first point near the target object that it should be around?

  • The circle in run time is not completed at the top of it there is a place with some space or a missing part.

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

运行游戏前线渲染器的小粉红色,怎么让它不显示呢?

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

在运行时绘制的半径圆

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);
// ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM