Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

My code below. How do I add Step 5 (in bold) to the code Step 5: Rename the ball variable as balls and initialise it

My code below. How do I add Step 5 (in bold) to the code

Step 5: Rename the ball variable as balls and initialise it as an array. Use a for loop to push 100 balls on it. Within the draw() function use a for loop to call the run() command on each of the balls.

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

var ball;

function setup() {

createCanvas(900, 600);

background(0);

ball = new Ball();

}

function draw() {

//background(0); background should not update

ball.run()

}

class Ball {

constructor() {

var randomX = width/2+random(-100,100);

var randomY = height/2+random(-100,100);

this.velocity = new createVector(0, 0); // speed is now called velocity

this.location = new createVector(randomX, randomY);

this.prevLocation = new createVector(randomX, randomY);

this.acceleration = new createVector(0, 0); // starting in the middle

this.maxVelocity = 5; // maximum velocity

}

run() {

this.draw();

this.move();

}

draw() {

//fill(125);

stroke(255);

strokeWeight(3);

line(this.location.x, this.location.y, this.prevLocation.x, this.prevLocation.y);

this.prevLocation = this.location.copy(); // update previous location

//ellipse(this.location.x, this.location.y, 40, 40);

}

move() {

var mouse = createVector(mouseX, mouseY);

var dir = p5.Vector.sub(mouse, this.location);

dir.normalize();

dir.mult(0.3);

this.acceleration = dir;

this.velocity.add(this.acceleration);

this.velocity.limit(this.maxVelocity); // make sure ball moves within max velocity set in constructor

this.location.add(this.velocity); // speed is now called velocity

}

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access with AI-Powered Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions