Cannot change edge colliders' points in Unity

Viewed 956

I am making a small game to learn Unity.

In the game, the character can slide. He has a EdgeCollider2D normally. When he slides, I would like the EdgeCollider2D to shrink to fit the character model as he is sliding.

I am currently trying to do this as shown below:

public void ChangeColliderForSlide()
{
    //used in animator behavior script
    edge2d.points.SetValue(new Vector2(-0.35f, -0.15f), 0);
    edge2d.points.SetValue(new Vector2(-0.35f, -0.55f), 1);
    edge2d.points.SetValue(new Vector2(0.4f, -0.55f), 2);
    edge2d.points.SetValue(new Vector2(0.4f, -0.15f), 3);
    edge2d.points.SetValue(new Vector2(-0.35f, -0.15f), 4);
}

This would shrink the collider and should be called as the player enter the slide animation, however, as I pause the game and check, the character's collider was not changed at all, and has the original values.

Would appreciate anyone who has an idea of what might be the problem here.

Thanks.

2 Answers

Note that you need to set correct amount of points in inspector first, or just reinitialize array like points = new Vector2[5]

    public void ChangeColliderForSlide()
    {
        //used in animator behavior script
        Vector2[] points = edge2d.points;

        points.SetValue(new Vector2(-0.35f, -0.15f), 0);
        points.SetValue(new Vector2(-0.35f, -0.55f), 1);
        points.SetValue(new Vector2(0.4f, -0.55f), 2);
        points.SetValue(new Vector2(0.4f, -0.15f), 3);
        points.SetValue(new Vector2(-0.35f, -0.15f), 4);

        edge2d.points = points;
    }

edge is ok

but the EdgeCollider2D is not

I just try a few options to fix this issue but edgeCollider is not working that i expect

 Vector2[] rr = new Vector2[2];   
           rr[0] = line.GetPosition(0);
           rr[1] = line.GetPosition(1);
 GetComponent<EdgeCollider2D>().points = rr;

OR

tempFingerPos = Camera.main.ScreenToWorldPoint(new Vector3( Input.mousePosition.x,Input.mousePosition.y,10f));

        line.SetPosition(line.positionCount - 1, tempFingerPos);
        pos.Clear();

        pos.Add(startPos);

      
        pos.Add ( tempFingerPos);

GetComponent().points = pos.ToArray();

Related