Skip to content

Instantly share code, notes, and snippets.

@joseadrian
Last active October 25, 2022 10:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joseadrian/5b9c52ecd21a6c1dd47f to your computer and use it in GitHub Desktop.
Save joseadrian/5b9c52ecd21a6c1dd47f to your computer and use it in GitHub Desktop.
Quintus - Box component

Component for Quintus Game Engine that prevents an sprite going outside the X axis of a level (layer) generated with Tiled. One of the layers needs to have a box attribute. And the box component uses the sprite's collision points.

Imgur

If you are not using a tiled map, you can set a box property with a "maxX" attribute to the sprite.

Tested a few times and it works, even if you scale the sprite.

Q.Sprite.extend("Square",{
init: function(p) {
this._super(p,{
// ...
});
this.add('box');
this.on('boundaries');
},
boundaries: function(side) {
// If the player touch the bottom of the map
if(side == 'bottom') {
this.p.x = Q.el.width / 2;
this.p.y = Q.el.height / 2;
}
}
});
Q.component('box', {
added: function() {
this.entity.on('inserted', this, 'getBoundaries');
this.entity.on('step', this, 'step');
},
getBoundaries: function() {
var p = this.entity.p;
if( ! p.scale) {
p.scale = 1;
}
// X
points = p.points.map(function(o){ return o[0] });
p.minPointX = Math.abs(Math.min.apply(null, points)) * p.scale;
p.maxPointX = Math.abs(Math.max.apply(null, points)) * p.scale;
// Y
points = p.points.map(function(o){ return o[1] });
p.minPointY = Math.abs(Math.min.apply(null, points)) * p.scale;
p.maxPointY = Math.abs(Math.max.apply(null, points)) * p.scale;
if(Q._isUndefined(p.boundingBox)) {
p.boundingBox = Q._detect(this.entity.stage.lists.TileLayer, function(layer) {
return layer.p.boundingBox ? { maxX: layer.p.w, maxY: layer.p.h } : {};
});
}
p.boundingBox = Q._extend({ minX: 0, maxX: Q.el.width, minY: 0, maxY: Q.el.height }, p.boundingBox);
},
step: function() {
var p = this.entity.p;
if(p.x <= p.boundingBox.minX + p.minPointX) {
p.x = p.boundingBox.minX + p.minPointX;
this.entity.trigger('boundaries', 'left');
} else if( p.x >= p.boundingBox.maxX - p.maxPointX) {
p.x = p.boundingBox.maxX - p.maxPointX;
this.entity.trigger('boundaries', 'right');
}
if(p.y <= p.boundingBox.minY + p.maxPointY) {
p.y = p.boundingBox.minX + p.maxPointY;
this.entity.trigger('boundaries', 'top');
} else if(p.y >= p.boundingBox.maxY - p.minPointY) {
p.y = p.boundingBox.maxY - p.minPointY;
this.entity.trigger('boundaries', 'bottom');
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment