Draw Game Objects from outside create function

From outside create function does anyone know how to draw lines or another game Objects? I ask this because the console log returns an error when i create some lines outside create function.

Error In console log:

Uncaught TypeError: Cannot read properties of undefined (reading ‘line’).

Can you help me?

var config = {
    type: Phaser.AUTO,
    parent: 'phaser-example',
    width: 800,
    height: 600,
    scene: {
        preload: preload,
        create: create
    }
};

var game = new Phaser.Game(config);

var l1

function preload ()
{ }

function create ()
{
    drawLines ();
}

function drawLines ()
{
    l1 = this.add.line(0,0, 50,50, 100, 100,  0x0000ff, 0.5).setOrigin(0);
}

can you share a fiddle / SS of the error for the same, code itself looks fine.

You need to set the calling context (this).

function create ()
{
    drawLines.call(this);
}

function drawLines ()
{
    l1 = this.add.line(0,0, 50,50, 100, 100,  0x0000ff, 0.5).setOrigin(0);
}
2 Likes