I am creating a 2D game in which a ball rolls on a line drawn by the user. I tried to create the line and the colliders in the same time, but the collision is applying only in points, not between them. The ball gets stuck in this space or just goes through the line. I know there is a way to create a collider with the dimension between the points, but I am a beginner and I have problems with the syntax.
Here is the code that creates the line and some colliders:
void Update()
{
if (Input.GetMouseButtonDown(0))
{
createLine();
isMousePressed = true;
line.SetVertexCount(0);
pointsList.RemoveRange(0, pointsList.Count);
line.SetColors(startColor, endColor);
}
// Drawing line when mouse is moving(presses)
if (isMousePressed)
{
mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mousePos.z = 0;
if (!pointsList.Contains(mousePos))
{
pointsList.Add(mousePos);
line.SetVertexCount(pointsList.Count);
line.SetPosition(pointsList.Count - 1, (Vector3)pointsList[pointsList.Count - 1]);
if (pointsList.Count > 2)
{
Vector3 l = pointsList[pointsList.Count - 2];
Vector3 k = pointsList[pointsList.Count - 1];
print(Vector3.Distance(k, l));
if (k != l)
{
GameObject colliderKeeper = new GameObject("collider");
BoxCollider2D bc = colliderKeeper.AddComponent<BoxCollider2D>();
colliderKeeper.transform.position = Vector3.Lerp(k, l, 0.5f);
colliderKeeper.transform.LookAt(k);
bc.size = new Vector3(0.1f ,0.1f, Vector3.Distance(k, l));
}
}
}
}
if (Input.GetMouseButtonUp(0))
{
lines.Add(line);
Ray mouseRay = Camera.main.ScreenPointToRay(Input.mousePosition);
Vector3 newDotPosition = mouseRay.origin - mouseRay.direction / mouseRay.direction.y * mouseRay.origin.y;
isMousePressed = false;
}
}
Any help is appreciated.