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 :smiley:

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

thank your for your help in advance

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

void setup() {
size(500, 500);

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


thank your for your fast help!

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 ( 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 ( :

ArrayList<PVector> list_positions;
int length_limit = 20;

void setup() {
  size(400, 400);

  list_positions = new ArrayList<PVector>();

void draw() {
  //Adding a new position
  list_positions.add(new PVector(mouseX, mouseY));
  if (list_positions.size() > length_limit) {
    //Removing the first element

  //Drawing a line
  for (PVector p : list_positions) {
    vertex(p.x, p.y);

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