"if" mechanisms
in
Programming Questions
•
3 years ago
hi everyone, i'm pretty new at processing and I'm tryin to write a little processing Pong game.
In order to understand when the ball hit the racket, I want the programm to test:
1) if the ball is horizontally beyond the racket
2) if 1 is true: test if the ball is vertically over the racket's lowest point
3) if 2 is true to test if the ball is under the racket highest point
4) if 3 is true, the ball is allowed to bounce
-> otherway, you loose the game.
I wrote this in processing but I don't understand why I loose only and just if the ball is 2 is false (if the ball is under the racket limit) while I expected to loose olso if the ball goes beyond th racket limit over the racket itself.
Here is the code I wrote. (the prblem is at line 70).
thanks!
In order to understand when the ball hit the racket, I want the programm to test:
1) if the ball is horizontally beyond the racket
2) if 1 is true: test if the ball is vertically over the racket's lowest point
3) if 2 is true to test if the ball is under the racket highest point
4) if 3 is true, the ball is allowed to bounce
-> otherway, you loose the game.
I wrote this in processing but I don't understand why I loose only and just if the ball is 2 is false (if the ball is under the racket limit) while I expected to loose olso if the ball goes beyond th racket limit over the racket itself.
Here is the code I wrote. (the prblem is at line 70).
- //ball position
float xBar = 20;
float yBar = mouseY;
// ball speed
float hSpeed = 10;
float vSpeed = random(5);
// bot position
float yBot = 0;
void setup() {
size(1000,500);
noCursor();
}
void draw() {
background(0);
stroke(0,255,0);
fill(0,255,0);
strokeWeight(1);
line(width/2, 0, width/2, height);
strokeWeight(2);
line(10,mouseY-20,10, mouseY+20); //player
line(width-10,yBot-20, width-10, yBot+20); //bot
rectMode(CENTER); //ball
rect(xBar, yBar, 5, 5);
xBar = xBar + hSpeed;
yBar = yBar + vSpeed;
// bot mistake
float ran = random(6);
if(ran > 0.5) {
yBot = yBar;
}
else {
yBot = 0;
}
// bot bounce
if (xBar > width-15) {
if(yBar < yBot+20) {
if(yBar > yBot-20) {
xBar = width-15;
hSpeed= -hSpeed;
}
}
else {
win();
}
}
// vertical bounce
if(yBar > height-5) {
yBar = height-5;
vSpeed = -vSpeed;
}
if(yBar < 5) {
yBar = 5;
vSpeed = -vSpeed;
}
//bounce angolation
float diff = mouseY-yBar;
// player bounce
if(xBar < 15) {
if(yBar < mouseY+20) {
if(yBar > mouseY-20) {
xBar = 15;
hSpeed= -hSpeed;
vSpeed= -0.2 * diff;
}
/*else {
loose();
}*/
}
else {
loose();
}
}
}
//mouse click -> restart the game
void loose() {
noLoop();
println("end program");
text("YOU LOOSE",width/2-40,height/2);
text("CLICK TO RESTART",width/2-60,height/2+15);
}
void win() {
noLoop();
println("end program");
text("YOU WIN",width/2-30,height/2);
text("CLICK TO RESTART",width/2-60,height/2+15);
}
void mousePressed() {
println("program restart");
xBar=10;
yBar = mouseY;
//hSpeed = 5;
vSpeed = random(7);
loop();
draw();
}
thanks!
1
