I’m trying to make a game where users have to trace alphabets. Alphabets are made of colliders. I cast a ray to see if there is a collider and then start drawing using the LineRenderer. But the problem I am facing is that LineRenderer even draws where there are no colliders (as seen in the image). I wish to draw only where there is a collider but can’t seem to figure it out.
My script for detecting colliders and enabling drawing script, “Tracer.cs”:
using UnityEngine;
using UnityEngine.SceneManagement;
using System.IO;
using System.Collections.Generic;
public class Tracer : MonoBehaviour
{
public PolygonCollider2D[] tracepoints;
private int index;
private int checkLevel;
private bool firstTime;
void Start()
{
index = 0;
checkLevel = tracepoints.Length;
firstTime = true;
}
void Update()
{
if (firstTime)
{
EnableScripts(true);
}
if (Input.GetMouseButton(0))
{
Camera cam = Camera.main;
//Raycast depends on camera projection mode
Vector2 origin = Vector2.zero;
Vector2 dir = Vector2.zero;
if (cam.orthographic)
{
origin = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
else
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
origin = ray.origin;
dir = ray.direction;
}
RaycastHit2D hit = Physics2D.Raycast(origin, dir);
//Check if we hit anything
if (hit)
{
EnableScripts(true);
if (hit.collider.name == tracepoints[index].name)
{
firstTime = false;
index++;
}
if (index == checkLevel)
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
}
}
else
{
EnableScripts(false);
}
}
}
private void EnableScripts(bool value)
{
GameObject.Find("Main Camera").GetComponent<DrawDot>().enabled = value;
GameObject.Find("Main Camera").GetComponent<DrawLine>().enabled = value;
}
}
The code for “DrawLine.cs”. I believe the issue is in this file:
using UnityEngine;
public class DrawLine : MonoBehaviour
{
public GameObject currentLineRenderer;
public GameObject lineRendererPrefab;
private bool clickStarted = false;
private int numOfPoints;
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
TouchPhaseHandle();
clickStarted = true;
}
else if (clickStarted)
{
TouchPhaseHandle();
}
if (Input.GetMouseButtonUp(0))
{
clickStarted = false;
currentLineRenderer = null;
numOfPoints = 0;
}
}
private void TouchPhaseHandle()
{
if (currentLineRenderer == null)
{
currentLineRenderer = Instantiate(lineRendererPrefab) as GameObject;
GameObject lines = GameObject.Find("lines");
currentLineRenderer.transform.parent = lines.transform;
}
numOfPoints++;
Vector3 mousePos = Input.mousePosition;
Vector3 temp = new Vector3(mousePos.x, mousePos.y, -5 - Camera.main.transform.position.z);
Vector3 wantedPos = Camera.main.ScreenToWorldPoint(temp);
LineRenderer newLineRenderer = currentLineRenderer.GetComponent<LineRenderer>();
newLineRenderer.positionCount = numOfPoints;
newLineRenderer.SetPosition(numOfPoints - 1, wantedPos);
}
}

