I'm creating a melonJS game.
In my player entity - game.PlayerEntity = me.ObjectEntity.extend({
, its update function checks for collision:
game.PlayerEntity = me.ObjectEntity.extend({
var collision = me.game.collide(this);
if (collision) {
if (collision.obj.type == me.game.ACTION_OBJECT) {
console.log("NPCname: " + game.NPCEntity.init); //get settings from NPCEntity
}
}
Then in my NPC entity object, game.NPCEntity = me.ObjectEntity.extend ({
, I want to return settings.name
to the PlayerEntity above. So to do this I've created a closure returnSettings()
.
1) console.log(settings.name)
outputs "Lee" as expected
2) return settings.name
outputs "undefined"
Why is this?
game.NPCEntity = me.ObjectEntity.extend ({
init : function(x, y, settings) {
settings.image = "wheelie_right";
settings.spritewidth = 64;
settings.name = "Lee";
this.parent(x, y, settings);
this.collidable = true;
this.type = me.game.ACTION_OBJECT;
console.log(settings.name); //works
console.log("returning... " + returnSettings()); //works
//closure to return settings values externally
function returnSettings () {
return settings.name; //returns undefined when called by PlayerEntity above.
}
},
Thanks!
game.NPCEnity
does not reference the instance, but the constructor function. If you set this.settings = …
in the constructor function, you are creating a property on the instance.You can access the instance with the this
keyword inside your update
function where you handle the collision, where it does point to the player
.
To cite the tutorial:
// call by the engine when colliding with another object // obj parameter corresponds to the other object (typically the player) touching this one onCollision: function(res, obj) {…}
That means you can access the enemies settings by obj.settings
inside that event handler.
If you're not using that handler but calling the collide
method, from what I see the return value of that function has a .obj
property which is presumably the collision target:
if (collision) {
if (collision.obj.type == me.game.ACTION_OBJECT) {
console.log("NPCname: " + collision.obj.settings.name); //get settings from NPCEntity
}
}