Unity 2D Line Renderer | Unity Tutorial
In this video tutorial, we’ll dive into the Unity 2D Line Renderer component to help you create stunning visual effects and dynamic paths in your 2D game projects. We'll cover the basics of setting up the Line Renderer, customizing its appearance, and applying it to various scenarios such as drawing paths, creating trails, and visualizing gameplay elements.
WATCH FULL TUTORIAL ON YOUTUBE
=========================================================
Unity Projects - ON SALE!!!
1. Water Sort Puzzle 9000 Levels
2. Ball Sort Puzzle 9000 Levels
3. Sling Shot
=========================================================
Script:
MouseDraw.cs
using UnityEngine;
public class MouseDraw : MonoBehaviour
{
private LineRenderer lineRenderer;
private Vector3 previousPosition;
private bool isDrawing;
[SerializeField]
private float minDistance = 0.02f; // Smaller distance for smoother lines
private void Start()
{
lineRenderer = GetComponent<LineRenderer>();
lineRenderer.positionCount = 0; // Start with no points
isDrawing = false;
}
void Update()
{
if (Input.GetMouseButtonDown(0)) // Start drawing
{
isDrawing = true;
// Reset the line renderer
lineRenderer.positionCount = 0; // Clear previous line
previousPosition = GetMouseWorldPosition();
AddPoint(previousPosition);
}
else if (Input.GetMouseButtonUp(0)) // Stop drawing
{
isDrawing = false;
}
if (isDrawing)
{
Vector3 currentPosition = GetMouseWorldPosition();
if (Vector3.Distance(currentPosition, previousPosition) > minDistance)
{
AddPoint(currentPosition);
previousPosition = currentPosition;
}
}
}
// Convert mouse position to world position
private Vector3 GetMouseWorldPosition()
{
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mousePosition.z = 0; // Ensure z is 0 for 2D
return mousePosition;
}
// Add a new point to the line renderer
private void AddPoint(Vector3 position)
{
lineRenderer.positionCount++;
lineRenderer.SetPosition(lineRenderer.positionCount - 1, position);
}
}