Added rotation support

This commit is contained in:
Nathan Kunicki 2016-03-27 15:46:06 +01:00
parent f283c4fdc4
commit ec56fe7dea
2 changed files with 39 additions and 6 deletions

View File

@ -20,6 +20,7 @@ class Entity {
this.velocity = new Vector2D(0, 0);
this.acceleration = new Vector2D(0, 0);
this.size = new Vector2D(0, 0);
this.rotation = 0;
this.fields = [];
@ -27,7 +28,8 @@ class Entity {
this.children = [];
this._relativePos = this.pos.clone();
this._lastCalculated = 0;
this._lastRelativePosCalculated = 0;
this._lastRelativeSizeCalculated = 0;
this._game = null;
this._parent = null;
@ -60,11 +62,19 @@ class Entity {
}
/**
* Returns the absolute x (Left) position relative to the entities parent tree
* @returns {number} x - x (Left) position relative to the entities parent tree
*/
get relativeLeft () {
return this._calculateRelativePos().x;
}
/**
* Returns the absolute y (Top) position relative to the entities parent tree
* @returns {number} y - y (Top) position relative to the entities parent tree
*/
get relativeTop () {
return this._calculateRelativePos().y;
}
@ -94,7 +104,7 @@ class Entity {
set height (height) {
return this.size.y = height;
}
/**
* Set the velocity of the entity
@ -193,7 +203,7 @@ class Entity {
// When rendering, the draw calls should use this._relativePos rather than this.pos in order for the position to be correct.
if (this._game && this._lastCalculated < this._game.frameCounter) {
if (this._game && this._lastRelativePosCalculated < this._game.frameCounter) {
if (this._parent) {
@ -205,7 +215,7 @@ class Entity {
this._relativePos.y = this.pos.y;
}
this._lastCalculated = this._game.frameCounter;
this._lastRelativePosCalculated = this._game.frameCounter;
}

View File

@ -49,8 +49,31 @@ class Rect extends Entity {
if (this._game) {
this._game.context.fillStyle = this.color.toString();
this._game.context.fillRect(this._scaleForLeft(this.relativeLeft), this._scaleForTop(this.relativeTop), this._scaleForWidth(this.width), this._scaleForHeight(this.height));
let left = this._scaleForLeft(this.relativeLeft),
top = this._scaleForTop(this.relativeTop),
width = this._scaleForWidth(this.width),
height = this._scaleForHeight(this.height),
ctx = this._game.context;
let xRot = left + (width / 2),
yRot = top + (height / 2);
if (this.rotation > 0) {
// Rotate the canvas based on the central point of this entity
ctx.translate(xRot, yRot);
ctx.rotate(this.rotation * Math.PI / 180);
ctx.translate(-xRot, -yRot);
}
ctx.fillStyle = this.color.toString();
ctx.fillRect(left, top, width, height);
if (this.rotation > 0) {
// Rotate back after drawing
ctx.translate(xRot, yRot);
ctx.rotate(-(this.rotation * Math.PI / 180));
ctx.translate(-xRot, -yRot);
}
return true;