Quantcast
Channel: Tutorials – Unity Coding – Unity3D
Viewing all articles
Browse latest Browse all 58

Drawing Lines

$
0
0

Hi dear reader!

In this tutorial we want to learn how to draw a line in unity by user mouse movement and interaction.

First we need a component that would be able to render simple lines.
Our choice is ​Line Renderer​, this component is able to renderer lines between given positions so we can pass mouse position and let it to render them.

Getting Started

  1. Create or Open an Empty scene
  2. Create a new Empty Game Object
  3. Create a new c# script and name it ​DrawLine ​then put the below script into it

Now, attach the ​DrawLine​ script to Created Empty Game Object and Play the game.
Press primary mouse button and move your mouse around screen, as you can see the line goes to draw lines in your mouse position.

 

Explanation

In the script we first check the mouse primary button is pressed or not, when it is pressed we go to next step and try to get the mouse position in world space. After that we try to check if the mouse position isn’t exists in the line points, if the point doesn’t exists then we increase the line positions count and then we add mouse position to line positions and all done.

In the next tutorial we will try to use the line drawing in 2d mode and add a collider to the line.

 

Resources

This code mainly gathered from a gist and also is available in Unity Library

Thanks for reading.

 

Source Code


Viewing all articles
Browse latest Browse all 58

Trending Articles