How to Draw a Circle in Unity

Draw a curve using linerenderer

Sometimes, yous need to describe lines, circles or curves in your Unity games. In these cases, y'all tin can use Unity's LineRenderer course. In this tutorial, we will run across how we can draw lines, polygons, circles, wave functions, Bézier Curves. And likewise we will see how nosotros can do a free drawing using Line Renderer in Unity3D. In lodge to come across our other Unity tutorials, click here.

Line Renderer Component

To describe a line we have to add a LineRenderer component to a game object. Fifty-fifty if this component can be attached to whatsoever game object, I propose you create an empty game object and add together the LineRenderer to this object.

Nosotros need a material which will be assigned to LineRenderer. To do this create a fabric for the line in Project Tab. Unlit/Color shader is suitable for this fabric.

Line Material of Line Renderer in Unity3D

Assign LineMat material to the Line Renderer component.

adding line material

Line Renderer draws lines between determined positions. In other words, we tell the Line Renderer the points which will be connected and Line Renderer connects these points.

Line width of the line which will be rendered

In the Positions section, y'all tin change the number of points and positions of points. If you enter 2 dissimilar points, you will get a directly line. You can also modify the width of the line in the section below.

A straight line which is rendered using line renderer in Unity3D

As well, two depict a triangle, y'all need 3 points and to depict a rectangle you need four points. Let's draw a rectangle as an example.

To draw a rectangle, we need to set positions of four points. We also accept to check the Loop toggle to obtain a closed shape.

A square which is rendered using line renderer in Unity3D

Cartoon Lines From C# Script

If we want to draw or command lines in real-fourth dimension, nosotros need to create a C# script. To draw lines from a script, we determine the size of position assortment and coordinates of positions in C# script. Therefore, LineRenderer can connect the points.

Let's draw a triangle using a script every bit an case. First, create a script with the proper name "DrawScript". And attach this script to a game object which already has a LineRenderer component.

          public          course          DrawScript          :          MonoBehaviour          {          private          LineRenderer lineRenderer;          void          Outset(          )          {          lineRenderer          =          GetComponent<LineRenderer>          (          )          ;          Vector3[          ]          positions          =          new          Vector3[          3          ]          {          new          Vector3(          0          ,          0          ,          0          )          ,          new          Vector3(          -          1          ,          i          ,          0          )          ,          new          Vector3(          1          ,          1          ,          0          )          }          ;          DrawTriangle(positions)          ;          }          void          DrawTriangle(Vector3[          ]          vertexPositions)          {          lineRenderer.positionCount          =          three          ;          lineRenderer.SetPositions(vertexPositions)          ;          }          }        

This script will depict a triangle. Note that nosotros already set the line width to 0.ane and checked the loop toggle, before. Therefore the same setting is too valid here.

A triange which is rendered using line renderer in Unity3D

We tin also change the line width from the script using startWidth and endWidth. In add-on to this, if yous would like to alter line width by position, you tin can set different values to them. In this example, Line Renderer will interpolate the line width according to position.

          public          class          DrawScript          :          MonoBehaviour          {          private          LineRenderer lineRenderer;          void          Start(          )          {          lineRenderer          =          GetComponent<LineRenderer>          (          )          ;          Vector3[          ]          positions          =          new          Vector3[          three          ]          {          new          Vector3(          0          ,          0          ,          0          )          ,          new          Vector3(          -          1          ,          1          ,          0          )          ,          new          Vector3(          i          ,          1          ,          0          )          }          ;          DrawTriangle(positions,          0.02          f          ,          0.02          f          )          ;          }          void          DrawTriangle(Vector3[          ]          vertexPositions,          float          startWidth,          float          endWidth)          {          lineRenderer.startWidth          =          startWidth;          lineRenderer.endWidth          =          endWidth;          lineRenderer.loop          =          true          ;          lineRenderer.positionCount          =          three          ;          lineRenderer.SetPositions(vertexPositions)          ;          }          }        

Drawing Regular Polygons and Circles

In this section, we are going to see how we can write a method that draws regular polygons. Since circles are n-gons which has big n, our function volition exist useful for circles also. Simply first, allow me explain the mathematics behind it.

Vertices of regular polygons are on a circle. Also, the centre of the circle and the center of the polygon are top of each other. The most reliable method to depict a polygon is to find the bending between successive vertices and locate the vertices on the circle. For example, angle of the arc between successive vertices of a pentagon is 72 degrees or for an octagon, information technology is 45 degrees. To find this angle, we can divide 360 degrees(or 2xPI radians) with the number of vertices.

Rotation matrices

So nosotros need to find the positions of the vertices. To do this we assign an initial point for the first vertex and rotate this vertex for each vertex using a rotation matrix.

As y'all probably know, in society to rotate a indicate effectually an centrality, we multiply the position vector of the indicate with the rotation matrix. Rotation matrices for rotations effectually x, y and z axes are given on the right.

For example, when we want to rotate a bespeak by ninety degrees effectually the z-centrality, which has a coordinate (1,0,0), we multiply the position vector by a rotation matrix.

Rotating a point around z-axis

We need to construct a rotation matrix to rotate each vertex around the z-axis. Permit'southward me write our DrawPolygon method start and explain it.

          void          DrawPolygon(          int          vertexNumber,          float          radius,          Vector3 centerPos,          float          startWidth,          bladder          endWidth)          {          lineRenderer.startWidth          =          startWidth;          lineRenderer.endWidth          =          endWidth;          lineRenderer.loop          =          true          ;          bladder          bending          =          2          *          Mathf.PI          /          vertexNumber;          lineRenderer.positionCount          =          vertexNumber;          for          (          int          i          =          0          ;          i          <          vertexNumber;          i+          +          )          {          Matrix4x4 rotationMatrix          =          new          Matrix4x4(          new          Vector4(Mathf.Cos(bending          *          i)          ,          Mathf.Sin(bending          *          i)          ,          0          ,          0          )          ,          new          Vector4(          -          1          *          Mathf.Sin(angle          *          i)          ,          Mathf.Cos(angle          *          i)          ,          0          ,          0          )          ,          new          Vector4(          0          ,          0          ,          ane          ,          0          )          ,          new          Vector4(          0          ,          0          ,          0          ,          1          )          )          ;          Vector3 initialRelativePosition          =          new          Vector3(          0          ,          radius,          0          )          ;          lineRenderer.SetPosition(i,          centerPos          +          rotationMatrix.MultiplyPoint(initialRelativePosition)          )          ;          }          }        

You may wonder why the constructed rotation matrix is 4×4. In reckoner graphics, the 3-dimensional world is represented as 4-dimensional but this topic is not related to our business concern here. Nosotros just use it as if it is three-dimensional.

We fix the position of initial vertex and rotate it using rotationMatrix each time and add the centre position to it.

The following image is an example of a hexagon which is fatigued by this method.

A hexagon which is rendered using line renderer in Unity3D by C# script

If you increment the number of vertex points, this polygon turns to a circle.

A circle which is rendered using line renderer in Unity3D by C# script

Drawing Waves

In this section, nosotros are going to draw a sinusoidal wave, a traveling wave and a standing wave using sine function.

The mathematical function of the sine wave is given by the following:

Sine wave functions

where

Wave number

Here, k is wave number, f is frequency, ω is the angular frequency, λ is wavelength, v is the linear speed, t is the time and φ is the phase angle. We volition not worry about the phase bending in our discussions.

Sine wave equation with a minus sign represents traveling wave from left to correct and the equation with plus sign represents a traveling line moving ridge correct to left.

In guild to draw a stable sinusoidal moving ridge, we tin can drib the time part. The following method will draw a sine wave.

          void          DrawSineWave(Vector3 startPoint,          float          amplitude,          float          wavelength)          {          float          10          =          0f;          float          y;          bladder          k          =          two          *          Mathf.PI          /          wavelength;          lineRenderer.positionCount          =          200          ;          for          (          int          i          =          0          ;          i          <          lineRenderer.positionCount;          i+          +          )          {          x          +          =          i          *          0.001          f          ;          y          =          amplitude          *          Mathf.Sin(grand          *          x)          ;          lineRenderer.SetPosition(i,          new          Vector3(x,          y,          0          )          +          startPoint)          ;          }          }        

Our DrawSineWave method takes three parameters. They are startPoint which is for setting the starting time position in world infinite, amplitude which is for setting the amplitude of the wave and wavelength which is for setting the wavelength of the sine moving ridge.

A sine wave which is rendered using line renderer in Unity3D by C# script

To obtain the positions of the corresponding mathematical function, first, nosotros determine the positions on the ten-axis. For each ten, we have to summate the y-position.

To breathing this wave, we have to implement time to our office as follows:

          void          DrawTravellingSineWave(Vector3 startPoint,          float          aamplitude,          float          wavelength,          float          waveSpeed)          {          float          x          =          0f;          bladder          y;          float          k          =          2          *          Mathf.PI          /          wavelength;          bladder          w          =          k          *          waveSpeed;          lineRenderer.positionCount          =          200          ;          for          (          int          i          =          0          ;          i          <          lineRenderer.positionCount;          i+          +          )          {          ten          +          =          i          *          0.001          f          ;          y          =          aamplitude          *          Mathf.Sin(k          *          ten          +          due west          *          Fourth dimension.time)          ;          lineRenderer.SetPosition(i,          new          Vector3(x,          y,          0          )          +          startPoint)          ;          }          }        
A traveling sine wave which is rendered using line renderer in Unity3D by C# script
A standing sine wave which is rendered using line renderer in Unity3D by C# script

This time we have four parameters. The fourth parameter is to prepare the wave speed. This wave travels to the left since nosotros used plus sign in the function. If we would like to create a wave that travels to the correct, we have to apply the minus sign. You should continue in mind that we accept to write this method in Update().

To create a standing moving ridge, we accept to add together two waves which travel to the correct and which travel to left.

          void          DrawStandingSineWave(Vector3 startPoint,          bladder          amplitude,          bladder          wavelength,          float          waveSpeed)          {          float          ten          =          0f;          float          y;          bladder          k          =          2          *          Mathf.PI          /          wavelength;          float          w          =          thousand          *          waveSpeed;          lineRenderer.positionCount          =          200          ;          for          (          int          i          =          0          ;          i          <          lineRenderer.positionCount;          i+          +          )          {          10          +          =          i          *          0.001          f          ;          y          =          amplitude          *          (Mathf.Sin(k          *          10          +          w          *          Time.time)          +          Mathf.Sin(thousand          *          ten          -          w          *          Time.time)          )          ;          lineRenderer.SetPosition(i,          new          Vector3(x,          y,          0          )          +          startPoint)          ;          }          }        

Drawing Bézier Curves

Bézier curves are parametric curves that are used to create smooth curved shapes. They are widely used in estimator graphics. In this section, we are going to meet how we tin draw Bézier curves.

When a Bézier bend is controlled by 3 points, and then it is called Quadratic Bézier Curve(the offset equation beneath) and when information technology is controlled by four points, it is called Cubic Bézier Curve.

The post-obit script volition draw a quadratic Bézier curve using positions p0, p1, and p2. You should create three game objects and assign these objects to corresponding variables in the script to modify the shape of the curve in real-fourth dimension.

          using          Arrangement.Collections;          using          System.Collections.Generic;          using          UnityEngine;          public          class          BezierScript          :          MonoBehaviour          {          private          LineRenderer lineRenderer;          public          Transform p0;          public          Transform p1;          public          Transform p2;          void          Start(          )          {          lineRenderer          =          GetComponent<LineRenderer>          (          )          ;          }          void          Update(          )          {          DrawQuadraticBezierCurve(p0.position,          p1.position,          p2.position)          ;          }          void          DrawQuadraticBezierCurve(Vector3 point0,          Vector3 point1,          Vector3 point2)          {          lineRenderer.positionCount          =          200          ;          float          t          =          0f;          Vector3 B          =          new          Vector3(          0          ,          0          ,          0          )          ;          for          (          int          i          =          0          ;          i          <          lineRenderer.positionCount;          i+          +          )          {          B          =          (          1          -          t)          *          (          ane          -          t)          *          point0          +          2          *          (          i          -          t)          *          t          *          point1          +          t          *          t          *          point2;          lineRenderer.SetPosition(i,          B)          ;          t          +          =          (          1          /          (          float          )lineRenderer.positionCount)          ;          }          }          }        
A quadratic Bezier curve which is rendered using line renderer in Unity3D by C# script

Also, the following method draws a cubic Bézier curve. This fourth dimension we need iv points.

          void          DrawCubicBezierCurve(Vector3 point0,          Vector3 point1,          Vector3 point2,          Vector3 point3)          {          lineRenderer.positionCount          =          200          ;          float          t          =          0f;          Vector3 B          =          new          Vector3(          0          ,          0          ,          0          )          ;          for          (          int          i          =          0          ;          i          <          lineRenderer.positionCount;          i+          +          )          {          B          =          (          ane          -          t)          *          (          1          -          t)          *          (          1          -          t)          *          point0          +          3          *          (          i          -          t)          *          (          1          -          t)          *          t          *          point1          +          3          *          (          1          -          t)          *          t          *          t          *          point2          +          t          *          t          *          t          *          point3;          lineRenderer.SetPosition(i,          B)          ;          t          +          =          (          1          /          (          float          )lineRenderer.positionCount)          ;          }          }        
A cubic Bezier Curve which is rendered using line renderer in Unity3D by C# script

Costless Drawing using Line Renderer

In this department, we are going to see how we can draw freely using the mouse position. We tin do this by creating a new game object with a line renderer fastened. When nosotros press the left mouse button, a new game object is created and each frame the position of the mouse added to the line renderer.

Drawing freely using line renderer in Unity3D

First of all, nosotros need a prefab to create a new game object when nosotros press the left mouse button. This is an empty game object with a line renderer component attached. In addition to this, do not forget to assign a material to the line renderer component. Create a prefab from this game object.

Second, create an empty game object and attach the post-obit script DrawManager.

          using          System.Collections;          using          Organization.Collections.Generic;          using          UnityEngine;          public          class          DrawManager:          MonoBehaviour          {          private          LineRenderer lineRenderer;          public          GameObject drawingPrefab;          void          Update(          )          {          if          (Input.GetMouseButtonDown(          0          )          )          {          GameObject drawing          =          Instantiate(drawingPrefab)          ;          lineRenderer          =          drawing.GetComponent<LineRenderer>          (          )          ;          }          if          (Input.GetMouseButton(          0          )          )          {          FreeDraw(          )          ;          }          }          void          FreeDraw(          )          {          lineRenderer.startWidth          =          0.1          f          ;          lineRenderer.endWidth          =          0.one          f          ;          Vector3 mousePos          =          new          Vector3(Input.mousePosition.ten,          Input.mousePosition.y,          10f)          ;          lineRenderer.positionCount+          +          ;          lineRenderer.SetPosition(lineRenderer.positionCount          -          1          ,          Camera.master.ScreenToWorldPoint(mousePos)          )          ;          }          }        

When yous printing the left mouse button, a new game object is instantiated from the prefab which we created before. We get the line renderer component from this game object. Then while nosotros are pressing the left mouse button, we call FreeDraw() method.

In the FreeDraw method, we take ten and y components of the mouse position and set the z-position equally 10. Here, the mouse position is in the screen space coordinates. But nosotros use world space coordinates in line renderer. Therefore we need to catechumen mouse position to world infinite coordinates. In each frame, we also need to increase the number of points. Since we do not know how many points nosotros need, we cannot set position count earlier.

References
ane-https://docs.unity3d.com/ScriptReference/LineRenderer.html
two-http://www.theappguruz.com/blog/bezier-curve-in-games
three-https://en.wikipedia.org/wiki/Bézier_curve
four-https://en.wikipedia.org/wiki/Sine_wave

tinklenournst.blogspot.com

Source: https://www.codinblack.com/how-to-draw-lines-circles-or-anything-else-using-linerenderer/

0 Response to "How to Draw a Circle in Unity"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel