Reputation: 33
I am trying to make the ball infinite bounce from the right to the left but I can't get it to work. The code downbelow makes it that the ball will go to the right and back to the left but I can't get it to bounce back again to the right. someone has any ideas how to fix this?
var speed = 3;
var ball = {
x: 100,
y: 200,
draw: function() {
fill('red');
circle(this.x, this.y, 100);
},
move: function(){
if(this.x > width){
speed = -3;
}
this.x = this.x + speed;
}
}
function setup() {
createCanvas(500, 500);
background(200, 225, 200);
}
function draw() {
background(200,225,200);
ball.draw();
ball.move();
}
P.S. This is my first post please tell me if I am doing something wrong or need to add anything.
Upvotes: 2
Views: 1629
Reputation: 211277
You have to invert the direction of movement (speed *= -1
), if the ball either hits the right (this.x > width
) or hits the left (this.x < 0
):
let radius = 50;
if (this.x > width-radius || this.x < radius ) {
speed *= -1;
}
See the example:
var speed = 3;
var ball = {
x: 100,
y: 200,
radius: 50,
draw: function() {
fill('red');
circle(this.x, this.y, this.radius*2);
},
move: function(){
if (this.x > width-this.radius || this.x < this.radius) {
speed *= -1;
}
this.x = this.x + speed;
}
}
function setup() {
createCanvas(500, 500);
background(200, 225, 200);
}
function draw() {
background(200,225,200);
ball.draw();
ball.move();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>
Upvotes: 3