Great suggestions. What about a Multiway component that will make it easy to create controlcomponents by binding a key to a direction in degrees:
Crafty.c("LeftControls", {
init: function() {
this.requires('Multiway');
},
leftControls: function(speed) {
this.multiway(speed, {W: -90, S: 90, D: 0, A: 180})
return this;
}
});
Crafty.c("NumControls", {
init: function() {
this.requires('Multiway');
},
numControls: function(speed) {
this.multiway(speed, { NUMPAD_8: -90, NUMPAD_2: 90, NUMPAD_6: 0, NUMPAD_4: 180,
NUMPAD_9: -45, NUMPAD_3: 45, NUMPAD_7: -135, NUMPAD_1: 135})
return this;
}
});
I have moved most stuff out of the enterframe event, so all that has to happen is calculate two sums and trigger the Moved event.
There is quite a bit of housekeeping to do in order to support keys that move on two axes, but performance vise it is ok as it is done on KeyDown (i fixed the KeyDown rapid fire).
Crafty.c("Multiway", {
_speed: 3,
_keyDirection: {},
_keys: [],
_movement: {x: 0, y: 0},
init: function() {
this.requires("Keyboard");
},
multiway: function(speed, keys) {
if(speed) this._speed = speed;
this._keyDirection = keys;
this.speed(this._speed);
this.bind("KeyDown", function(e) {
if(this._keys[e.keyCode]) {
this._movement.x = Math.round((this._movement.x + this._keys[e.keyCode].x)*1000)/1000;
this._movement.y = Math.round((this._movement.y + this._keys[e.keyCode].y)*1000)/1000;
this.trigger('NewDirection', this._movement);
console.log(this._movement.y + ' ' + this._movement.x);
}
})
.bind("KeyUp", function(e) {
if(this._keys[e.keyCode]) {
this._movement.x = Math.round((this._movement.x - this._keys[e.keyCode].x)*1000)/1000;
this._movement.y = Math.round((this._movement.y - this._keys[e.keyCode].y)*1000)/1000;
this.trigger('NewDirection', this._movement);
}
})
this.bind("enterframe",
function() {
if (this.disableControls) return;
if(this._movement.x !== 0) {
this.x += this._movement.x;
this.trigger('Moved', {x: this.x - this._movement.x, y: this.y});
}
if(this._movement.y !== 0) {
this.y += this._movement.y;
this.trigger('Moved', {x: this.x, y: this.y - this._movement.y});
}
});
return this;
},
speed: function(speed) {
for(var k in this._keyDirection) {
var keyCode = Crafty.keys[k] || k;
this._keys[keyCode] = { x: Math.round(Math.cos(this._keyDirection[k]*(Math.PI/180))*1000 * speed)/1000,
y: Math.round(Math.sin(this._keyDirection[k]*(Math.PI/180))*1000 * speed)/1000}
}
return this;
}
});
I think that the Multiway component could exist along some easy to use components, say LeftControls, RightControls.