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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> (); | |
} | |
} |
Related Posts
18 Comments + Add Comment
Leave a comment
Recent posts
- MotionVector Effect: Object “disappears” when paused
- [GreaseMonkey] Unity Forum Fixer
- UnityHub: Make Hub application background Translucent
- Customize SpriteShapeRenderer quality (but has issues)
- Editor tool: Copy selected gameobject’s names into clipboard as rows (for Excel)
- Editor tool: Replace string in selected gameobject’s names
- UnityHub: Enable built-in Login Dialog (no more browser login/logout issues!)
- Use TikTok-TTS in Unity (with WebRequest)
- Create Scene Thumbnail Image using OnSceneSaved & OnPreviewGUI
- webgl+javascript TTS
- Using Moonsharp (LUA) + Unity Webgl
- Using 3D gameobject prefabs with Unity Tilemap + NavMesh Surface
Recent Comments
- [Asset Store] Point Cloud Viewer & Tools on
- [Asset Store] Point Cloud Viewer & Tools on
- Vector3 maths for dummies! on
- UnityHub: Make Hub application background Translucent on
- UnityHub: Make Hub application background Translucent on
- Install Android SDK+JDK+NDK for Unity (without AndroidStudio or Unity Hub) on
- Install Android SDK+JDK+NDK for Unity (without AndroidStudio or Unity Hub) on
- [Asset Store] Point Cloud Viewer & Tools on
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?
Of course, it does.
It doesn’t work, it draws the line, but without the collider
its not work on android why?
You might need to replace Input.GetMouseButton with Input.GetTouch:
https://docs.unity3d.com/ScriptReference/Input.GetTouch.html
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.