问题是您在这里同时设置所有值:
//Stores the x&y values of the mouse in the arrays
for (int i = 0; i < xArray.length; i++){
xArray[i] = this.mouseX;
yArray[i] = this.mouseY;
}
您只想更新数组中的 1 个元素,并让其他元素移动一个:“最旧”值消失,新值进入。您可以手动使用反向 for 循环(从数组末尾到前面除了第一个元素)或使用arrayCopy:
private void updateArrays(int x,int y){
arrayCopy(xArray, 0, xArray, 1, xArray.length-1);//shift all elements backwards by 1
arrayCopy(yArray, 0, yArray, 1, yArray.length-1);//so x at index 99 goes 98, 98 to 97, etc. excepting index 0
xArray[0] = x;//finally add the newest value
yArray[0] = y;//at the start of the array (so in the next loop it gets shifted over by 1) like the above values
}
这使得完整列表:
import processing.core.PApplet;
public class Assignment09b extends PApplet {
// Create arrays to stort the x & y values of the mouse
int [] xArray = new int [100];
int [] yArray = new int [100];
public void setup(){
//Runs at 60Fps
size(500, 500);
}
public void draw(){
//Changes the background each frame
background(0);
updateArrays(mouseX,mouseY);
//SHOULD print out the snake using series of ellipses
for (int i = 0; i < xArray.length; i++){
//Generates a random color each time
fill(random(255), random(255), random(255));
ellipse(xArray[i], yArray[i], 25, 25);
}
}
private void updateArrays(int x,int y){
arrayCopy(xArray, 0, xArray, 1, xArray.length-1);//shift all elements backwards by 1
arrayCopy(yArray, 0, yArray, 1, yArray.length-1);//so x at index 99 goes 98, 98 to 97, etc. excepting index 0
xArray[0] = x;//finally add the newest value
yArray[0] = y;//at the start of the array (so in the next loop it gets shifted over by 1) like the above values
}
}
由于这是一个练习,我建议更多地使用 for 循环和数组。这是你最终会使用很多并且值得练习/掌握的东西。祝你好运!
var xArray = new Array(100);
var yArray = new Array(100);
function setup(){
createCanvas(500, 500);
}
function draw(){
//Changes the background each frame
background(0);
updateArrays(mouseX,mouseY);
//SHOULD print out the snake using series of ellipses
for (var i = 0; i < xArray.length; i++){
//Generates a random color each time
fill(random(255), random(255), random(255));
ellipse(xArray[i], yArray[i], 25, 25);
}
}
function updateArrays(x,y){
arrayCopy(xArray, 0, xArray, 1, xArray.length-1);//shift all elements backwards by 1
arrayCopy(yArray, 0, yArray, 1, yArray.length-1);//so x at index 99 goes 98, 98 to 97, etc. excepting index 0
xArray[0] = x;//finally add the newest value
yArray[0] = y;//at the start of the array (so in the next loop it gets shifted over by 1) like the above values
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.4/p5.min.js"></script>