简体   繁体   English

Libgdx的Matrix4#translate()无法正常工作

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

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. 我试图使用变换矩阵绘制NinePatch以便可以缩放,旋转,移动等。因此,我创建了一个继承自LibGDX的NinePatch类的类,该类负责该矩阵。

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 : 以及我如何呈现自定义NinePatch类:

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 情况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 这是我渲染4个9个色块时得到的结果:位置= 0,0 /原点= 0,0 /比例= 0.002 /旋转=每个9个色块均不同

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 现在相同的四个九个面片具有:位置= 0,0 /原点= 0.5,0.5 /比例=相同/旋转=相同

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. 您可以看到我的9个色块不是在0,0(它们的位置)绘制的,而是在0.5,0.5(它们的原点) .translate(-originX, -originY, 0)在计算变换矩阵时没有.translate(-originX, -originY, 0) 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? 那么,为什么显然没有考虑我的第二次翻译?

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. 由于它还会缩小转换,因此您的第二个转换实际上会转换(-originX*scale, -originY*scale, 0)因为scale = 0.002,看来根本没有任何转换。 For instance for the x coordinate, you compute : 例如,对于x坐标,您可以计算:

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

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 : 我不得不更改计算转换矩阵的代码,以按照Guillaume G的指示进行转换时要考虑缩放比例,但我的代码与他的代码不同:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM