Making 2D easier
Peter Nederlof //
Ex Machina Games
Peter Nederlof //
Ex Machina Games
Really easy:
var Vector = function(x, y) {
this.x = x;
this.y = y;
};
Vector.prototype = {
add: function(v) {
return new Vector(this.x + v.x, this.y + v.y);
},
multiply: function(v) {
return new Vector(this.x * v.x, this.y * v.y);
},
// ...
var Color = function(r, g, b, a) {
// ...
};
Color.prototype = {
add: function(color) {
// layering?
},
multiply: function(color) {
// bright-/darkening?
},
// ...
An ordered bunch of numbers, somehow related.
var matrix = [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ];
Entries may represent things like rotation, scaling, translation, ...
function Matrix() {
// magic
}
Too much code for slides, but I put mine on Github:
// Vector.prototype
transform: function(matrix) {
var m = matrix.entries;
return new Vector(
m[0] * this.x + m[1] * this.y + m[2],
m[3] * this.x + m[4] * this.y + m[5]
);
}
}
No more heaps of separate x and y coordinates, readability!
var v = new Vector(3, 7); var m = new Matrix(); var c = m.translate(v).rotate(0,4); // translated & rotated! // ...
div.lorem span.ipsum {
-webkit-transform: matrix(
1.004, -0.071, -0.024, 0.997, 41.814, -24.096
);
}
var ctx = canvas.getContext('2d');
ctx.setTransform(
1.004, -0.071, -0.024, 0.997, 41.814, -24.096
);