简体   繁体   中英

Endless game: How to spawn objects randomly on 4 lines wit p5.js

I am creating an endless racing game with p5.js and I am currently facing the biggest problem in its development. I need the other cars/obstacles to spawn randomly but in an ordered fashion, each one in its lane and leaving enough space for the player's car to drive through. Do you have any suggestion how can I achieve this? Thanks in advance.

What I managed to do so far is to create classes of obstacles, set their position and give them different speeds. But this doesn't create randomness of course.

class Obstacle1 {

 constructor() {
    this.x = 120
    this.y = 0;
    this.speed = 2
 }

 draw() {
    image(this.imgObst1, this.x, this.y, 60, 120)
    
    this.y += this.speed
    
    if (this.y >= height){
        this.y = 0
    }
  }

  preload() {
    this.imgObst1 = loadImage('/resources/player/car.png')
 }
}

Try that:

let ob = [];

function setup() {
  createCanvas(400, 400);
  for(let i = 0; i < 4; i ++){
    coords[i] = i*120;
  }
  for(let i = 0; i < 3; i ++){
    ob[i] = new Obstacle1();
  }
}

function draw() {
  background(0);
  for(let i = 0; i < 3; i ++){
    ob[i].draw();
  }
}

class Obstacle1 {

 constructor() {
    this.x = random(coords);
    this.y = 0;
    this.speed = 2
 }

 draw() {
    rect(this.x, this.y, 60, 120)
    
    this.y += this.speed
    
    if (this.y >= height){
        this.y = 0
    }
  }
}

if I understand correctly this should work.

I recommend you create a pickRandom() function

Ex-

function pickRandom(){
    x= random(20,width-20)
}

Although you will need to adjust the code for this particular instance I would also recommend you add a if statement with pickRandom() function in it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM