The Innards of a Rotation Function

爱⌒轻易说出口 提交于 2020-01-05 08:42:37

问题


I'm looking for information on what goes on in a rotation function that modifies a 2d matrix. I found this, but assigning the rotation to 90, 180, or 270 renders no change. Here's my code:

Matrix.prototype.rotate = function(deg) {
    var radians = deg * Math.PI / 180,
        sin = Math.sin(radians),
        cos = Math.cos(radians),
        a = this.a,
        b = this.b,
        c = this.c,
        d = this.d,
        tx = this.tx,
        ty = this.ty;

    this.a = a*cos - b*sin;
    this.b = a*sin + b*cos;
    this.c = c*cos - d*sin;
    this.d = c*sin + d*cos;
    this.tx = tx*cos - ty*sin;
    this.ty = tx*sin + ty*cos;
}

I did manage to find some info on why it doesn't work, but nothing on how to fix it. From what I understand, rotating by 90 degrees causes sin and/or cos to be such a small number, that when applied to the matrix, it doesn't change anything. Please let me know if I'm wrong about this.

To get it to work I added this to the beginning of the function:

if(!(deg % 90)) {
    deg -= .0001;
}

It works, but I'm sure after rotating several thousands times it isn't going to be very accurate. Does anyone know of a better solution?

The actual rotation value is stored elsewhere and only passes the difference to the function, if that helps.

Edit : I forgot to mention that nothing happens when sin or cos equals 1 or -1 either.


回答1:


Not sure what your a, b, c and d are used for, but whenever possible you should keep all the original values and use the absolute angle to compute the rotated values. Otherwise, as you mentioned as well, the summation of inaccuracies will become more and more obvious.

I would get rid of the -= 0.001 hack, at 90 degrees, sin should be 1 and cos should be 0 (or at least very close to it), effecting the following transformation:

a' := -b
b' := a
c' := -d
d' := c
tx' := -ty
ty' := tx


来源:https://stackoverflow.com/questions/12049003/the-innards-of-a-rotation-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!