Code – lines pointing at mouse w/OOP

Main Sketch:

// declare an array of DirectionLines
DirectionLine lines[];

void setup() {

  //how long will each line be
  int lineLength = 30;

  //we can find out how many lines we will have 
  //by dividing width and height by the lineLength
  int w = width/lineLength;
  int h = height/lineLength;

  //initialize the array with number of total lines
  lines = new DirectionLine[w*h];

  //index to access each element of the array
  int i=0;
  //nested for loop, start at lineLength/2 to offset and center the lines on screen
  //increase each step through the loops by lineLength, to space the lines appropriately
  for (int y=lineLength/2; y<height; y+=lineLength) {
    for (int x=lineLength/2; x<width; x+=lineLength) {
      //access each DirectionLine in the way and create a new DirectionLine object
      //the x & y vairbales from the for loops give us the origin location of each line
      lines[i] = new DirectionLine(x, y, lineLength);
      //be sure to increase i

void draw() {
  //just loop through all the lines and call run()
  for (int i=0; i<lines.length; i++) {


class DirectionLine {

  float angle;
  float len;
  PVector origin;

  DirectionLine(float x, float y, float _len) {
    origin = new PVector(x, y);
    len = _len;


  //update our angle based on the mouse position
  void update() {
    //turn the mouse into a pvector in order to use the pvector functions
    PVector destination = new PVector(mouseX, mouseY);
    //subtract the origin from the destination, this is our direction
    PVector direction = PVector.sub(destination, origin);
    //get the angle of the direction
    angle = direction.heading();

  //draw the line
  void display() {
    //translate and rotate the line based on the angle
    translate(origin.x, origin.y);
    line(0, 0, len, 0);

  //function to wrap up both update and display
  void run() {

Leave a Reply