We are about to switch to a new forum software. Until then we have removed the registration on this forum.
int p1x, p1y;
int p2x, p2y;
int ballx, bally, ballvx, ballvy;
void setup() {
size(1000, 1000);
p1x=25;
p1y=height/2;
p2x=width-25;
p2y=height/2;
ballx=width/2;
bally=height/2;
int r=(int)(random(0, 1));
if (r==0) {
ballvx=-1;
} else {
ballvx=1;
}
int ra=(int)(random(0, 1));
if (ra==0) {
ballvy=-1;
} else {
ballvy=1;
}
}
void draw() {
background(255/2+50);
ellipse(ballx, bally, 25, 25);
ballx+=ballvx;
bally+=ballvy;
if ((ballx>=p1x&&ballx<=p1x-25)||(ballx>=p2x+25&&ballx<=p2x-25)&&(bally>=p1y+25||bally<=p1y-25||bally>=p1y+25||bally<=p1y-25))
{
ballvx=-ballvx;
println("deflected");
}
if (((bally>=p1y+25&&bally<=p1y-25)||(bally>=p2y+25&&bally<=p2y-25))&&(ballx<=p1x||ballx>=p2x)||(bally>=height+25||bally<=25))
{
ballvy=-ballvy;
println("deflected");
}
if(ballx<=0||ballx>=height-25){
textSize(50);
fill(255,0,0);
text("YOU LOST",width/2,height/2);
}
rect(p1x, p1y, 10, 50);
rect(p2x, p2y, 10, 50);
}
void keyPressed() {
if (keyCode=='W')
{
p1y+=5;
println("paddle 1 increasing");
}
if (keyCode=='S') {
p1y-=5;
println("paddle 1 decreasing");
}
if (keyCode=='Y')
{
p2y+=5;
println("paddle 2 increasing");
}
if (keyCode=='H') {
p2y-=5;
println("paddle 2 decreasing");
}
}
so the problem that i am encountering is that the if statement randomly deflects the ball so i added (ballx<=p1x||ballx>=p2x)
to the y section. can someone rewrite the if statements for me or just tell me how to
Answers
Please explain this to us
Do line numbers 19 and 27 work? Do you get different results for ballvx and y?
In line 45 write a function and treat ball paddle collision for each paddle separately, not in one if.
Try to write functions for the other parts of draw() too