- Home /
Dynamically Created Edge Collider Woes
Hey all
I'm creating a 2D platformer with tile-based levels. Each tile is 6x6 units, square. I'm working on a script right now that detects neighboring tiles and only generates edge colliders for "open" edges. So if a tile is right next to another tile, they'll detect each other and only place edge colliders on the edges that aren't touching. Hopefully that makes sense. I've got the script to work to make the edge colliders by firing four raycasts (top, bottom, left, right) which collide against temporary boxcollider2D's attached to the tiles.
hitT = Physics2D.Raycast (new Vector2(transform.position.x, transform.position.y + 3.25f), transform.up, 0.25f, 1 << LayerMask.NameToLayer("Ground"));
if (hitT){}
else
{
EdgeCollider2D eCT = gameObject.AddComponent<EdgeCollider2D> ();
eCT.points = new Vector2[]
{
new Vector2(-3, 3),
new Vector2(3, 3)
};
eCT.sharedMaterial = Resources.Load ("Materials/Ground") as PhysicsMaterial2D;
}
This is the code just for the top edge collider, the other three are redundant. So this works fine in creating the edge colliders, but there seems to be something wrong with the physics on the tiles. The material "Ground" has 0 friction and 0 bounciness, so when my player contacts it with any motion at all he should just slide across it, however... he just sticks to it and can't move.
The issue is that the collider is behaving as though the physicsmaterial2d isn't loaded even though I can see it is in the inspector. Oddly enough, if I'm in play mode I can simply select the tiles that aren't working and reload the physics material and it will function fine. Is this a bug or am I simply not loading the material correctly?
EDIT: Found a workaround. Not sure why, but disabling and re-enabling the collider makes the change take effect. New code:
if (hitT){}
else
{
EdgeCollider2D eCT = gameObject.AddComponent<EdgeCollider2D> ();
eCT.points = new Vector2[]
{
new Vector2(-3, 3),
new Vector2(3, 3)
};
eCT.sharedMaterial = Resources.Load ("Materials/Ground") as PhysicsMaterial2D;
eCT.enabled = false;
eCT.enabled = true;
}
Hopefully this will help someone out.
Your answer
Follow this Question
Related Questions
physics materials not showing up? 1 Answer
How to be dynamically attached to the PolygonCollider2D in on iOS 1 Answer
[Answered] Level Complete? 1 Answer
Tile-based approach in Unity 1 Answer
Change gravity on button 1 Answer