Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/455.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 无休止的游戏:如何在p5.js中随机生成4行对象_Javascript_P5.js - Fatal编程技术网

Javascript 无休止的游戏:如何在p5.js中随机生成4行对象

Javascript 无休止的游戏:如何在p5.js中随机生成4行对象,javascript,p5.js,Javascript,P5.js,我正在用p5.js创建一个无休止的赛车游戏,目前我正面临其开发中最大的问题。我需要其他车辆/障碍物随机生成,但以有序的方式,每个车辆/障碍物在其车道上,并为玩家的车辆留出足够的空间。你有什么建议我怎样才能做到这一点?提前谢谢 到目前为止,我所能做的就是制造各种障碍物,设置它们的位置,并给它们不同的速度。但这当然不会产生随机性 class Obstacle1 { constructor() { this.x = 120 this.y = 0; this.speed =

我正在用p5.js创建一个无休止的赛车游戏,目前我正面临其开发中最大的问题。我需要其他车辆/障碍物随机生成,但以有序的方式,每个车辆/障碍物在其车道上,并为玩家的车辆留出足够的空间。你有什么建议我怎样才能做到这一点?提前谢谢

到目前为止,我所能做的就是制造各种障碍物,设置它们的位置,并给它们不同的速度。但这当然不会产生随机性

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')
 }
}
试试看:

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
    }
  }
}
让ob=[];
函数设置(){
createCanvas(400400);
for(设i=0;i<4;i++){
coords[i]=i*120;
}
for(设i=0;i<3;i++){
ob[i]=新的Obstacle1();
}
}
函数绘图(){
背景(0);
for(设i=0;i<3;i++){
ob[i].draw();
}
}
类别障碍1{
构造函数(){
此.x=随机(coords);
这个。y=0;
这个速度=2
}
画(){
rect(this.x,this.y,60120)
this.y+=this.speed
如果(此.y>=高度){
这个。y=0
}
}
}

如果我理解正确,应该可以使用。

我建议您创建一个pickRandom()函数

前-

尽管您需要调整此特定实例的代码
我还建议您添加一个if语句,其中包含pickRandom()函数。

您必须共享代码的一小部分,这说明了当前无法正常工作的部分。
function pickRandom(){
    x= random(20,width-20)
}