The Nature Of Code, Exercise 1.5

edited December 2017 in Hello Processing

Hello everyone, i'm reading "The Nature of Code" and i wanted to know if my solution for the exercise 1.5 could be good. The text says: "Create a simulation of a car (or a runner) that accelerates when you press the up key and brakes when you press the down key"

class Runner {
  PVector location;
  PVector velocity;
  PVector acceleration;

  float topspeed;
  float dim; //width and height of the runner

  Runner() {
    location=new PVector(0+(dim/2), height-(dim/2);
    velocity=new PVector(0, 0);
    acceleration=new PVector(0, 0);
    topspeed=2;
    dim=16;
  }

  void display() {
    stroke(0);
    fill(100);
    ellipse(location.x, location.y, dim, dim);
  }



  void step() {
    if (keyPressed) {
      if (keyCode==UP)
        acceleration.add(new PVector(0.001, 0));
      else if (keyCode==DOWN)
        if (velocity.x<=0)
          runnerStop();
        else acceleration.sub(new PVector(0.005, 0));
    }

    velocity.add(acceleration);
    location.add(velocity);
    velocity.limit(topspeed);
  }

  void checkEdges() {
    if (location.x+(dim/2)>=width) 
      location.x=0+(dim/2);
  }

  void runnerStop() {
    acceleration=new PVector(0, 0);
    velocity=new PVector(0, 0);
  }
}

Runner r;

void setup() {
  size(640, 320);

  r=new Runner();
}

void draw() {
  background(255);
  r.step();
  r.checkEdges();
  r.display();
}

Any suggestion or improvement? Thank you :)

Answers

  • What does this code do? Does it do what you expected? Do you understand how it's working? If the answer to both of those questions is yes, then I wouldn't worry too much about it.

  • As an addition I would suggest adding arguments to your constructor so that when you call a new Runner you can do something like pass it a starting location in the middle of the screen (width/2, height/2 to put it ), or pass it a size to make it easy to see.

Sign In or Register to comment.