Sep
23
2017

Drawing 2D lines and Adding Collider to it

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.

 


4 Comments + Add Comment

  • Thanks man, it really helpful tutorial good Work.
    hope you provide many more interesting tutorial 🙂

    • I’m so happy to hear it is useful for you.
      Give us some more tutorial ideas.
      Thanks.

      • How about google firebase + unity?
        Not a lot about that out there. And more and more games are using cloud services.

        And thanks for this tutorial, it’s fun, and code is written well so even a newb like me can understand it 🙂

        • Looks good idea, thanks for sharing, i will make a simple tutorial about it.
          Thanks.

Leave a comment

@unitycoder_com

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.