Vectors & Matrices

Making 2D easier

Peter Nederlof // Ex Machina Games

Oh hai :) oh noes! Play with me rotate scale skew skew move
Play for output ...

What's a vector?

 

 

 

Basically

Any n dimensional value (with n > 1)

Vector implementation

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);
	},

	// ...

"Hidden" vectors

var Color = function(r, g, b, a) {
	// ...
};

Color.prototype = {
	add: function(color) {
		// layering?
	},

	multiply: function(color) {
		// bright-/darkening?
	},

	// ...

 

Look for more!

What's a matrix?

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, ...

Matrix implementation?

function Matrix() {
	// magic
}

Too much code for slides, but I put mine on Github:

https://github.com/peterned

Combining them


	// 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]
		);
	}
}

"Why should I use 'em?"

Valid question ...

 

Power!

Vectors & Matrices help simplifying code

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!

// ...

Things that use matrices

CSS

div.lorem span.ipsum {
	-webkit-transform: matrix(
		1.004, -0.071, -0.024, 0.997, 41.814, -24.096
	);
}

More things that use matrices

Canvas

var ctx = canvas.getContext('2d');
ctx.setTransform(
	1.004, -0.071, -0.024, 0.997, 41.814, -24.096
);

Demo

Use JS to generate things:

*le click*

*le click*

Thanks!

Online:

http://twitter.com/peterlof

https://github.com/peterned