If you want to extend Kiwi.js objects, such as Sprites, to create reusable specialised game objects, you can use your favourite Javascript techniques to do so. If you want to mimic classical inheritance Kiwi.js provides an easy way to do this.
Here is an example of extending the Kiwi.GameObjects.Sprite class in both Typescript and Javascript.
Typescript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class CannonBall extends Kiwi.GameObjects.Sprite { constructor( state, x, y, angle ) { super( state, state.textures['cannonBall'], x, y, false ); this.angle = angle; this.speed = 12; this.rotation = this.angle; } public speed: number; public angle: number; public update() { super.update(); this.x += ( Math.cos( this.angle ) * this.speed ); this.y += ( Math.sin( this.angle ) * this.speed ); } } |
Javascript
If you’re using Javascript you can use the Kiwi.extends function to create the subclass. The extends function uses a technique of extending objects identical to Typescript.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// First - the subclass constructor var CannonBall = function( state, x, y, angle ){ //call the superclass constructor Kiwi.GameObjects.Sprite.call( this, state, state.textures.cannonBall, x, y, false ); this.angle = angle; this.speed = 12; this.rotation = this.angle; CannonBall.prototype.update = function(){ Kiwi.GameObjects.Sprite.prototype.update.call(this); this.x += ( Math.cos( this.angle ) * this.speed ); this.y += ( Math.sin( this.angle ) * this.speed ); } }; //Second - extend the class Kiwi.extend( CannonBall, Kiwi.GameObjects.Sprite ); |
This is functionally identical to the Javascript that Typescript would compile to do the same thing. If you prefer you can use the function in the same way too. It’s purely a matter of preference. It looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
var CannonBall = (function (_super) { __extends(CannonBall, _super); function CannonBall(state, x, y, angle) { _super.call(this, state, state.textures['cannonBall'], x, y, false); this.angle = angle; this.speed = 12; this.rotation = this.angle; } CannonBall.prototype.update = function () { _super.prototype.update.call(this); this.x += (Math.cos(this.angle) * this.speed); this.y += (Math.sin(this.angle) * this.speed); }; return CannonBall; })(Kiwi.GameObjects.Sprite); |
Share the joy
Recent Comments