- Home /
How to create a collider between 2 points in a 2d game?
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.
@Scroodge$$anonymous$$ Could you help me please? I know you made some code that looks approximately the same.
Answer by GarretLawrence · Jan 27, 2017 at 12:12 AM
There is EdgeCollider component that can solve your problem.
I made a simple demo, you can check it
You can move the anchors in scene mode while game is running to see the collider change.
Thanks a lot! I understood how EdgeColiider works from your code and now I can use it.
Your answer
Follow this Question
Related Questions
How can you change a colliders shape on collision with another collider? 1 Answer
Why is there a gap between my player and the wall during wall slide? SOLVED 2 Answers
OnTriggerEnter2D not working 2 Answers
Use transform.position in FixedUpdate to ensure collision with objects which have Velocity 0 Answers
Button above Collider is being ignored when clicked. 0 Answers