Hello!
In my current project I need to have multiple sprites on the screen at the same time, some of them changing their coordinates each frame. If the number of the sprites on the screen gets bigger than 6, the app gets slower and slower, just like a lag effect.
The sprites that are on the screen are all like this:
package objects;
import openfl.display.Sprite;
import openfl.text.TextField;
import openfl.text.TextFormat;
import openfl.text.TextFormatAlign;
import utils.ColorManager;
class Square extends Sprite {
public var square: Sprite;
public var number: TextField;
public function new(size: Float, value: String) {
super();
initSquare(size);
initNumber(size, value);
}
private function initSquare(size: Float): Void {
square = new Sprite();
square.graphics.beginFill(ColorManager.PRIMARY_COLOR);
square.graphics.drawRect(0, 0, size, size);
square.graphics.endFill();
addChild(square);
}
private function initNumber(size: Float, value: String): Void {
var format: TextFormat = new TextFormat();
format.font = "fonts/Verano.ttf";
format.size = Std.int(size - 5);
format.color = ColorManager.BACKGROUND_COLOR;
format.align = TextFormatAlign.CENTER;
number = new TextField();
number.text = value;
number.defaultTextFormat = format;
number.selectable = false;
number.width = number.textWidth + 4;
number.height = number.textHeight + 4;
number.x = size / 2 - number.width / 2;
number.y = size / 2 - number.height * 2 / 5;
addChild(number);
}
}
And this is the function I call to create two new Sprites:
private function createNewSquaresPair(): Void {
var leftSquareValue: String, rightSquareValue: String;
var randomNumber: Float = Math.random();
if (randomNumber < 0.500) {
leftSquareValue = "0";
rightSquareValue = "1";
} else {
leftSquareValue = "1";
rightSquareValue = "0";
}
leftAisle.push(new Square(Lib.current.stage.stageWidth / 12, leftSquareValue));
leftAisle[leftAisle.length - 1].x = leftSquare.x + leftSquare.width / 2 - leftAisle[leftAisle.length - 1].width / 2;
leftAisle[leftAisle.length - 1].y = - leftAisle[leftAisle.length - 1].height;
addChild(leftAisle[leftAisle.length - 1]);
rightAisle.push(new Square(Lib.current.stage.stageWidth / 12, rightSquareValue));
rightAisle[rightAisle.length - 1].x = rightSquare.x + rightSquare.width / 2 - rightAisle[rightAisle.length - 1].width / 2;
rightAisle[rightAisle.length - 1].y = - rightAisle[rightAisle.length - 1].height;
addChild(rightAisle[rightAisle.length - 1]);
}
Every frame I move the sprites:
private function onEnterFrame(event: Event): Void {
for (index in 0...leftAisle.length) {
leftAisle[index].y += 3;
rightAisle[index].y += 3;
}
if (leftAisle[leftAisle.length - 1].y >= 200 && rightAisle[rightAisle.length - 1].y >= 200) {
createNewSquaresPair();
}
}
I’ve done this before and everything worked fine.
Thank you!