This project has moved and is read-only. For the latest updates, please go here.

[Solved] Anyone....How to Dynamically Change/Delete Shape attached to a Fixture

Topics: User Forum
Aug 1, 2012 at 7:45 AM

Hi, Could someone please help me with issue I am having. I have a game sprite that on collision would like to make it smaller, thus needing to remove the current Shape attached to the body and adding a new Shape.

Is there a way to do that without destroying Fixture attached to an existing body.

Aug 2, 2012 at 7:49 AM

Anyone ??? Please chime in.

I destroyed fixture and added a new one, but there are so many variables that I have to re-assign to newly created fixture, plus it also destroys the OnCollision & OnSeparation events....


Any better way of handling this better?

Aug 7, 2012 at 2:45 AM

A fixture is just the binding between the body and shape. I would recommend that you remove the fixture and add a new one instead. There is actually a Fixture.Clone(Body) method that clones all the properties of a fixture onto a new Body. It does not clone events.

The only other way of doing it is to manipulate the vertices of a polygonshape directly on collision:

private bool Rectangle_OnCollision(Fixture fixtureA, Fixture fixtureB, Contact contact)
    PolygonShape shape = (PolygonShape) fixtureA.Shape;

    return true;

This is not recommended for various reasons, but it is possible. In your case, you could do something like this:

private Vector2 _scale = new Vector2(0.5f, 0.5f);
private bool Rectangle_OnCollision(Fixture fixtureA, Fixture fixtureB, Contact contact)
	PolygonShape shape = (PolygonShape)fixtureA.Shape;
	shape.Vertices.Scale(ref _scale);
	return true;
That would scale the polygon to 50% size each time it collides with something. Watch out that too small polygons will cause problems with the engine.

Aug 7, 2012 at 6:27 AM

@Genbox - Thank you sir for the feedback. What I ended up doing was copying the initialization of properties again in my Update() method and subscribing to the OnCollision(....) and OnSeparation events again.

I'll give Body.Clone(body) a try next time.

Could you advise when to use Body.Clone(...) vs Body.DeepClone(...), they both look similar to me. I'm just not sure if one does a deep copy while the other does a shallow copy.

Aug 7, 2012 at 9:32 PM

You are correct. One does deep, one does shallow.

The DeepClone() makes a perfect copy together with a shape and fixture. Clone() just takes the properties of the body.

They are not perfect - let me know if you have any problems with them.