Moving a ellipse on a grid with arrow keys

I have an ellipse that can move on a grid by using the arrow keys. I can move the ellipse but since it’s a function called within draw it keeps creating circles after moving with it. I know using background() in draw can prevent this but this also means that my grid is gone. How can I make my ellipse move while also preventing new ones being created?

This is my code:

int rows = 40;
int cols = 60;
int[][] raster = new int[rows][cols];

int size = 25;
int xPos = 0;
int yPos = 100;


void setup () {
  
  size(1500, 900); 
  
};


void draw () {
  
  fill(225);
  rect(650, 70, 200, 60);
  maakRaster();
  duiker();
  
};


void maakRaster () {
  
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      fill(0, 110, 180);
      rect(xPos, yPos, size, size);
      xPos += size;
    }
      xPos = 0;
      yPos += size;
  }
  
};

int radius = 30, directieX = 0, directieY = 0;
float xPositie = 750, yPositie = 30, speed= 1;

void duiker() {
  
  xPositie = xPositie + speed * directieX;
  yPositie = yPositie + speed * directieY;
  
  if ((xPositie > width-radius) || (xPositie < radius)) {   
    directieX=-directieX;
  }
  
  if ((yPositie > height-radius) || (yPositie < radius)) {   
    directieY=-directieY;
  } 
  
  fill (200); 
  ellipse (xPositie, yPositie, radius, radius);
  
}


void keyPressed() {
  
  if (key == CODED) {
    if (keyCode == LEFT) { 
      directieX=-2;
      directieY=0;
    }
      else if (keyCode == RIGHT) {
        directieX=2;
        directieY=0;
      }
      else if (keyCode == UP) {
        directieY=-2;
        directieX=0;
      }
      else if (keyCode == DOWN) { 
        directieY=2;
        directieX=0;
    }
  }
  
};

I would draw the grid in a PGraphics in setup() and then use the image() in background().

2 Likes

Hello,

You can use background() if you initialize xPos and yPos at the start of each draw() loop:

void maakRaster () 
  {
  xPos = 0;
  yPos = 0;
  //Rest of your code
  }

:)

1 Like

That worked, thank you!