Libgdx's Matrix4#translate() doesn't work as expected

668 views Asked by At

I'm trying to draw a NinePatch using a transform matrix so it can be scaled, rotated, moved etc. So I created a class that inherits from LibGDX's NinePatch class and which is responsible of the matrix.

This is how I compute my transform matrix (I update it each time one of the following values changes) :

this.transform
    .idt()
    .translate(originX, originY, 0)
    .rotate(0, 0, 1, rotation)
    .scale(scale, scale, 1)
    .translate(-originX, -originY, 0)
;

and how I render my custom NinePatch class :

drawConfig.begin(Mode.BATCH);
this.oldTransform.set(drawConfig.getTransformMatrix());
drawConfig.setTransformMatrix(this.transform);
this.draw(drawConfig.getBatch(), this.x, this.y, this.width, this.height); // Libgdx's NinePatch#draw()
drawConfig.setTransformMatrix(this.oldTransform);

Case 1

Here's what I get when I render 4 nine patches with : Position = 0,0 / Origin = 0,0 / Scale = 0.002 / Rotation = different for each 9patch

I get what I expect to.

Case 2

Now the same 4 nine patches with : Position = 0,0 / Origin = 0.5,0.5 / Scale = same / Rotation = same

You can see that my 9 patches aren't draw at 0,0 (their position) but at 0.5,0.5 (their origin), like if I had no .translate(-originX, -originY, 0) when computing the transform matrix. Just to be sure, I commented this instruction and I indeed get the same result. So why is my 2nd translation apparently not taken into account?

2

There are 2 answers

0
Mickäel A. On BEST ANSWER

I had to change the code computing my transform matrix to take the scale into account when translating back as pointed by Guillaume G. except my code is different from his :

this.transform
    .idt()
    .translate(originX, originY, 0)
    .rotate(0, 0, 1, rotation)
    .scale(scale, scale, 1)
    .translate(-originX / scale, -originY / scale, 0);
;
1
Guillaume Gris On

The problem is probably your scaling. Because it also scales down the translation, your seccond translate actually translates (-originX*scale, -originY*scale, 0) since scale=0.002, it looks like there is no translate at all. For instance for the x coordinate, you compute :

x_final = originX + scale * (-originX + x_initial)