Cant find solution for restart

Hi All!

I have been trying to add a restart button to this code but variables dont seem to work for me or maybe im doing it wrong. As of now i have tried to add:

void keyPressed() {
 if(key == 'r') {
  restart();
 }
}

void restart() {
 And then some of my variables
}

However i cannot figure it out, anyways here is my code

PImage img;
ArrayList<PVector> data;

float m = 1;
float b = 0;

void setup() {
  img = loadImage("Cykelsti.jpg");
  size(600, 600);
  data = new ArrayList<PVector>();
}

void LinearRegression() {
  float xsum = 0;
  float ysum = 0;

  for (int i = 0; i < data.size(); i++) {
    PVector point = data.get(i);
    xsum += point.x;
    ysum += point.y;
  }

  float xmean = xsum / data.size();
  float ymean = ysum / data.size();

  float num = 0;
  float den = 0;
  for (int n = 0; n < data.size(); n++) {
    PVector point = data.get(n);
    float x = point.x;
    float y = point.y;
    num += (x - xmean) * (y - ymean);
    den += (x - xmean) * (x - xmean);
  }

  m = num/den;
  b = ymean - m * xmean;
}
void drawLine () {
  float x1 = 0;
  float y1 = m * x1 + b;

  float x2 = width;
  float y2 = m * x2 + b;

  stroke(255, 0, 255);
  line(x1, y1, x2, y2);
}

void mousePressed () {
  PVector point = new PVector(mouseX, mouseY);
  data.add(point);
}

void draw() {
  background(51);
  image(img, 0, 0, width, height);
  for (int i = 0; i < data.size(); i++) {
    PVector point = data.get(i);
    fill(255, 0, 0);
    stroke(255);
    ellipse(point.x, point.y, 8, 8);
  }
  if (data.size() > 1) {
    LinearRegression();
    drawLine();
  }
}

Thanks for reading

1 Like

here’s my go to button class, you can make your own as I’ve done here but there are plenty of great libraries with much better functionality.

class Button{
  
  float x,y,w,h;
  int toggle = 0;
  String label;
  boolean pressed = false;
  Button(float xx, float yy, float ww, float hh, String Label){
    
    x = xx;
    y = yy;
    w = ww;
    h = hh;
    label = Label;
  }
  void draw(){
    noStroke();
    fill(255);
    rect(x,y,w,h);
    fill(0);
    text(label,x+5,y+h-5);
  }
  
  boolean pos(){
    
    return x < mouseX && mouseY < x + w && y< mouseY && mouseY < y + h;
  }
  
  void click(){
    if(pos()){
      toggle ++;
    }
    
    if(toggle==2){
      toggle = 0;
    }
  }
};

then create a new button variable.

Button reset
void Reset(){
  if (reset.toggle==1){
    //values you want to reinitialize
  }
}
void mousePressed(){
  if(mouseButton == LEFT && ! reset.pos() && ! trim.pos()){
  toggle++;
  if(toggle == 2){
    toggle = 0;
  }}
  
  if(mouseButton == RIGHT && ! reset.pos() && ! trim.pos()){
    
    inc = -inc;
  }
  if(mouseButton == LEFT && reset.pos()){
  reset.click();
  }
  
  if(mouseButton == LEFT && trim.pos()){
  trim.click();
  }
  
};
include a global "toggle variable"
int toggle = 0;

then in setup

void setup(){
  reset = new Button(1140,10,50,20, "reset");

then in draw


reset.draw();
1 Like