1
\$\begingroup\$

I generated a procedural mesh using marching squares and the MeshFilter component (it's 2 dimensional). Now I got the point that I need do collision detection with the character (a sprite with a box collider).

I tried simply converting the mesh's vertices to Vector2s and putting it inside the collider the following way:

PolygonCollider2D collider = chunk.gameObject.AddComponent<PolygonCollider2D>();
List<Vector2> points = new List<Vector2>();

foreach (Vector2 vec in vertices)
{
    points.Add(vec);
}
collider.points = points.ToArray();

This almost worked, but it had some flaws in the collider:

flaw

Then I tried to use an EdgeCollider instead, but this made the character jitter. Lastly I tried to set each shape coming out of the marchingsquares algorithm be a separate path, but this was somehow very slow.

Is there any ways to create a good collider for a procedural surface?

Edit: Edge collider approach as requested (I got a bit further with it in the mean time):

So, to implement the edge collider, I changed my marching squares algorithm a bit, so it can output pure lines instead of actual triangles. The problem with this was that at some points, the character just randomly goes into the collider:

enter image description here

\$\endgroup\$
5
  • 1
    \$\begingroup\$ The EdgeCollider approach is probably your best bet for meshes that can be concave like this. Can you show us what your edge-based implementation looked like? We might be able to help you find & eliminate the character jitter bug that you describe. \$\endgroup\$
    – DMGregory
    Dec 20, 2016 at 23:42
  • \$\begingroup\$ @DMGregory Here you go \$\endgroup\$
    – Bálint
    Dec 21, 2016 at 0:05
  • 1
    \$\begingroup\$ That output looks reasonable, though it can be hard to tell on a gently sloping curve. Can you show us the code that's setting up the edge collider data (gathering only the boundary vertices of of the mesh), and maybe a rougher/sharper test case? Also, it looks like you might be breaking your mesh up into chunks - are you finding the bug occurs only at the connections between two chunks, or does it happen in the middle of a single collider too? \$\endgroup\$
    – DMGregory
    Dec 21, 2016 at 0:25
  • \$\begingroup\$ @DMGregory Sorry for the late reply, I was sleeping. That's the interesting part, no, whenever I checked I saw that this happens at part where the box collider is completely paralell to the edge (I froze the z rotation of the rigidbody, because I manually change that) \$\endgroup\$
    – Bálint
    Dec 21, 2016 at 10:04
  • \$\begingroup\$ Did you ever figure out an efficient solution? I'm also making an editable terrain using marching squares and can't figure out how to handle collisions efficiently (meshes can have holes) \$\endgroup\$ Apr 27, 2022 at 19:05

0

You must log in to answer this question.