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

Drawing 2D lines and Adding Collider to it

$
0
0

Hi awesome reader!

In our past tutorial “How to Draw Line” we discussed about drawing a line in the game by mouse
interaction. But sometimes we need to draw a line that collides with our game objects in 2D mode.
So we need to add physics to our line drawing system, then we are going to learn you how to do it.

Getting Started
– Create or Open an Empty Scene
– Change Camera projection to Orthographic, otherwise it won’t work.
– Create a Game Object with Physics Enabled (Add Sprite, Collider and Rigidbody2D)
– Create a new Empty Game Object.
– Create a new C# script called DrawLine2D ​and put the below content in it:

Now attach the DrawLine2D ​script to the 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. (Don’t let the ball to fall)

 

Explanation
In the code we first draw the line using mouse movement positions then we add the
positions to the LineRenderer component, then when the points added to LineRenderer, we use
the points to Setup EdgeCollider2D points, so the ball will collide with the line as you can see in
the above.

Try to make a game with this awesome line drawing script!

Resources
The above code mainly gathered from these sources:
https://gist.github.com/EmpireWorld/fcd12ca23cb6cb5dee69b6dc093d6dd5
https://github.com/UnityCommunity/UnityLibrary
Thanks for reading.

 


Viewing all articles
Browse latest Browse all 58

Trending Articles