We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hey guys,
I got this sketch here : https://www.openprocessing.org/sketch/391671 I want the Circles to bounce of the walls. I made an if statement inside "this.update" to make the circles bounce off the left and right of the canvas, but it doesn't work. Also i'd like the circles to bounce of each other.
var fly;
var sam;
function setup() {
createCanvas(900,600);
background(100);
fly = new Bug(width/2,height/2);
sam = new Bug(100,250);
}
function draw() {
fly.update();
fly.draw();
sam.update();
sam.draw();
}
function Bug(startX,startY) {
this.x = startX;
this.y = startY;
this.diameter = random(10,100);
this.speed = random(2,10);
this.draw = function(){
fill(55);
stroke(255);
ellipse(this.x,this.y,this.diameter,this.diameter);
}
this.update = function() {
this.x += random(-this.speed,this.speed);
this.y += random(-this.speed,this.speed);
if (this.x > 200){
this.speed = this.speed * -1;
console.log("out of canvas right")
}
if (this.x < 200){
this.speed = this.speed;
console.log("out of canvas left")
}
}
}
/*this.bounce = function() {
if (this.x >= width || this.x <= width){
this.speed *= -1;
console.log("test");
}
}*/
Answers
Line 37 and 38 ....
X+=speedx;
Treat speedx and speedy separately!!! You need 2 vars.
Line 45: also '* -1 ' !!!!!
this is wrong. one or the other will be called (unless x is exactly 200).
Yes, first say 400, then 50 or so
Also y is missing
Thanks for your input guys, tried to apply it. But it seems I got it wrong, doesn't work yet. I added the second variable for the y position.
https://www.openprocessing.org/sketch/391671
You're modifying properties x & y before checking out whether they're valid coordinates! :-S
IMO, your sketch is about jittering, not bouncing. :-?
And it would greatly benefit from constrain() me guess: *-:)
http://p5js.org/reference/#/p5/constrain
Thanks GoToLoop and everyone, didn't know the constraint mehtod! But I dont fully understand what happens in line 1, you assign the diameter to the constant rad, but what means ">>1" ?
It's the same as
/2
, but w/ the fractional part removed from result. :\">Ahh okay :) I made now the canvas a square and drew a circle with the same height and width. Now I want to apply the constrain on the circle, but I'm not sure how to proceed. Maybe you can help me out once more.
Every time you update your code, you should post it so we know its current state as well! 8-X
Here is the Code :D
http://codepen.io/Slothside/pen/LbzmKo