Skip to content

Instantly share code, notes, and snippets.

@blixt
Last active August 29, 2015 14:05
Show Gist options
  • Save blixt/99d051fa8a887f1981f5 to your computer and use it in GitHub Desktop.
Save blixt/99d051fa8a887f1981f5 to your computer and use it in GitHub Desktop.
var pocket = require('pocket');
// Traits just need to implement an interface and can be instances or singletons (see anonymous trait below for
// interface).
var controller = require('./traits/controller');
var health = require('./traits/health');
var score = require('./traits/score');
var verlet = require('./traits/verlet');
var player = pocket.entity({name: 'Blixt'});
// Adding traits to an entity will really create a reverse map of trait => [entities] which will tick in an order
// that satisfies the before/after relationships.
// This version will not create instances of traits, and instead let the trait either set up its own global state,
// or add properties onto the player entity to keep state at an entity-level.
player.addTrait(controller, {a: 'left', d: 'right'});
player.addTrait(health, 100);
player.addTrait(score);
player.addTrait(verlet, 100, 500);
// This version creates self-contained instances of traits instead of putting properties directly on the entity.
// It will however need to put anonymous properties on the entity that point at the trait instance. For example,
// this would happen under the hood: player._t1 = <instance returned by controller(...)>;
// The controller instance would also be assigned an "id" property with value "_t1" to accommodate lookups (see
// below).
player.addTraits(
controller({a: 'left', d: 'right'}),
health(100),
score(),
verlet(100, 500));
// Anonymous trait for applying controller input to Verlet physics.
player.addTrait({
// Ensure we know the inputs for this tick. This will work by checking:
// x == controller || x instanceof controller
after: [controller],
// Ensure we apply acceleration before Verlet is evaluated.
before: [verlet],
init: function (player, arg1, arg2) {
// We could set up the player entity here, and/or do something with the arguments after the trait in addTrait.
// The arguments would only make sense for the first version of using traits (the second version would put
// them in the instance instead).
},
tick: function (player) {
// This assumes each trait adds certain properties on the entity. Unsure how to make the property API obvious.
if (player.input.left) player.vx -= .1;
if (player.input.right) player.vx += .1;
// An alternative way would be to store a reference to the trait itself on the entity (have addTrait apply a
// unique id to every trait constructor/singleton and add a property with the id as its name, referencing the
// trait on the entity).
var input = player.get(controller), physics = player.get(verlet);
if (input.left) physics.vx -= .1;
if (input.right) physics.vy += .1;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment