craftyjs/Crafty

How to edit the value of a text component when stored in a variable?

Opened this issue · 1 comments

I have this variable

var sceneHealthText = Crafty.e("2D, DOM, Text")
        .attr({x: 100, y: 100})
        .textColor("white")
        .textFont({size: "20px", weight: "bold"});

when I try to update the text using sceneHealthText.text(player.health); I get an error saying TypeError: Cannot read property 'text' of undefined

If it helps, you can see my full code here (https://ghostbin.com/paste/azcxx) and a 'working' example here (https://repl.it/@j0rdancodes/Game)

The issue is how you're using and calling the init method:

  init: function(maxHealth, healthText) {
    // snip 
    healthText.text(String(this.health));

Init isn't a constructor -- it doesn't take any arguments so maxHealth and healthText are always undefined. The simplest approach would probably be to create a separate method that you can call and pass in those values:

Crafty.c("Player", {
  player: function(maxHealth, healthText) {
    this.maxHealth = maxHealth;
    this.health = maxHealth;
    healthText.text(String(this.health));
  },
  init: function() {
     //  etc

And then later call it like this:

  var player = Crafty.e("Player")
      .player(100, sceneHealthText)
      .twoway(200)
      // etc

This is what methods like twoway are doing for their respective components -- passing in the initial data.

Hope that helps!