Source
let ball;
function setup() {
createCanvas(600, 600);
ball = new Ball(100, 100, 25, "red");
}
function draw() {
background(255);
ball.draw();
ball.applyForce(createVector(0,2));
ball.update();
noFill();
stroke("black");
rect(0,0,width, height);
}
class Ball {
constructor(x, y, radius, color) {
this.radius = radius;
this.mass = radius;
this.color = color;
this.position = createVector(x, y);
this.velocity = createVector(1,0);
this.force = createVector(0,0);
}
applyForce(force){
this.force.add(force);
}
update(){
const acceleration = p5.Vector.div(this.force, this.mass);
this.force.x = 0;
this.force.y = 0;
this.velocity.add(acceleration);
this.position.add(this.velocity);
if ((this.position.x - this.radius< 0 && this.velocity.x < 0)
|| (this.position.x + this.radius >= width && this.velocity.x > 0)){
this.velocity.x *= -.9;
}
if ((this.position.y - this.radius < 0 && this.velocity.y < 0)
|| (this.position.y + this.radius >= height && this.velocity.y > 0)){
this.velocity.y *= -.9;
}
this.position.x = min(width - this.radius, max(this.radius, this.position.x));
this.position.y = min(height - this.radius, max(this.radius, this.position.y));
}
draw(){
fill(this.color);
circle(this.position.x, this.position.y, this.radius*2);
}
}