Aniziz: Keeping code local and independent
Posted Sept. 10, 2012 by Dave GriffithsA large part of the Aniziz project involves porting the Germination X isometric engine from Haxe to Javascript, and trying to make things a bit more consistent and nicer to use as I go. One of the things I've tried to learn from experiments with functional reactive programming is using a more declarative style, and broadly trying to keep all the code associated with a thing in one place. A good real world example is the growing ripple effect for Aniziz (which you can just about make out in the screenshot above), consisting of a single function that creates, animates and destroys itself without need for any references anywhere else:
game.prototype.trigger_ripple=function(x,y,z) { var that=this; // lexical scope in js annoyance var effect=new truffle.sprite_entity( this.world, new truffle.vec3(x,y,z), "images/grow.png"); var len=1; // in seconds effect.spr.do_centre_middle_bottom=false; effect.finished_time=this.world.time+len; effect.needs_update=true; // will be updated every frame effect.spr.expand_bb=50; // expand the bbox as we're scaling up effect.spr.scale(new truffle.vec2(0.5,0.5)); // start small effect.every_frame=function() { // fade out with time var a=(effect.finished_time-that.world.time); if (a>0) effect.spr.alpha=a; // scale up with time var sc=1+that.world.delta*2; effect.spr.scale(new truffle.vec2(sc,sc)); // delete ourselves when done if (effect.finished_time<that.world.time) { effect.delete_me=true; } }; }
The other important lesson here is the use of time to make movement framerate independent. In this case it's not critical as it's an effect - but it's good practice to always multiply time changing values by the time elapsed since the last frame (called delta). This means you can specify movement in pixels per second, and more importantly means that things will remain consistent in terms of interactivity (within reason) on slower machines.
Created: 15 Jul 2021 / Updated: 15 Jul 2021