top of page
Search
  • Writer's pictureDavid McDonald

Ball bounce on p5.js

It was difficult for me to get the color of the ball to change when it hit the wall but through different methods of experimentation I got it, while getting the ball to go up and down was much easier.


The code I used:


var xPos;

var yPos;

var bsize;


var xSpeed;

var ySpeed;

var sR, sG, Sb;


function setup() {

createCanvas(400, 400);

xPos = random(50,50);

yPos = random(50,50);

xSpeed = 10;

ySpeed=10;

bsize = 50;

sR = 255;

sG = 165;

sB = 0;

sColor = color(sR,sG,sB);

}


function draw() {

background(220);

fill(sColor);

ellipse(xPos, yPos, 50, 50);


xPos = xPos + xSpeed;

yPos = yPos + ySpeed;

if ((xPos > (400-bsize/2)) || (xPos < bsize/2)){

if(yPos < 0){

ySpeed = -ySpeed;

}

if(yPos >400){

ySpeed = -ySpeed;

}

xSpeed= -xSpeed;

ySpeed= -ySpeed;

sColor=('red')

}

/*

if(xPos < 0){

xSpeed = -xSpeed;

if(xPos >400){

xSpeed = -xSpeed

}

//If our Ellipse touches the right edge, bounce back...

//move the opposite direction

if(xPos > 400){

xSpeed = -xSpeed;

}


if(xPos < 0){

xSpeed = -xSpeed;

}*/






}




0 views0 comments

Recent Posts

See All

Interactive drawing Program

At first I wanted to edit the paddleball code to add a function like a boost button, but I ended up preferring the mouseX and mouseY functions so I decided to focus on an interactive drawing program.

Post: Blog2_Post
bottom of page