Assignment 3: OOP

The product of this assignment is an extension of assignment 2: I wanted to further develop the code for bouncing ball by using class. The concept of this work is shooting star. Recently, the weather in Abu Dhabi has been so nice and I have been enjoying taking “sky-gaze”. Looking at the night sky and the stars, I thought I could use class to create several stars on P5.

This is the class named Star. Under this class, there is a constructor that determines the position and speed of the star. Also, there are three other instructions that guide the actions of the star (move, bounce, and show). I didn’t encounter any difficulty while constructing class and this process was easier than constructing the code under function draw.

class Star {
  constructor(x,y,xspeed,yspeed) {
    this.x = x;
    this.y = y;
    this.xspeed = xspeed;
    this.yspeed = yspeed;
  }

  move() {
    this.x = this.x + this.xspeed;
    this.y = this.y + this.yspeed;
  }

  bounce() {
    if (this.x > width || this.x < 0) {
      this.xspeed = this.xspeed * -1;
    }

    if (this.y > height || this.y < 0) {
      this.yspeed = this.yspeed * -1;
    }
  }

  show() {
    noStroke();
    fill('rgb(241,241,214)');
    ellipse(this.x, this.y, 15, 15);
  }
}

This is the section of code that I struggled with. Because I wasn’t familiar with some of the code such as interactive, new,  and push, I had to spend extra time to figure out how to use the code. However, once I grasped an understanding of the code by referencing class slide, I could use it to draw interactive stars.

function mousePressed(){
  
  //adding new star
  let interactiveStar = new Star(mouseX, mouseY, random(-5,5), random(-5,5));
  star.push(interactiveStar);

}

This is a portion of code that I am proud of. I learned how to animate objects in P5 using arrow keys by watching this video. The overall process of creating this code was easy but I had to go back and make global variables to be able to animate the object (rocket).

  //moving the rocket up and down
  if (keyIsPressed){
    if (keyCode == UP_ARROW){
      b--;
    } else if (keyCode == DOWN_ARROW){
      b++;
    }
  }
  
  //moving the rocket right and left
  if (keyIsPressed){
    if (keyCode == LEFT_ARROW){
      a--;
    } else if (keyCode == RIGHT_ARROW){
      a++;
    }
}

For improvement, I would like to actually create a star shaped shooting star and not use an ellipse. In this way, a shooting star would be more well-represented.

Leave a Reply