数组索引超出范围异常:100

时间:2015-05-22 07:11:15

标签: processing

    //----------------------------------------------\\
float x = 300;

float y = 300;

float direction = 0;

float increment = 1;

float speed = 5;

boolean toggle = true; // - For spaceship reversal

float wormX = random(0, 600); // - For wormHole v

float wormY = random(0, 600);

float wormGrowth = 0;

boolean growthSwitch = true; // - for wormHole ^

float[] starXpos = new float[100]; //starsRandom

float[] starYpos = new float[100]; //starsRandom

float d = dist(x, y, wormX, wormY);

int score = 0;



//----------------------------------------------\\
//----------------------------------------------\\ Setup

void setup (){

  size (600, 600);

starsP1();

}
//----------------------------------------------\\ Draw

void draw (){

background (0);

  spaceShip();   
  starsP2();
  wormHole ();
  score();
  warpInitial();
  blackHoleAt(100, 40);
  blackHoleAt(400, 500);


}
//----------------------------------------------\\ 
//----------------------------------------------\\ starsRandom
void starsP1(){

  int i = 0;
   while (i < 100){
     starXpos[i] = random(0, width);
     starYpos[i] = random(0, height);
       i = i + 1;
     } 
}

void starsP2(){

  stroke(255);
  strokeWeight(5);

  int i = 0;
  while (i < 100){
  point(starXpos[i], starYpos[i]);
   i = i + 1; 
   } 
    if (key == 'w'){
   starYpos[i] = starYpos[i] + 1;
 } 




}

我正在尝试为我的代码中的星星创建一种视差形式。当用户按下w,a,s,d时,星形阵列应对应于方向。我不明白这应该如何工作,因为我不断收到此错误。

1 个答案:

答案 0 :(得分:1)

尝试格式化代码,以便更好地了解正在进行的操作:

$value = scalar @books

你的while循环执行直到i == 100.然后在while循环退出后,再次使用该void starsP2(){ stroke(255); strokeWeight(5); int i = 0; while (i < 100){ point(starXpos[i], starYpos[i]); i = i + 1; } if (key == 'w'){ starYpos[i] = starYpos[i] + 1; } } 变量。由于i为100,而您的i数组最多只有99,因此会出错。

修复方法是将if语句移动到while循环内部,或者重构代码以使starYpos不超出数组的范围。