public void Crafty.c(String name, Object component)
Creates a component where the first argument is the ID and the second is the object that will be inherited by entities.
There is a convention for writing components.
init
will automatically be called as soon as the
component is added to an entity.Crafty.c("Annoying", {
_message: "HiHi",
init: function() {
this.bind("EnterFrame", function() { alert(this.message); });
},
annoying: function(message) { this.message = message; }
});
Crafty.e("Annoying").annoying("I'm an orange...");
WARNING:
in the example above the field _message is local to the entity. That is, if you create many entities with the Annoying component they can all have different values for _message. That is because it is a simple value, and simple values are copied by value. If however the field had been an object or array, the value would have been shared by all entities with the component because complex types are copied by reference in javascript. This is probably not what you want and the following example demonstrates how to work around it:
Crafty.c("MyComponent", {
_iAmShared: { a: 3, b: 4 },
init: function() {
this._iAmNotShared = { a: 3, b: 4 };
},
});