how create a simple object animation in processing

Viewed 190

QUESTION

I'm trying to create a simple object "car" animation in Processing. My code is:

Car car;

void setup(){
   size(800, 600);
   background(#818B95);
   frameRate(30);
   
   car = new Car(10,10);
}

void draw(){  
    //refresh background
    background(#818B95); 
    
    print("-");
    car.drawCar();    
}

void mouseClicked() {
  
  car.run();
}

public class Car implements Runnable{
  
  private int pos_x, pos_y;
  
  public Car(int pos_x, int pos_y){
    this.pos_x = pos_x;
    this.pos_y = pos_y;
  }
  
  public void drawCar(){ 
    
    rect(pos_x,pos_y,10,10);
  }
  
  public void run(){
    while(true){
      pos_x += 10;
      print("*");
      delay(200);
    }
  }
}

I'm expecting to see the car/rectangle move right when I click the mouse button, but nothing happens.

I've added the two print in order to see if the draw method and my car.run are executed in parallel showing some * and - printed alternately. What I see is a sequence of - until I click and then only * are printed.

Is it possible that starting a new object thread will stop the main draw cycle?

SOLUTION

This is just a variant of the suggested solution (by Mady Daby) without using threads.

Car car;

void setup(){
   size(800, 600);
   background(#818B95);
   frameRate(30);
   
   car = new Car(10,10);
}

void draw(){  
    //refresh background
    background(#818B95); 
    
    print("-");
    car.drawCar();    
}

void mouseClicked() {
  
  car.moving = true;
}

public class Car{
  
  private int pos_x, pos_y;
  boolean moving = false;
  
  public Car(int pos_x, int pos_y){
    this.pos_x = pos_x;
    this.pos_y = pos_y;
  }
  
  public void drawCar(){ 
    
    rect(pos_x,pos_y,10,10);
    
    //animation 
    if(moving){
      pos_x += 10;
      print("*");
    }
  }
  
}
1 Answers

You could make the car move right by just introducing a boolean variable to track whether the car is supposed to be moving right moving and then increment pos_x if moving is true. You can also use the clicks to toggle between moving and not moving.

Car car;

void setup() {
  size(800, 600);
  background(#818B95);
  frameRate(30);

  car = new Car(10, 10);
}

void draw() {  
  //refresh background
  background(#818B95); 

  print("-");
  car.drawCar();
}

void mouseClicked() {
  car.toggleMoving();
}

public class Car implements Runnable {
  private int pos_x, pos_y;
  private boolean moving = false;

  public Car(int pos_x, int pos_y) {
    this.pos_x = pos_x;
    this.pos_y = pos_y;
  }

  public void toggleMoving() {
    moving = !moving;
  }

  public void drawCar() { 
    if (moving) {
      this.run();
    }
    rect(pos_x, pos_y, 10, 10);
  }

  public void run() {
    pos_x += 10;
    print("*");
    delay(200);
  }
}
Related