Question

Can anybody know what's the problem of my formula when getting corners of my rotated square. It seems right when I rotate my square from 1 to 10 degrees, but when you gave it 10 plus rotation I get wrong corners position.

This code is from my getCorners() method of my Square class:

var hx = 0,
    hy = 0;

hx = hy = this.size / 2;

var cos = Math.cos(this.rotation * Math.PI / 180),
    sin = Math.sin(this.rotation * Math.PI / 180);                      

var corners = {
      a: { x: this.x - hx, y: this.y - hy },
      b: { x: this.x + hx, y: this.y - hy },
      c: { x: this.x + hx, y: this.y + hy },
      d: { x: this.x - hx, y: this.y + hy }
};

var tl = corners.a,
    tr = corners.b,
    br = corners.c,
    bl = corners.d;

corners.a.x = (tl.x - this.x) * cos - (tl.y - this.y) * sin + this.x;
corners.a.y = (tl.x - this.x) * sin + (tl.y - this.y) * cos + this.y;                                           

corners.b.x = (tr.x - this.x) * cos - (tr.y - this.y) * sin + this.x;
corners.b.y = (tr.x - this.x) * sin + (tr.y - this.y) * cos + this.y;                                                                   

corners.c.x = (br.x - this.x) * cos - (br.y - this.y) * sin + this.x;
corners.c.y = (br.x - this.x) * sin + (br.y - this.y) * cos + this.y;                                                                                           

corners.d.x = (bl.x - this.x) * cos - (bl.y - this.y) * sin + this.x;
corners.d.y = (bl.x - this.x) * sin + (bl.y - this.y) * cos + this.y;

For full source code and running program here's the link: http://jsfiddle.net/css3guy/8B2eT/

Was it helpful?

Solution

Your formula (rotation matrix) is correct but you are using reference values which means you are updating the values in the first part of the calculations and then the rest of the calculations uses that new value instead of the one you intend.

One way to fix this is to define your objects this way instead (just shown for one corner):

// clone the values instead of referencing them
var tl = {x:corners.a.x, y:corners.a.y},
    ...

// now you have a copy to work with here instead of accumulated updates
corners.a.x = (tl.x - this.x) * cos - (tl.y - this.y) * sin + this.x;
corners.a.y = (tl.x - this.x) * sin + (tl.y - this.y) * cos + this.y;

Modified fiddle (only one corner fixed)

I would strongly encourage though to refactor and use a common rotation/translation function instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top