Sign in to follow this  

Need help figuring out Parallax background

Recommended Posts

So I'm working on a 2D space shooter type of game and am trying to get a parallax background thing going. But I'm having trouble getting the math right.

You can see my work in progress here:

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, and then updating their position with this code.

_Nebulas: is Array<NebulaParticle> which is listed below as well.
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 position the Sprite was given.

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;

Thank you very much.

Share this post

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.