var score = 0;
Crafty.init(800, 600, $('#game')[0])
Crafty.background('blue')
/**
* because of the way gravity works
* (or maybe I just don't really understand it),
* I had to make separate entities for the
* gravity and the actual hit testing for each
* platform.
**/
Crafty.c('Platform', {
platform: function(x, y, visId) {
this.addComponent('2D, DOM')
.attr({
h: 20,
w: 200,
x: x,
y: y - 10,
visId: visId
});
return this;
},
isCounted: false,
visId: 0,
vis: function() {
return Crafty(this.visId);
}
});
Crafty.c('PlatformVis', {
platformVis: function(x, y) {
this.addComponent('2D, DOM, Color, PlatformVis')
.color('green')
.attr({
h: 20,
w: 200,
x: x,
y: y
});
return this;
}
});
// make some platforms
for (var i = 0; i < 5; ++i) {
var x = i * 200;
var y = i * 75 + 92;
var vis = Crafty.e('PlatformVis').platformVis(x, y)
Crafty.e('Platform').platform(x, y, vis.getId());
}
// player
Crafty.e('2D, DOM, Color, Twoway, Gravity, Collision')
.color('red')
.twoway(6, 14)
.gravity('PlatformVis')
.gravityConst(.8)
.attr({
x: 0,
y: 0,
h: 32,
w: 32
})
.checkHits('Platform')
.bind('HitOn', function(e) {
var platform = e[0].obj;
if (!platform.isCounted) {
platform.isCounted = true;
platform.vis().color('yellow');
Crafty('Score').text(++score);
}
}, this);
// score hud
Crafty.e('2D, DOM, Text, Score')
.text(score)
.textColor('white')
.textFont({
size: '32px'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/crafty/0.6.3/crafty-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Player uses the <b>Twoway</b> component, so use arrows/wasd to move/jump</p>
<div id="game"></div>