Hi, this is my first time asking in the forum. I’ll try to be as clear as possible.
I am currently trying to make and finish my first game. I just started the project today so it only has one script. This script manages a LineRenderer, which creates multiple connected points every time the user clicks with the mouse button. This part of the script works fine.
Now I’m trying to apply walls to the game, so when creating those connected points, they can’t go throught walls. I’ve done it by using a RaycastHit2D and taking it’s point of impact, which works fine, except that after adding a new position to the LineRenderer, which position emerges from a RaycastHit2D, I can’t add points anywhere else than that certain point, so the player gets stucked.
Via debugging, I’ve come to the conclusion that this happens because when it does the Raycast, it detects instantly that there’s a collider from the starting position to wherever I aim with my mouse. I’ve tried to ignore that certain collider by storing it into a variable and then clearing it depending on the circumstances. This certainly works, but in my case it’s not what I need, because I’m going to build a map and the player might get out of it this way. Any ideas on how I can fix this issue?
Here’s my code:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
public class LineTracer : MonoBehaviour
{
public LineRenderer line;
public LineRenderer previewLine;
public Vector2 lastPoint
{
get
{
if (line == null) return Vector2.zero;
return line.GetPosition(line.positionCount - 1);
}
}
bool inPreview
{
get
{
return previewLine.enabled;
}
set
{
previewLine.enabled = value;
}
}
private void Start()
{
if(!TryGetComponent(out line))
{
line = gameObject.AddComponent<LineRenderer>();
}
line.positionCount = 1;
inPreview = true;
}
void Update()
{
Vector2 mousePosition = Input.mousePosition;
Vector3 worldPosition = Camera.main.ScreenToWorldPoint(mousePosition);
worldPosition.z = 0;
worldPosition = PositionHitCheck(lastPoint, worldPosition);
if (inPreview)
{
previewLine.positionCount = 2;
previewLine.SetPosition(0, lastPoint);
previewLine.SetPosition(1, worldPosition);
}
if (Input.GetMouseButtonDown(0) && inPreview)
{
StartCoroutine(PlaceLine(lastPoint, worldPosition));
}
}
private Vector3 PositionHitCheck(Vector2 origin, Vector2 target)
{
Vector2 direction = target - origin;
RaycastHit2D hit = Physics2D.Raycast(origin, direction, Vector2.Distance(origin, target), 1 << LayerMask.NameToLayer("LineBlock"));
if (hit.collider != null) return hit.point;
return target;
}
public event Action<Vector3, Vector3> onPlaceLine;
public IEnumerator PlaceLine(Vector3 start, Vector3 end)
{
onPlaceLine?.Invoke(start, end);
// Logic that will always be done no mather what.
inPreview = false;
line.positionCount++;
line.SetPosition(line.positionCount - 1, end);
inPreview = true;
yield return null;
}
}
Thanks!