- Home /
How to draw circular sector in RunTime?
I want to draw a circular sector in Runtime. Something like the following command but in run time: Handles.DrawSolidArc An image is attached to clarify. The arc changes dynamically during the runtime in a way that p0 and p1 are constant and p2 moves on a circle with a known radius. What is the best way to implement it? Any help is appreciated.
Answer by Namey5 · Jun 16, 2020 at 06:25 AM
This shader will draw a sector with the desired angle using UV coordinates. You can attach it to a plane/quad, scale the object to your circle's radius, align the forward vector of the plane with [p1-p0] and find the angle between [p1-p0] and [p2-p0] as your input angle to the shader. If you need the plane to be on a tilt between the two vectors, then you can take the cross product of the two and use that as the plane's normal.
Shader "Custom/Sector"
{
Properties
{
_Color ("Color", Color) = (1,1,1,1)
_Angle ("Angle", Range(0,360)) = 120.0
}
SubShader
{
Tags { "RenderType"="Transparent" "Queue"="Transparent" "PreviewType"="Plane" }
Pass
{
Blend SrcAlpha OneMinusSrcAlpha
ZWrite Off
Cull Off
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
half _Angle;
half4 _Color;
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float4 pos : SV_POSITION;
float2 uv : TEXCOORD0;
};
v2f vert (appdata v)
{
v2f o;
o.pos = UnityObjectToClipPos (v.vertex);
o.uv = v.uv;
return o;
}
half4 frag (v2f i) : SV_Target
{
//Re-map this now rather than later
float2 pos = -(i.uv * 2.0 - 1.0);
//Calculate the angle of our current pixel around the circle
float theta = degrees (atan2 (pos.x, pos.y)) + 180.0;
//Get circle and sector masks
float circle = length (pos) <= 1.0;
float sector = theta <= _Angle;
//Return the desired colour masked by the circle and sector
return _Color * (circle * sector);
}
ENDCG
}
}
}
Answer by YasinJavaid_ · Jun 16, 2020 at 08:00 AM
Hi, here is your simple solution, follow below points.
1) create cylinder and set its y scale to 0.01 (or any N feasible for your).
2) Set cylinder position to P01 position that is in your figure.
bellow screen is for ref.
p01 same position that have cylinder.
3) Now calculate radius of p01 and p02. code bellow.
float radius = Vector3.Distance(p01.transform.position, p02.transform.position);
4) Set radius to cylinders X and Z scale and you get the perfect circular shape. code bellow.
cylinder.transform.localScale = new Vector3(radius,0.01f/*any N value */, radius);
5) use any material for colors , you can also use your custom cylinder for more circular round shape and transparent etc.
6) complete code.
public GameObject cylinder;
public GameObject p01, p02;
void Start()
{
float radius = Vector3.Distance(p01.transform.position, p02.transform.position);
cylinder.transform.localScale = new Vector3(radius,0.01f/*any N value */, radius);
}