Get Off My Lawn - 2 months ago 8

Javascript Question

I am trying to rotated 4 points around an origin. When I don't rotate the points, they show up in the correct location. I am doing that like this:

`let origin = this.transform.position;`

for (let i in this._pointsOrig) {

let point = this._pointsOrig[i];

this._points[i] = new Vector2(

point.x + origin.x,

point.y + origin.y

);

}

Which gives me this result:

When I attempt to rotate the rectangle, like this:

`// degrees is between 0 & 360, so convert to radians`

let rotation = this.transform.rotation.degrees * (Math.PI / 180);

let cos = Math.cos(rotation);

let sin = Math.sin(rotation);

let origin = this.transform.position;

for (let i in this._pointsOrig) {

let point = this._pointsOrig[i];

this._points[i] = new Vector2(

(cos * (point.x - origin.x)) + (sin * (point.y - origin.y)) + origin.x,

(cos * (point.y - origin.y)) - (sin * (point.x - origin.x)) + origin.y

);

}

I get this result where the rectangle is now on the bottom left.

I am not sure what I need to do so the points rotate around the origin.

Answer

I would try using

```
(cos * point.x) + (sin * point.y) + origin.x,
(cos * point.y) - (sin * point.x) + origin.y
```

It looks like the point.x and point.y are the values before shifting by (origin.x,origin.y). So shifting coordinates before rotation has an undesired effect.

You might find the rotation is in the wrong direction

```
(cos * point.x) - (sin * point.y) + origin.x,
(cos * point.y) + (sin * point.x) + origin.y
```

so changing signs could work.

If the rotation is alway 90° we know than cos(90°)=0, sin(90°)=1 so it simplifies to

```
this.points[i] = new Vector2(
- point.y + origin.x,
point.x + origin.y );
```

If problems persist it might help to include some actual values for `origin`

, `_pointsOrig[i]`

and the result.