Page 1 of 1

Transfer shape to different body

Posted: Sat Jun 18, 2016 9:50 am
by koro
Hi, this is my first post in the forum.
I'd like to know if it's possible to somehow "detach" a shape from a body it's attached to and re-attach it to a different body (everything done while the shapes and bodies are not added to any space).
The reason for wanting to do this is that I have bodies with several shapes that routinely get "broken" into single-shape bodies. To do this i'm just destroying and re-creating the shapes on separate bodies, but I think it would be much more efficient if I could re-use the existing shapes.

Thanks,
koro

Re: Transfer shape to different body

Posted: Sat Jun 18, 2016 1:52 pm
by slembcke
When you create a shape, you give it a body that it will be connected to. Adding it to the space is what makes it active. So to change the body of a shape, you first have to remove the shape from the space to deactivate it. Then you can call cpShapeSetBody() to change the shape, and add it back to the space to reactivate it.

As for efficiency, it should help a little, but don't expect much. Many implementations of malloc() have nice pools of memory that they work with and seem to be pretty thread friendly. Reusing memory will always be better, just maybe not as much of an improvement as it would have been 10 or 20 years ago.

Re: Transfer shape to different body

Posted: Sat Jun 18, 2016 3:03 pm
by koro
Thanks. I assume the local coordinates of the shape are kept exactly the same, right? Or are the global coordinates preserved instead?

For instance, if my body had two (poly)shapes attached, one to the left and one to the right of its center of gravity, and I want to create two new bodies with a single shape each (each shape having its centroid at the body center), I would first create my new bodies, position them at the centroid of each shape, and then use cpShapeSetBody. But I think if I do this the shapes will be off-center because their local coordinates were nonzero originally. Is that right?

If so, is there any function that will let me translate the shape without having to get its vertices, shift them them and re-creating the shape?

Re: Transfer shape to different body

Posted: Sun Jun 19, 2016 11:38 pm
by slembcke
Shape coordinates are always relative to the body they are attached to. It makes it easy to set shapes up initially (the base case), but unfortunately not for what you want.

You'll have to transform the shapes yourself. Chipmunk 7 does have transform matrices exposed through the public API, so it should make the process a bit easier.