1

Im trying to make a scrolling background of stars for my game in p5js. I've found code that makes the background scroll vertically from bottom to top but i want it backwards. How do I fix this?

let ship;
var bgImg;
var x1 = 0;
var x2;

var scrollSpeed = 2;

function preload() {
  bgImg = loadImage('assets/starbg.png');
  ship = new Sprite(0, 0, 20);
  ship.addImg('assets/space puppy plane.png');
  
}

function setup() {
  new Canvas(800, 800);

  x2 = height;
}

function draw() {
  image(bgImg, 0, x1, width, height);
  image(bgImg, 0, x2, width, height);
  
  x1 -= scrollSpeed;
  x2 -= scrollSpeed;
  
  if (x1 < -height){
    x1 = height;
  }
  if (x2 < -height){
    x2 = height;
  }

 ship.moveTowards(mouse.x, 700);
}


Rabbid76
  • 202,892
  • 27
  • 131
  • 174
Sam Apers
  • 11
  • 1

1 Answers1

1

In this part of your code:

x1 -= scrollSpeed;
x2 -= scrollSpeed;

It's as simple as changing each "-=" into a "+=". This will reverse the direction of travel for each of the squares.

However, this will ruin the part of your code that returns the images back to their starting position, so change this part of your code:

if (x1 < -height){
  x1 = height;
}
if (x2 < -height){
  x2 = height;
}

To instead be:

if (x1 > height){
  x1 = -height;
}
if (x2 > height){
  x2 = -height;
}