Car controlled by Keys

Hi Everyone,

I am a newbie in processing. I have this mouse attracted object that i am trying to convert into a key arrows controlled algorithm. I want to keep this notion in pointing in the direction of motion but don’t know how to process to do that while keeping the vector logic.

Any idea?

Car c;

void setup(){
  size (600,600);
  
  c = new Car(width/2, height/2);
  
}

void draw(){
  background(255);
  
  c.update();
  c.display();
  c.checkEdges();
}

class Car {
  PVector location;
  PVector velocity;
  PVector acceleration;
  float factor;
  
  Car(float _x, float _y){
    location = new PVector(_x,_y);
    velocity = new PVector(0,0);
    acceleration = new PVector(0,0);
    factor = 20;
  }
  
  void update(){
    PVector mouse = new PVector (mouseX,mouseY);
    PVector dir = PVector.sub(mouse,location);
    
    dir.normalize();
    dir.mult(0.2);
    acceleration = dir;
    
    velocity.add(acceleration);
    velocity.limit(10);
    location.add(velocity);
  }
  
  void display(){
    float angle = velocity.heading();
    
    pushMatrix();
    translate(location.x, location.y);
    rotate(angle);
    noStroke();
    
    fill(0);
    rect(0, -factor/2, factor*1.5, factor/4);
    rect(0, factor/2, factor*1.5, factor/4);
    
    fill(125);
    rectMode(CENTER);
    rect(0, 0, factor, factor*2);
    

    
    popMatrix();
  }
  
  void checkEdges(){
    if(location.x < 0){
      location.x = width;
    } else if (location.x > width){
      location.x = 0;
    }
    if(location.y < 0){
      location.y = height;
    } else if (location.y > height){
      location.y = 0;
    }
  }
}

Thank you,

Rémy

1 Like

http://Studio.ProcessingTogether.com/sp/pad/export/ro.9Nl$898UQxW3Q

2 Likes