JSFiddle - React, Tailwind, and code Playground
HTML
<script src="http://cdn.crafty-modules.com/crafty-DEBUG.js"></script>
JavaScript
Crafty.init(400,400);
Crafty.background("#000");
Crafty.c("Velocity", {
/*
Provides entity with a vecctor2D that is applied to object position.
_clamp sets the maximum length of this
*/
_clamp: 7,
init: function() {
console.log('Velocity component init');
this.v = new window.Vector2;
this.bind("EnterFrame", function(e) {
if (window.paused !== 1) {
if (this.v.length() > this._clamp) {
this.v = this.v.normalize();
this.v = this.v.scale(this._clamp);
}
this.x += this.v.x;
return this.y += this.v.y;
}
});
return this;
}
});
Crafty.c("Gravity", {
_amount: .1,
init: function() {
this.requires("Velocity");
return this.bind("EnterFrame", function(e) {
return this.v.y += this._amount;
});
}
});
var Vector2;
Vector2 = (function() {
Vector2.name = 'Vector2';
function Vector2(x, y) {
this.x = x != null ? x : 0;
this.y = y != null ? y : 0;
}
Vector2.prototype.add = function(vector) {
return new Vector2(this.x + vector.x, this.y + vector.y);
};
Vector2.prototype.sub = function(vector) {
return new Vector2(this.x - vector.x, this.y - vector.y);
};
Vector2.prototype.scale = function(factor) {
return new Vector2(this.x * factor, this.y * factor);
};
Vector2.prototype.length = function() {
return Math.sqrt(this.x * this.x + this.y * this.y);
};
Vector2.prototype.normalize = function() {
return new Vector2(this.x / this.length(), this.y / this.length());
};
Vector2.prototype.perp = function() {
return new Vector2(-this.y, this.x);
};
return Vector2;
})();
window.Vector2 = Vector2;
console.log( window.Vector2);
var redSq = Crafty.e("2D, Canvas, Color, Gravity, Velocity")
.attr({x: 200, y: 30, w: 16, h: 16})
.color('rgb(255,0,0)').bind(...