Parallax background in with depth in Phaser 3

I'm working on a 2D space shooter type of game in typescript using Phaser 3 and am trying to get a parallax background with different depths going. But I'm having trouble getting the math right.

You can see my work in progress here: https://www.youtube.com/watch?v=Pea9yVbTD64

As stated in the video everything works if the players x and y are positive, but breaks when they are negative, and I can't figure out what I am doing wrong. Any help would be greatly appreciated. Or perhaps there is a better way to accomplish this?

What I'm doing is randomly generating out a bunch of the Sprites, storing them in an Array, and then updating their position with this code.

• _Nebulas: is an Array<NebulaParticle>.
• p.distance: is a number between 1 and 5 to signify how far away the sprite is and is used to make them move slower when they are furher away.
• _Width and _Height are both arbitrary numbers to signify how big the area is that the parallax should cover, in the video they are both set to 80.
• OriginalOffsetX/Y is the original random po﻿sition the Sprite was given.

(this line is here because the below code formatting wont work otherwise.)

public update(delta: number, playerx: number, playery: number) {
console.log(playerx + ", " + playery );
for (let i = 0; i < this._Nebulas.length; i++) {
let p = this._Nebulas[i];
p._Sprite.x = (playerx + (this._Width / 2)) - (((playerx / p.distance) + p.OriginalOffsetX) % this._Width);
p._Sprite.y = (playery + (this._Width / 2)) - (((playery / p.distance) + p.OriginalOffsetY) % this._Height);
}
}

class NebulaParticle {
public _Sprite: Phaser.GameObjects.Sprite;
public OriginalOffsetX: number;
public OriginalOffsetY: number;
public distance: number;
}﻿


Just use a camera with the gameobject method setScrollFactor. Setting 0 makes it fixed to the camera; setting a number between 0-1 will make it scroll at varying rates, which you can use to set up parallax scrolling layers.