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.

 


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DrawLine2D : MonoBehaviour
{
[SerializeField]
protected LineRenderer m_LineRenderer;
[SerializeField]
protected bool m_AddCollider = false;
[SerializeField]
protected EdgeCollider2D m_EdgeCollider2D;
[SerializeField]
protected Camera m_Camera;
protected List<Vector2> m_Points;
public virtual LineRenderer lineRenderer
{
get
{
return m_LineRenderer;
}
}
public virtual bool addCollider
{
get
{
return m_AddCollider;
}
}
public virtual EdgeCollider2D edgeCollider2D
{
get
{
return m_EdgeCollider2D;
}
}
public virtual List<Vector2> points
{
get
{
return m_Points;
}
}
protected virtual void Awake ()
{
if ( m_LineRenderer == null )
{
Debug.LogWarning ( "DrawLine: Line Renderer not assigned, Adding and Using default Line Renderer." );
CreateDefaultLineRenderer ();
}
if ( m_EdgeCollider2D == null && m_AddCollider )
{
Debug.LogWarning ( "DrawLine: Edge Collider 2D not assigned, Adding and Using default Edge Collider 2D." );
CreateDefaultEdgeCollider2D ();
}
if ( m_Camera == null ) {
m_Camera = Camera.main;
}
m_Points = new List<Vector2> ();
}
protected virtual void Update ()
{
if ( Input.GetMouseButtonDown ( 0 ) )
{
Reset ();
}
if ( Input.GetMouseButton ( 0 ) )
{
Vector2 mousePosition = m_Camera.ScreenToWorldPoint ( Input.mousePosition );
if ( !m_Points.Contains ( mousePosition ) )
{
m_Points.Add ( mousePosition );
m_LineRenderer.positionCount = m_Points.Count;
m_LineRenderer.SetPosition ( m_LineRenderer.positionCount – 1, mousePosition );
if ( m_EdgeCollider2D != null && m_AddCollider && m_Points.Count > 1 )
{
m_EdgeCollider2D.points = m_Points.ToArray ();
}
}
}
}
protected virtual void Reset ()
{
if ( m_LineRenderer != null )
{
m_LineRenderer.positionCount = 0;
}
if ( m_Points != null )
{
m_Points.Clear ();
}
if ( m_EdgeCollider2D != null && m_AddCollider )
{
m_EdgeCollider2D.Reset ();
}
}
protected virtual void CreateDefaultLineRenderer ()
{
m_LineRenderer = gameObject.AddComponent<LineRenderer> ();
m_LineRenderer.positionCount = 0;
m_LineRenderer.material = new Material ( Shader.Find ( "Particles/Additive" ) );
m_LineRenderer.startColor = Color.white;
m_LineRenderer.endColor = Color.white;
m_LineRenderer.startWidth = 0.2f;
m_LineRenderer.endWidth = 0.2f;
m_LineRenderer.useWorldSpace = true;
}
protected virtual void CreateDefaultEdgeCollider2D ()
{
m_EdgeCollider2D = gameObject.AddComponent<EdgeCollider2D> ();
}
}

view raw

DrawLine2D.cs

hosted with ❤ by GitHub


18 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.

  • I’m really really thanks to you, sir.
    i had looking for this for some time.
    it’s really helpful !!!

  • I’m really really thanks to you, sir.
    but can you add gravity to the line

    • Hi, I haven’t tried Rigidbody on it, but it should worth the try and I guess it should work fine with a Rigidbody.
      – Try to add a 2D rigid body and all the physics stuff would be done.
      Thanks.

      • I tried with 2D rigid body but it’s not working so How can I draw the Line the line have physics and it fall down after draw?

  • Hi ! You made a great work. Thanks a lot ;D

  • DOES IT WORK ON ANDROID?

  • It doesn’t work, it draws the line, but without the collider

  • its not work on android why?

  • how to create line with gravity?

    • add RigidBody2D component to it

  • Hi thanks ! I draw a line with linerenderer so i want to detect collision gameobject and stop line drawing. How can i do ?

    • Just wanted to state that this was addressed in the email, you can just use a Raycast before drawing the line and once it hits a collider, stop drawing.

Leave a comment

Connect

Twitter View LinkedIn profile Youtube Github Join Discord Twitch Instagram BlueSky

UnityLauncherPro

Get UnityLauncherPRO and work faster with Unity Projects!
*free unity hub alternative

@unitycoder_com

Subscribe to Blog via Email

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