See if you can look through it and understand what's going on. I know it looks like a lot but break it down and it's not so scary. Use the processing reference page if there is a keyword you do not understand. Or write me if you're confused about something specific an can't figure it out.
joester5 at mac.com
void setup(){
size(600, 400);
}
void draw (){
background (50);
smooth();
ballx = ballx + speedx; // calculate ball position
bally = bally + speedy;
collision(); // check to see if ball has collided with an edge or paddle
if (keyPressed) {
if (key == 'j'){
p1xbutton = true; // check for button and chandges a boolean array if it has been pressed
}
if (key == 'm'){
p1ybutton = true;
}
if (key == 'a'){
p2xbutton = true;
}
if (key == 'z'){
p2ybutton = true;
}
}
if (p1xbutton == true){
player1y = player1y - 6;
}
if (p1ybutton == true){
player1y = player1y + 6;
}
if (p2xbutton == true){
player2y = player2y - 6;
}
if (p2ybutton == true){
player2y = player2y + 6;
}
rect(player1x, player1y, 10, 50);
rect(player2x, player2y, 10, 50);
ellipse (ballx, bally, 10, 10);
}
void collision(){
if (((ballx > player1x) && (ballx < player1x + 10)) && ((bally > player1y) && (bally < player1y + 50))){ // if it hits player 1 paddle
if (p1xbutton == true){ // if the paddle is going up puts up "spin" on the ball
speedy -= .5 ;
}
if (p1ybutton == true){// down "spin"
speedy += .5;
}
ballx = player1x - 1; // ensures it won't hit twice!
speedx = speedx * -1; // go back
}
if (((ballx < player2x+ 10) && (ballx > player2x)) && ((bally > player2y) && (bally < player2y + 50))){ // if it hits player 2 paddle
if (p2xbutton == true){ // up "spin"
speedy -= .5 ;
}
if (p2ybutton == true){// down "spin"
speedy += .5;
}
ballx = player2x + 11; // ensures it won't hit twice!
speedx = speedx * -1; // go back
}
if (speedy < -4){// keeps the ball from going too far up and down.
speedy = -4;
}
else if (speedy > 4){
speedy = 4;
}
if (ballx > width){
reset(1); // runs the routine reset below and passes the value 1
}
if (bally > height){
speedy = speedy * -1;
}
if (bally < 0){
speedy = speedy * -1;
}
if (ballx < 0){
reset(2); // runs the routine reset below and passes the value 2
}
}
void keyReleased(){
if (key == 'j'){ // check for button released
p1xbutton = false; // changes the boolean to false, letting the computer know that j is no longer being pressed
}
if (key == 'm'){
p1ybutton = false;
}
if (key == 'a'){
p2xbutton = false;
}
if (key == 'z'){
p2ybutton = false;
}
}
void reset(int plyr){
ballx = 300;
bally = 200;
if(random(2) == 2) { // randomly changes the direction when it restarts
speedx = 2.7;
}
else{
speedx = - 2.7;
}
speedy = (random (.6) - .3);
delay (1000); // pauses at the end for a second
}