kontra
Version:
Kontra HTML5 game development library
70 lines (61 loc) • 1.65 kB
HTML
<html>
<head>
<title>Advanced Vector Plugin</title>
<script src="../../kontra.js"></script>
</head>
<body>
<canvas id="game" width="600" height="400" style="background: #333331"></canvas>
<script id="code">
// plugin: upgrade kontra.Vector with advanced vector functions
(function() {
let subtract = function(vec) {
return kontra.Vector(this.x - vec.x, this.y - vec.y);
}
let dot = function(vec) {
return this.x * vec.x + this.y * vec.y;
}
let cross = function(vec) {
return this.x * vec.y - this.y * vec.x;
}
let length = function() {
return this.dot(this, this) ** 0.5;
}
let scale = function(percent) {
return kontra.Vector(this.x * percent, this.y * percent);
}
let normalize = function() {
this.scale(this, 1 / (this.length(this) || 1));
}
let distance = function(vec) {
return this.length(this.subtract(this, vec));
}
let advancedVectorPlugin = {}
kontra.extendObject(kontra.Vector, {
subtract,
dot,
cross,
length,
scale,
normalize,
distance
});
})();
// code
// initialize the game and setup the canvas
kontra.init();
// create a basic sprite
window.sprite = kontra.Sprite({
x: 290,
y: 180,
width: 20,
height: 40,
color: 'red'
});
sprite.position = sprite.position.scale(1.5); // move sprite offcenter
// render the sprite
sprite.render();
</script>
<script src="../prism/codeOutput.js"></script>
</body>
</html>