Draw a Circle and Line Game

Draw a curve using linerenderer

Sometimes, y'all need to describe lines, circles or curves in your Unity games. In these cases, you tin can use Unity'southward LineRenderer class. In this tutorial, we will encounter how we can draw lines, polygons, circles, wave functions, Bézier Curves. And also we will see how we can practice a free cartoon using Line Renderer in Unity3D. In order to see our other Unity tutorials, click here.

Line Renderer Component

To draw a line we take to add together a LineRenderer component to a game object. Even if this component can be attached to any game object, I suggest you create an empty game object and add the LineRenderer to this object.

We need a textile which volition be assigned to LineRenderer. To do this create a material for the line in Projection Tab. Unlit/Color shader is suitable for this material.

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, you can alter the number of points and positions of points. If yous enter 2 different points, you lot will get a straight line. You tin besides modify the width of the line in the section below.

A straight line which is rendered using line renderer in Unity3D

Likewise, two draw a triangle, you need 3 points and to describe a rectangle you demand 4 points. Allow's depict a rectangle as an example.

To draw a rectangle, we need to set positions of iv points. We too accept to check the Loop toggle to obtain a airtight shape.

A square which is rendered using line renderer in Unity3D

Drawing Lines From C# Script

If nosotros want to draw or control lines in real-time, we need to create a C# script. To draw lines from a script, we decide the size of position array and coordinates of positions in C# script. Therefore, LineRenderer tin can connect the points.

Let'southward draw a triangle using a script equally an example. Outset, create a script with the proper name "DrawScript". And adhere this script to a game object which already has a LineRenderer component.

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

This script will describe a triangle. Notation that nosotros already prepare the line width to 0.1 and checked the loop toggle, earlier. Therefore the same setting is also valid hither.

A triange which is rendered using line renderer in Unity3D

We can also modify the line width from the script using startWidth and endWidth. In addition to this, if yous would like to change line width by position, you can set dissimilar values to them. In this case, Line Renderer will interpolate the line width according to position.

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

Drawing Regular Polygons and Circles

In this section, we are going to see how we tin can write a method that draws regular polygons. Since circles are due north-gons which has big due north, our function will exist useful for circles also. Simply first, allow me explain the mathematics backside information technology.

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

Rotation matrices

And so nosotros demand 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.

Equally you probably know, in society to rotate a point effectually an axis, we multiply the position vector of the point with the rotation matrix. Rotation matrices for rotations around ten, y and z axes are given on the right.

For example, when we want to rotate a betoken past ninety degrees around the z-axis, which has a coordinate (1,0,0), we multiply the position vector past a rotation matrix.

Rotating a point around z-axis

We need to construct a rotation matrix to rotate each vertex around the z-axis. Allow's me write our DrawPolygon method starting time and explain information technology.

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

You may wonder why the constructed rotation matrix is iv×4. In reckoner graphics, the 3-dimensional world is represented as 4-dimensional merely this topic is not related to our business here. We just use information technology as if information technology is iii-dimensional.

We gear up the position of initial vertex and rotate it using rotationMatrix each time and add the center position to it.

The following image is an case of a hexagon which is drawn by this method.

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

If you increase 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, we 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 post-obit:

Sine wave functions

where

Wave number

Hither, 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 will not worry about the stage angle in our discussions.

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

In social club to draw a stable sinusoidal wave, we tin drop the fourth dimension part. The following method volition draw a sine wave.

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

Our DrawSineWave method takes three parameters. They are startPoint which is for setting the start position in earth space, 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 role, outset, we determine the positions on the x-axis. For each x, we take to summate the y-position.

To animate this wave, we have to implement time to our part as follows:

          void          DrawTravellingSineWave(Vector3 startPoint,          bladder          amplitude,          float          wavelength,          float          waveSpeed)          {          float          x          =          0f;          float          y;          bladder          1000          =          2          *          Mathf.PI          /          wavelength;          float          w          =          k          *          waveSpeed;          lineRenderer.positionCount          =          200          ;          for          (          int          i          =          0          ;          i          <          lineRenderer.positionCount;          i+          +          )          {          ten          +          =          i          *          0.001          f          ;          y          =          aamplitude          *          Mathf.Sin(k          *          x          +          westward          *          Time.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 quaternary parameter is to set the wave speed. This wave travels to the left since we used plus sign in the function. If nosotros would like to create a wave that travels to the right, we have to apply the minus sign. You should go on in listen that we have to write this method in Update().

To create a standing wave, we have to add ii waves which travel to the right and which travel to left.

          void          DrawStandingSineWave(Vector3 startPoint,          float          amplitude,          float          wavelength,          float          waveSpeed)          {          float          ten          =          0f;          bladder          y;          float          g          =          2          *          Mathf.PI          /          wavelength;          float          westward          =          g          *          waveSpeed;          lineRenderer.positionCount          =          200          ;          for          (          int          i          =          0          ;          i          <          lineRenderer.positionCount;          i+          +          )          {          10          +          =          i          *          0.001          f          ;          y          =          amplitude          *          (Mathf.Sin(chiliad          *          x          +          w          *          Time.time)          +          Mathf.Sin(k          *          x          -          west          *          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 computer graphics. In this section, we are going to run into how nosotros tin draw Bézier curves.

When a Bézier curve is controlled by 3 points, then it is called Quadratic Bézier Bend(the first equation beneath) and when it is controlled past 4 points, it is called Cubic Bézier Curve.

The following script will 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 change the shape of the bend in existent-fourth dimension.

          using          System.Collections;          using          Arrangement.Collections.Generic;          using          UnityEngine;          public          grade          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          *          (          1          -          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 time nosotros need 4 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          =          (          1          -          t)          *          (          1          -          t)          *          (          1          -          t)          *          point0          +          3          *          (          1          -          t)          *          (          1          -          t)          *          t          *          point1          +          iii          *          (          i          -          t)          *          t          *          t          *          point2          +          t          *          t          *          t          *          point3;          lineRenderer.SetPosition(i,          B)          ;          t          +          =          (          ane          /          (          bladder          )lineRenderer.positionCount)          ;          }          }        
A cubic Bezier Curve which is rendered using line renderer in Unity3D by C# script

Free Cartoon using Line Renderer

In this department, we are going to see how we can draw freely using the mouse position. We can practice this by creating a new game object with a line renderer attached. When we press the left mouse push, 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, we need a prefab to create a new game object when we press the left mouse push button. This is an empty game object with a line renderer component attached. In addition to this, practice not forget to assign a textile to the line renderer component. Create a prefab from this game object.

2d, create an empty game object and attach the following script DrawManager.

          using          System.Collections;          using          Organisation.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.i          f          ;          lineRenderer.endWidth          =          0.ane          f          ;          Vector3 mousePos          =          new          Vector3(Input.mousePosition.10,          Input.mousePosition.y,          10f)          ;          lineRenderer.positionCount+          +          ;          lineRenderer.SetPosition(lineRenderer.positionCount          -          1          ,          Camera.main.ScreenToWorldPoint(mousePos)          )          ;          }          }        

When y'all 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. And then while we are pressing the left mouse push button, we call FreeDraw() method.

In the FreeDraw method, we accept x and y components of the mouse position and set the z-position as x. Here, the mouse position is in the screen space coordinates. But nosotros use world space coordinates in line renderer. Therefore nosotros need to convert mouse position to globe space coordinates. In each frame, we also demand to increase the number of points. Since we practice not know how many points nosotros demand, we cannot fix position count before.

References
ane-https://docs.unity3d.com/ScriptReference/LineRenderer.html
ii-http://www.theappguruz.com/blog/bezier-bend-in-games
3-https://en.wikipedia.org/wiki/Bézier_curve
4-https://en.wikipedia.org/wiki/Sine_wave

hicksthengs.blogspot.com

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

0 Response to "Draw a Circle and Line Game"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel