Javascript 如何在数组中循环

Javascript 如何在数组中循环,javascript,processing,p5.js,Javascript,Processing,P5.js,我想让我的机器人的头部在反弹后改变颜色,要做到这一点,我必须在我的阵列中循环。有人能告诉我怎么做吗?另外,如何识别机器人何时碰撞并播放碰撞音乐?有没有办法让机器人在碰撞时改变方向 var颜色=[ {r:66,g:135,b:245}, {r:66,g:242,b:245}, {r:199,g:135,b:194}, {r:168,g:135,b:199}, {r:76,g:35,b:239} ]; var=[]; var x=200; 变量y=100; var xspeed=4; var ysp

我想让我的机器人的头部在反弹后改变颜色,要做到这一点,我必须在我的阵列中循环。有人能告诉我怎么做吗?另外,如何识别机器人何时碰撞并播放碰撞音乐?有没有办法让机器人在碰撞时改变方向

var颜色=[
{r:66,g:135,b:245},
{r:66,g:242,b:245},
{r:199,g:135,b:194},
{r:168,g:135,b:199},
{r:76,g:35,b:239}
];
var=[];
var x=200;
变量y=100;
var xspeed=4;
var yspeed=-3;
var机器人;
var-img;
var bounceSound;
声音;
空间声音;
函数预加载(){
img=loadImage('resources/space.png');
bounceSound=loadSound('Sounds/blip.mp3');
collideSound=loadSound('Sounds/collide.mp3');
spaceSound=loadSound('Sounds/spaceSound.mp3');
}
函数设置(){
createCanvas(1200800);
矩形模式(中心);
spaceSound.loop();
机器人[0]=新机器人(随机(1200)、随机(800)、0);
机器人[1]=新机器人(随机(1200)、随机(800)、1);
机器人[2]=新机器人(随机(1200)、随机(800)、2);
机器人[3]=新机器人(随机(1200)、随机(800)、3);
}
函数绘图(){
背景(img);
for(机器人的var){
r、 show();
r、 move();
r、 反弹();
}
}
函数mousePressed(){
推(新机器人(mouseX,mouseY,4));
}
班级机器人{
构造函数(_x,_y,_col){
this.xLoc=x;
this.yLoc=\u y;
this.colNum=\u col;
这个.xspeed=4;
这个.yspeed=-3;
}
show(){
仰泳();
填充(颜色[this.colNum].r,颜色[this.colNum].g,颜色[this.colNum].b);
rect(this.xLoc,this.yLoc,100,50,25);
填充(0);
椭圆(this.xLoc-25,this.yLoc+10,20);
椭圆(this.xLoc+25,this.yLoc+10,20);
填充(255);
椭圆(this.xLoc-25,this.yLoc+15,5);
椭圆(this.xLoc+25,this.yLoc+15,5);
中风(150);
行(this.xLoc-20、this.yLoc-10、this.xLoc-30、this.yLoc-60);
行(this.xLoc+20,this.yLoc-10,this.xLoc+30,this.yLoc-60);
仰泳();
填充(150);
椭圆(this.xLoc,this.yLoc+65,40,80);
填充(218112214)
三角形(this.xLoc-17,this.yLoc+40,this.xLoc-20,this.yLoc+70,this.xLoc-40,this.yLoc+85);
三角形(this.xLoc+17,this.yLoc+40,this.xLoc+20,this.yLoc+70,this.xLoc+40,this.yLoc+85);
三角形(this.xLoc-10,this.yLoc+100,this.xLoc+10,this.yLoc+100,this.xLoc,this.yLoc+120);
}
移动(){
this.xLoc=this.xLoc+this.xspeed;
this.yLoc=this.yLoc+this.yspeed;
}
弹跳(){
如果(this.xLoc>宽度| | this.xLoc<0){
this.xspeed=(this.xspeed*-1);
蹦蹦跳跳;
}
if(this.yLoc>高度| | this.yLoc<0){
this.yspeed=this.yspeed*-1;
蹦蹦跳跳;
}
}
}

需要显示颜色时,请使用nextColor(发布在下面)功能

var currentColorIndex=0;
var nextColor = function(){
  var color = colors[currentColorIndex];
  currentColorIndex = (currentColorIndex+1)%colors.length;
  return color;
}