I am getting kind of headache… I am using jsbox2d.js for a 2d game, based on SVG graphics. I would like to »connect« a b2d-body to an svg element, what already works for the debug draw, but not for the graphics in the scene.
setup:
there is an SVG, including an arbitrary deeply nested structure of groups and shapes. Each one my have some transformations, so each element resides in its own coordinate space.
aside there is a box2d simulation and some bodies represent an element in the svg.
I would like to apply the b2body's transform to the svg-element it represents, so that the animation looks correctly. It is already working for the debug draw, where I am using this code:
// links is an array like [[b2body, svgelement],…]
for (var i = 0; i < links.length; i++) {
var t = links[i][0].GetTransform();
//tiny helper function just taking the values and
//setting it to the element
// transform(element, a,b,c,d,e,f)
//|a c e|
//|b d f|
svghelper.transform(links[i][1],
t.q.c, t.q.s, -t.q.s,
t.q.c, t.p.x, t.p.y);
}
The main difference is, that the elements used for the debug draw are generated on the fly, without any transformations, using the world coordinates of the vertices of the b2dShapes.
But the Graphics for the scene are taken from an SVG graphic created with inkscape and, f.i. using groups for an arm or the head of the charackter.
How can I apply the transform of the body right on the elements? I guess I need to change the basis of the transform matrix, but I somehow can't make it work.
I have tried this:
var t = body.GetTransform(),
mtr = svg,createSVGMatrix(
t.q.c, t.q.s, -t.q.s,
t.q.c, t.p.x, t.p.y),
toElement = element.getTransformToElement(element.ownerSVGDocument),
toElement_inv = toElement.invert();
mtr = mtr.multiply(toElement);
mtr = toElement_inv.multiply(mtr);
//applying the result
But that resulted in a wrong result and errors by inverting the matrix.
Thanks in ahead!
getTransformToElement
takes anElement
argument, not aDocument
.SVGMatrix
has aninverse()
method, notinvert()
. Have you tried simply adding the transform matrix as an attribute? E.gelement.setAttribute("transform", "matrix(" + t.q.c + " " + t.q.s + " " + (-t.q.s) + " " + t.q.c + " " + t.p.c + t.p.y + " " + ")");
? – Erik Dahlström