Reputation: 147
The answer should be simple but I can't find out how anywhere..
So I have a Main.hx class and a ObjectManager.hx class. In the main class's constructor, it calls ObjectManager.addAllToScreen(); and my objectManager should then add the objects to the screen.
I thought this would be ok because in the constructor of Main you can just say addChild(Objects.platform); but apparently addChild isn't accessible?
The error is: Class<Main> has no field addChild
so I'd guess that addChild is a method of Sprite or something?
package;
class Main extends Sprite {
public function new() {
super();
ObjectManager.addAllToScreen();
}
}
In ObjectManager:
package;
class ObjectManager {
public static function addAllToScreen():Void {
Main.addChild(Objects.platform);
Main.addChild(Objects.messageField);
}
}
UPDATE:
Ok so now the code is this... and it runs just fine apart from the objects never showing up on screen - however if the addChild code is put in main, they do show up.
Main:
class Main extends Sprite {
public function new() {
super();
var objectManager = new ObjectManager();
objectManager.addAllToScreen();
}
ObjectManager:
package;
import openfl.display.Sprite;
class ObjectManager extends Sprite {
public function new() {
super();
}
public function addAllToScreen() {
addChild(Objects.platform);
addChild(Objects.messageField);
}
}
Upvotes: 2
Views: 929
Reputation: 45
You just need to pass a reference to the stage to your ObjectManager class so you can add things to it later on.
Check this out.
Main.hx
package;
import openfl.display.Sprite;
class Main extends Sprite {
public function new () {
super();
ObjectManager.setup(stage);
ObjectManager.addAllToScreen();
}
}
ObjectManager.hx
package ;
import openfl.display.Sprite;
import openfl.display.Stage;
class ObjectManager {
// The reference to the applications stage
private static var stage:Stage;
// Do this first,
// we need to hold a reference to the Stage object so we can add to it later
public static function setup(stageref:Stage) {
stage = stageref;
}
public static function addAllToScreen() {
// An array of randomly generated sprite objects
var sprites:Array<Sprite> = [randomSprite(), randomSprite(), randomSprite()];
for(sprite in sprites) {
// Position the sprites randomly over the screen
sprite.x = Math.random() * stage.stageWidth;
sprite.y = Math.random() * stage.stageHeight;
// Add them to the stage
stage.addChild(sprite);
}
}
// Ignore this
// Makes a randomly sized circle in a random colour
private static function randomSprite():Sprite {
var spr = new Sprite();
spr.graphics.beginFill(Std.int(0xffffff * Math.random()), 1);
spr.graphics.drawCircle(0, 0, (Math.random() * 100) + 20);
spr.graphics.endFill();
return spr;
}
}
Upvotes: 2
Reputation: 935
addChild() is available in openfl.DisplayObjectContainer
, which Sprite
extends. So you would need to make your class extend Sprite, yes.
Upvotes: 2