So I have two predetermined points and I want to draw a line between them.
I don't have an issue with actually drawing the line or snapping it to final position, but I want to lock it in between the two points while it's drawing. At the moment, it follows my touch's position in all directions.
Here's what it currently does:
Here's an approximation of what I'm trying to do (finger still on screen):
And here's how the line looks when it connects with the final point (finger has been lifted and line is still drawn):
public class Path : MonoBehaviour
{
[SerializeField] private Vector3[] positions;
[SerializeField] private GameObject child1, child2;
private Vector3 startPos, currentPos, endPos;
[SerializeField] private bool _firstChildSelected = false;
[SerializeField] private bool _secondChildSelected = false;
[SerializeField] private LineRenderer line;
Vector3 direction;
Touch touch;
// Start is called before the first frame update
void Start()
{
positions = new Vector3[4];
endPos = child2.transform.position;
}
// Update is called once per frame
void Update()
{
if (Input.touchCount > 0)
{
touch = Input.GetTouch(0);
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(touch.position), Vector2.zero);
if (touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Stationary)
{
if (hit)
{
// If it collides with the first checkpoint for the first time...
if (hit.transform.gameObject == child1 && !_firstChildSelected)
{
positions[0] = child1.transform.position;
line.SetPosition(0, positions[0]);
line.SetPosition(1, Camera.main.ScreenToWorldPoint(touch.position));
_firstChildSelected = true;
}
// If it collides with the second checkpoint for the first time, and already passed by the first one...
if (hit.transform.gameObject == child2 && _firstChildSelected && !_secondChildSelected)
{
_secondChildSelected = true;
}
}
// Follow the touch.position until it reached the final position...
else if (_firstChildSelected)
{
currentPos = Camera.main.ScreenToWorldPoint(touch.position) + new Vector3(0, 0, 10);
direction = (endPos - positions[0]).normalized;
line.SetPosition(1, currentPos);
}
// When both have been selected, lock the line in
if (_firstChildSelected == true && _secondChildSelected == true)
{
currentPos = child2.transform.position;
line.SetPosition(1, currentPos);
}
}
// Clear all on finger lift, but keep the line drawn
if (touch.phase == TouchPhase.Ended)
{
Array.Clear(positions, 0, positions.Length);
_firstChildSelected = false;
_secondChildSelected = false;
}
}
}
I know my code is messy, I'm kinda new to all this and I've been trying out some stuff. Any help would be appreciated!