Rjdlee
Rjdlee

Reputation: 779

Finding vertices from dimensions and position of angled rectangle

I'm attempting to implement the transformation matrix formula:

cos() -sin()

sin() cos()

In the following Javascript code where this.rot.cos = cos of the angle and this.rot.sin is sin of the angle.

var h1 = this.rot.cos * this.dimension.x,
h2 = this.rot.sin * this.dimension.x,
h3 = this.rot.cos * this.dimension.y,
h4 = this.rot.sin * this.dimension.y;

v = [

{
  x: h1 - h4,
  y: h2 + h3
},

{
  x: -(h1 - h4),
  y: h2 + h3
},

{
  x: -(h1 - h4),
  y: -(h2 + h3)
},

{
  x: h1 - h4,
  y: -(h2 + h3)
}

  ];

 tankBattle.ctx.beginPath();
  tankBattle.ctx.moveTo(v[0].x, v[0].y);
  tankBattle.ctx.lineTo(v[1].x, v[1].y);
  tankBattle.ctx.lineTo(v[2].x, v[2].y);
  tankBattle.ctx.lineTo(v[3].x, v[3].y);
  tankBattle.ctx.lineTo(v[0].x, v[0].y);

The shape I get moves in the same pattern as sin and cos waves and becomes 0 at certain degrees (90 and 270 I believe). Is there something I'm doing wrong to calculate the vertices here?

Upvotes: 0

Views: 67

Answers (1)

GameAlchemist
GameAlchemist

Reputation: 19294

It seems you did a mistake in your formula, the following is working :

http://jsbin.com/wudeqewa/1/edit

function drawTank(x, y, rot)  {

    var cosrot = Math.cos(rot);
    var sinrot = Math.sin(rot);

    var h1 = cosrot * dimension.x,
        h2 = sinrot * dimension.x,
        h3 = cosrot * dimension.y,
        h4 = sinrot * dimension.y;

    v = [{
        x: h1 - h4,
        y: h2 + h3
    },

    {
        x: h1 + h4,
        y: h2 - h3
    },

    {
        x: -h1 + h4,
        y: -h2 - h3
    },

    {
        x: -h1 - h4,
        y: -h2 + h3
    }];

    ctx.save();
    ctx.translate(x, y);
    ctx.beginPath();
    ctx.moveTo(v[0].x, v[0].y);
    ctx.lineTo(v[1].x, v[1].y);
    ctx.lineTo(v[2].x, v[2].y);
    ctx.lineTo(v[3].x, v[3].y);
    ctx.lineTo(v[0].x, v[0].y);
    ctx.stroke();
    ctx.restore();
}

Upvotes: 1

Related Questions