We are about to switch to a new forum software. Until then we have removed the registration on this forum.
drawing a gun that shoots bullets but i don't want all the bullets to appear at the same time.
final float SPEED = 2; // creates global constant for the speed the gun will move
final float BULLET_SPEED = 4;
final int GUN_WIDTH = 30; // creates global constant for the width of the gun
final int GUN_HEIGHT = 50; // creates global constant for the height of the gun
int centerX,centerY;
float posX,posY;
float trianglePos1X,trianglePos2X,trianglePos3X;
float trianglePos3Y;
float bulletDiam = 10;
float bulletX, bulletY;
boolean bullets = false;
float x,y;
void setup(){
size(500,500);
centerX = width/2;
centerY = height/2;
posX = centerX - GUN_WIDTH/2;
posY = height - GUN_HEIGHT;
}
void draw(){
background(200);
drawShot();
moveShot();
drawGun();
moveGun();
}
void moveGun(){
if(keyPressed && (key == CODED)){
if((keyCode == LEFT) && ( posX > 0 )){
posX = posX - SPEED;
} // bracket for LEFT
if((keyCode == RIGHT) && ( trianglePos2X < width)){
posX = posX + SPEED;
} // bracket for RIGHT
} // bracket for CODED
} // bracket for moveGun
void drawGun(){
trianglePos1X = posX;
trianglePos2X = posX + GUN_WIDTH;
trianglePos3X = posX + GUN_WIDTH/2;
trianglePos3Y = posY - GUN_WIDTH;
fill(255);
rect(posX , posY, GUN_WIDTH,GUN_HEIGHT);
triangle( trianglePos1X ,posY, trianglePos2X , posY , trianglePos3X, trianglePos3Y);
}
void mousePressed(){
bulletY = posY;
bulletX = trianglePos3X;
}
void drawShot(){
int i = 0;
while ( i < 320) {
ellipse (bulletX, bulletY + i, bulletDiam, bulletDiam);
i = i + 40;
}
if((bulletY - bulletDiam/2) < 0 )
background(200);
}
void moveShot(){
bulletY = bulletY - BULLET_SPEED;
}
Answers
You really should write a class for your Bullets.
See:
From several variables to arrays
From several arrays to classes
From Here:
https://forum.processing.org/two/discussion/8093/frequently-asked-questions#latest
I havent been taught or instructed to use arrays or classes so i need to still with just the while loop
Don't use keyPressed (the variable) use keyPressed () (the method). The first will be true 60 times a second, the second will be true once for every ever key pressed.
See reference.
why would i change the keypressed when im not using it for the bullets?
No arrays? No classes? UGH. Fine. You can still do it long-hand... but you're going to be limited to a specific number of bullets at once.
// Well, you can do the rest.
Or, with an array...
Convince yourself that this is a better way to do things. It's SO VASTLY MUCH BETTER, in fact, that YOU SHOULD DO THIS EVEN IF YOU HAVEN'T BEEN TAUGHT ARRAYS YET. Like, literally, LEARN THEM so you can do it this way!