Jump to content

changing text, label over sprite.


Recommended Posts

Hello, I have a sprite (named mosnter) with a child (nameLabel which is text).

Monster is being created in a main_state, clicked function just before adding and starting the state.

I have a function called when sprite is clicked, function is:

function overMonster(sprite)
    console.log("clicked " + sprite.name); //displays the name of sprite, in my case monster
    scoreM ++;
    console.log(scoreM); // coutner works fine
    //sprite.destroy();    // not needed yet
    sprite.nameLabel.setText = "has been clicked "+scoreM; // this one isn't working.

What am I missing?


Link to comment
Share on other sites

Thanks Xeke,  I tried your solution on another machine and I got a pointer on what's missing:


TypeError: sprite.nameLabel is undefined main.js:48"clicked Purple Monster" main.js:44

So it seems it is another kind of error, but I don't know how to fix it.

Link to comment
Share on other sites

It tells you what is wrong there.

nameLabel is undefined on the sprite object.

When you call addChild, the object you add is added to an array of children, not as a property on the sprite.

Quick fix is to also have this line where you call addChild:

sprite.nameLabel = nameLabel;
Link to comment
Share on other sites

Thank you XekeDeath, it's working now.

So basically everytime I addChild to another object, I must name it separatedly?
Just to leran some more, is there another way to access the child, something like:

    var valueAtIndex1 = sprite[0];    valueAtIndex1.text = scoreM;

(tried, but of course didn't worked)

Thank you for your time an patience, will mark this question as solved.


Link to comment
Share on other sites

You should be able to just reference an added object like so:

this.player = game.add.sprite(0, 0, 'player');this.player.gun = game.add.sprite(0, 0, 'gun');this.player.addChild(this.player.gun);// now the gun is accessible directly from the player by referencing this.player.gun

Sprites and all other objects in JavaScript are dynamic and can have properties added at will. Just be sure you don't overwrite a property that's already there, or you'll encounter problems!

Link to comment
Share on other sites


  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Create New...