Hi there, I am new to Processing and I came up with the idea to make a version of Space Invaders to get acquainted with it. After encountering a lot of trouble with processing simultaneous key inputs I properly took care of the controls. At least that is what I thought. One last problem showed up, being that after pressing multiple keys at the same time and release just one, the other key is ignored. My controls are as follows:
left - move left
right - move right
space - shoot (though this is an early version of the shoot function)
So for instance when I am moving left and press and hold space the character keeps moving left, as it is supposed to do. Then if I release the space bar, the character stops moving altogether, while I am still holding the left arrow. Could anyone take a quick look at my code? Thanks!
int x=456;
int y=670;
int xPos=155;
int yPos=600;
int leftPresses=0;
int rightPresses=0;
boolean left=false;
boolean right=false;
boolean space=false;
void setup(){
size(960,720);
}
void draw(){
//screen
background(0);
//fill(0,0,0);
//noStroke();
//rect(100,75,760,570);
if(space && !left && !right){
fill(255);
stroke(255);
rect(x+23,y-25,3,10);
}
if(!space && left && !right){
x-=1;
}
if(!space && !left && right){
x+=1;
}
if(space && left && !right){
x-=1;
fill(255);
stroke(255);
rect(x+23,y-25,3,10);
}
if(space && !left && right){
x+=1;
fill(255);
stroke(255);
rect(x+23,y-25,3,10);
}
if(left && right){
if(leftPresses>rightPresses){
x+=1;
if(space){
fill(255);
stroke(255);
rect(x+23,y-25,3,10);
}
}
else if(rightPresses>leftPresses){
x-=1;
if(space){
fill(255);
stroke(255);
rect(x+23,y-25,3,10);
}
}
else if(rightPresses==leftPresses){
if(random(1,100)<50){
x+=1;
rightPresses+=1;
if(space){
fill(255);
stroke(255);
rect(x+23,y-25,3,10);
}
}
else{
x-=1;
leftPresses+=1;
if(space){
fill(255);
stroke(255);
rect(x+23,y-25,3,10);
}
}
}
}
//player
fill(0,200,0);
stroke(0,200,0);
rect(x,y,50,10);
rect(x+5,y-3,40,3);
rect(x+20,y-10,10,7);
rect(x+23,y-15,3,5);
//walls
for(int j=0;j<7;j++){
drawWall(xPos+100*j,yPos);
}
}
//declare function keyPressed()
void keyPressed(){
if(key==' '){
space=true;
}
if(keyCode==LEFT){
left=true;
leftPresses++;
}
if(keyCode==RIGHT){
right=true;
rightPresses++;
}
}
//declare function keyReleased()
void keyReleased(){
if(space){
space=false;
}
if(left){
left=false;
leftPresses=0;
}
if(right){
right=false;
rightPresses=0;
}
}
//declare function drawWall
void drawWall(int xWall,int yWall){
rect(xWall,yWall,10,10);
rect(xWall,yWall-10,10,10);
rect(xWall,yWall-20,10,10);
triangle(xWall,yWall-20,xWall+10,yWall-20,xWall+10,yWall-30);
triangle(xWall+10,yWall-10,xWall+10,yWall-20,xWall+20,yWall-20);
rect(xWall+10,yWall-30,10,10);
rect(xWall+20,yWall-30,10,10);
rect(xWall+30,yWall-30,10,10);
triangle(xWall+40,yWall-30,xWall+40,yWall-20,xWall+50,yWall-20);
triangle(xWall+30,yWall-20,xWall+40,yWall-20,xWall+40,yWall-10);
rect(xWall+40,yWall-20,10,10);
rect(xWall+40,yWall-10,10,10);
rect(xWall+40,yWall,10,10);
}