We are about to switch to a new forum software. Until then we have removed the registration on this forum.
So I'm doing pong for a project we are doing in school in processing, but with my code the player's bars keep changing size when I change location! Can someone help me please? Thanks!
//SINGLE PLAYER PONG
//Made by Alex Yang 06/16/2016
//Directions:
//Try to hit the ball back every time.
//This is a 2-player game, so you can use the UP and DOWN keys,
//or the W and S keys.
//UP or W to move your paddle up, DOWN or S to move your paddle down.
//Initialize Variables
boolean gameStart = false;
float x = 150;
float y = 150;
float speedX = random(3, 5);
float speedY = random(3, 5);
int lpaddleColor = 255;
int rpaddleColor = 255;
int radius;
int rectSize = 150;
int paddleX1 = 30;
int paddleX2 = 770;
int paddleY1 = 400;
int paddleY2 = 400;
void setup() {
//Make an 800 by 800 pixel screen
size(800,800);
}
void draw() {
//Make a black background
background(0);
//Divide the screen up into 2 halves by adding a white line
stroke(255);
line(400,0,400,800);
//Make the ball
fill(255);
radius = 20;
ellipseMode(CENTER);
ellipse(x, y, radius, radius);
//Make the paddles
fill(lpaddleColor);
rect(paddleX1, mouseY-250, paddleX1-20, mouseY-175);
fill(rpaddleColor);
rect(paddleX2, paddleY2-325, paddleX2-760, paddleY2-250);
if (gameStart) {
//Ball moves diagonally when game starts.
x = x + speedX;
y = y + speedY;
//If ball hits either paddle, have the X direction go the opposite way.
//Change the color of the paddle when the ball collides with the paddle.
if (x > width-30 && x < width -20 && y > mouseY-rectSize/2 && y < mouseY+rectSize/2 ) {
speedX = speedX * -1;
x = x + speedX;
rpaddleColor = 0;
rectSize = rectSize-10;
rectSize = constrain(rectSize, 10,150);
}
// If ball hits either paddle, change direction of X and have the paddle color flicker gray.
else if ((x < 40) && (y < mouseY+75) && (y > mouseY-75)){
speedX = speedX * -1.1;
x = x + speedX;
lpaddleColor = 128;
}
else {
lpaddleColor = 255;
rpaddleColor = 255;
}
//Reset game when someone misses the ball
if ((x > width) || (x < 0)) {
gameStart = false;
x = 150;
y = 150;
speedX = 4;
speedY = 4;
rectSize = 150;
}
//If ball hits up or down, change direction of Y
if ( y > height || y < 0 ) {
speedY = speedY * -1;
y = y + speedY;
}
//Control the paddles with the UP, DOWN, W, and S keys.
if (key == CODED){
if (keyCode == UP){
paddleY2 = paddleY2 - 4;
} else if (keyCode == DOWN){
paddleY2 = paddleY2 + 4;
}
}
if (key == 'w'){
paddleY1 = paddleY1 - 4;
} else if (key == 's'){
paddleY1 = paddleY1 + 4;
}
}
}
void mousePressed() {
//Start or stop the game whenever the mosue is pressed.
gameStart = !gameStart;
}
Answers
In the rect() for your left paddle, the height of the rectangle should be constant, not change with mouseY. Try changing mouseY - 175 to just 75.
https://processing.org/reference/rect_.html
Thanks!