[OOP] How to set value of Text from a variable in World


(Secret) #1

I think this is more of a OOP and AS3 question than a Flashpunk one and I’ve searched on related materials but still can’t seem to grasp it.

Basically I have an Entity which is a Text to show some HUD stuff. Now the value that text is supposed to have is defined in the World class. So since the Entity is just called by the World, how do I make it so that the Text will update with a value from the parent class.


(JP Mortiboys) #2

If you’re using world.addGraphic() to add the text item, ignore the Entity itself and store a reference to the text object:

public class MyWorld extends World {
   private var txt:Text;

   override public function begin():void {
     addGraphic(txt = new Text("Hello, World!");
   }

   override public function update():void {
     if (Input.mousePressed) {
       txt.text = "Curse your sudden but inevitable betrayal!";
     }
   }
}

If, on the other hand, your Text item is embedded inside an Entity you create directly, simply wrap the call:

public class HudText extends Entity {
   private var txt:Text;

   public function HudText() {
     graphic = txt = new Text("Woo-hoo");
   }

   /** The text to be displayed. */
   public function get text():String { return txt.text; }
   public function set text(value:String):void {
     txt.text = value;
   }
}

public class MyWorld extends World {
   private var hud:HudText;

   override public function begin():void {
     add(hud = new HudText());
   }

   override public function update():void {
     if (Input.mousePressed) {
       hud.text = "Curse your sudden but inevitable betrayal!";
     }
   }
}

(Zachary Lewis) #3

I updated your code block to use get and set functions so your MyWorld would work properly.


(JP Mortiboys) #4

Ah, my mistake - I should have used setText(). Well-spotted sir!


(zakker) #5

Hello i was trying to do this but this addGraphic(hud = new HudText()); gives me error: Error: Implicit coercion of a value of type com.zakker.game:HudText to an unrelated type net.flashpunk:Graphic.


(JP Mortiboys) #6

Sorry mate, there’s a mistake in the second block of code - since HudText is an Entity, not a Graphic, you need to call add() rather than addGraphic().