We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I need help getting the ball to bounce off the paddles using a get function.
Paddle left;
Paddle right;
int leftPoints=0;
int rightPoints=0;
int x, y;
int Y = 0;
int p=255;
//variables for speed of ball
int xspeed=7;
int yspeed=7;
float changeX, changeY;
float r=0;
float g=0;
float b=0;
boolean keyPressed=false;
void setup()
{
size(800, 600);
smooth();
frameRate(60);
bob=new Ball();
left=new Paddle();
right=new Paddle();
}
void draw()
{
background(0);
bob.move();
bob.bounce();
bob.show();
left.left();
left.setY(Y);
right.right();
stroke(#08ECFF);
line(width/2, 0, width/2, height);
textSize(40);
text(leftPoints, 330, 100);
text(rightPoints, 445, 100);
}
void keyPressed() //movement for player
{
if (key =='w')
{
Y = Y - 15;
} else if (key=='s')
{
Y = Y + 15;
} else
{
Y=Y;
}
}
class Paddle
{
int x, y;
boolean up, down;
void left()
{
fill(255);
noStroke();
rect(15, y, 25, 100);
}
void right()
{
fill(255);
noStroke();
rect(760, mouseY, 25, 100);
}
void setY(int newY)
{
y = newY;
}
}
class Ball
{
int x, y;
boolean xd;//right
boolean yd;//up
Ball()
{
x=400;
y=100;
xd = true;
yd = true;
}
void bounce()
{
int minY=5;
int maxY=580;
{
if (y>maxY)
{
yd = false;
} else if (y<minY)
{
yd = true;
}
}
if (get(x+21, y)==color(255))
{
yspeed*=-1;
xd=false;
}
if (get(x-21, y)==color(255))
{
yspeed*=-1;
xd=false;
}
}
void move()
{
if (xd == true)
{
x = x + 4;
} else
{
x = x - 4;
}
if (yd == true)
{
y=y + 4;
} else
{
y = y - 4;
}
if (x>=780)
{
xd = false;
leftPoints++;
x=400;
}
if (x<=10)
{
xd = true;
rightPoints++;
x=400;
}
}
void show() //the ball
{
stroke(0);
fill(r, g, b);
r=random(0, 255);
g=random(0, 255);
b=random(0, 255);
rect(x, y, 20, 20);
}
}
Answers
Please learn how to format your code properly for posting on this forum. Highlight your code and hit Ctrl-k or the C button above the text entry box.
"using a get function"
Why? Since you have the geometry of the paddles and of the ball, you don't need no get function to check for collision.
apart from the get function that gets you a color, the get can also mean a function / method within the class that delivers you data - e.g. left.getY() etc. etc.
thus the paddle would give out its upper Y and you can check this is the ball class?
;-)