Hello. I have once again stumbled across a problem which I couldn’t resolve myself. My Plank does interact with the ball, but only sometimes. And sometimes on the edge the ball just bursts through. I think the problem is somewhere in the Ball class move function. I also noticed it has something to do with the direction the ball is coming down. If you have time, I would really appreciate if someone checked the code and saw for themselves. The game is in the early stages and the code looks messy, but I will fix it later :).
color colbcg;
Plank myPlank;
Ball myBall;
void setup(){
size(500,500);
myPlank = new Plank();
myBall = new Ball();
}
void draw(){
background(colbcg);
myPlank.display();
myPlank.move();
myBall.display();
myBall.move();
}
class Ball{
int xbpos;
int ybpos;
int bw;
int bl;
int xbspeed;
int ybspeed;
int bcol;
Ball(){
xbpos=width/2;
ybpos=393;
bw=width/50;
bl=height/50;
xbspeed=3;
ybspeed=-3;
bcol=255;
}
void display(){
ellipseMode(CENTER);
noStroke();
fill(bcol);
ellipse(xbpos,ybpos,bw,bl);
}
void move(){
ybpos+=ybspeed;
xbpos+=xbspeed;
if(xbpos<5||xbpos>width-5){
xbspeed*=-1;
}if(ybpos<0+5||ybpos>height-5){
ybspeed*=-1;
}if(xbpos>myPlank.xpos-15 && xbpos<myPlank.xpos+15 && ybpos>myPlank.ypos-7.4){
ybspeed*=-1;
}
}
}
class Plank{
int xpos;
int ypos;
int l;
int w;
int col;
Plank(){
xpos = width/2;
ypos = height-(height*1/5);
l = width/10;
w = height/100;
col = 255;
}
void display() {
rectMode(CENTER);
fill(col);
rect(xpos,ypos,l,w);
}
void move(){
if(mousePressed&&mouseButton == LEFT){
xpos = mouseX;
}
if(xpos<0+l/2){
xpos=0+l/2;
}if(xpos>width-l/2){
xpos=width-l/2;
}
}
}
I don’t like this expression although we see it in the examples and everywhere.
The reason is this: whenever the ball stays in the reverse area so that the expression is executed twice, the ball has the previous (wrong) direction again. Bad.
This can lead to stuttering of the ball (or leaving of the ball).
Instead I prefer the expression
ybspeed=abs(ybspeed); OR
ybspeed= - abs(ybspeed);
which is either always positive or always negative.
(Same for xbspeed)
This means even if the ball remains in the reverse
zone the outcome stays stable.
This means that you have to separate all ifs with
|| in it into two separate ifs.