# How to store last 20 mouse positions in an array?

Hey all together,

i am Sebastian, i am very new to programming and i think i need some help

i wrote this code snippet to store the last 20 mouse positions but it only stores the same 20times… i cannot figure out why…

``````int num = 20;
float[] lastMouseX = new float[num];
float[] lastMouseY = new float[num];

void setup() {
size(500, 500);
background(255);
}

void draw() {
for(int i = 0; i < num; i = i+1 ) {
lastMouseX[i] = mouseX;
lastMouseY[i] = mouseY;
}

printArray(lastMouseX);

}
``````

`http://Studio.ProcessingTogether.com/sp/pad/export/ro.90vdKMfkiO\$zf`

but i dont quite understand whats happening at the code you send…
i am not that good at programming…

Basically it uses the class `PVector` (https://processing.org/reference/PVector.html) which in this case, stores the `mouseX` and `mouseY` position.

The idea behind this, is that you have an array of `PVector` objects and at the beginning, you keep filling the array until the length becomes 20 and then you continue adding one element at a time and you remove the first element so the length stays at 20.

An example with `ArrayLists` (https://processing.org/reference/ArrayList.html) :

``````ArrayList<PVector> list_positions;
int length_limit = 20;

void setup() {
size(400, 400);
stroke(0);
strokeWeight(4);

list_positions = new ArrayList<PVector>();
}

void draw() {
background(255);
if (list_positions.size() > length_limit) {
//Removing the first element
list_positions.remove(0);
}

//Drawing a line
beginShape();
for (PVector p : list_positions) {
vertex(p.x, p.y);
}
endShape();
}
``````
3 Likes

Thank you very much!
that is exactly what i want, i did not know about PVector but this is very usefull!

1 Like

A PVector is just a convenient way to store a group of two or three floats in a single variable. Plus it has some other handy functions related to vector math.

1 Like