Fix code to make spaceship blaster shoot

Why won’t my code work to make my spaceship blaster shoot?

float shipX; // player spaceship
float shipY; // player spaceship 
float enemyX; //enemy UFO
float enemyY; //enemy UFO
float enemySpeed = 2; 
float blastX;
float blastY;

void setup() {
  size (500, 500);
}

void drawSpaceship(float shipX, float shipY) {
  fill (228, 232, 26);
  triangle(shipX, shipY+475, shipX+25, shipY+450, shipX+50, shipY+475);
}
void drawEnemy(float enemyX, float enemyY) {
  rectMode(CENTER);
  ellipse(enemyX, enemyY+250, 30, 20);
  rect(enemyX, enemyY+250, 50, 10);
  enemyX += 1;
}
void moveEnemy() {
  fill (random(200), 0, 0);
  enemyX += enemySpeed;
  if (enemyX > width || enemyX < 0) {
    enemySpeed *= -1;
  }
}
void shootBlaster(float blastX, float blastY) {
  fill(0, 0, 200);
  triangle (blastX, blastY+495, blastX+5, blastY+490, blastX+10, blastY+495);
  if (mousePressed) {
    blastY += -5;
  } // why is this if condition not causing blastY to move? What am I missing?
}

void draw() {
  background(200);
  moveEnemy();
  drawEnemy(enemyX, enemyY); // enemy UFO
  drawSpaceship(mouseX, shipY); // player spaceship at canvas bottom
  shootBlaster(mouseX+20, blastY-20); //this code should shoot a triangle up the canvas
}

You never initialize the variables. Try setting them to a default value.

hi @the-junk, also i don’t see any functions that draw the spaceship shooting or the enemy being destroyed. so for example, i would create another function like destroyEnemy(enemyX, enemyY) with other shapes illustrating destruction of the ship, then test out the logic.:slight_smile: Unless this is not all your code. best of luck

Hi,

The answer is pretty simple. While your vertical value is stored in your public variable blastY, it is still initialized to 0 each frame when your drawSpaceship() function is called because it has a parameter variable with the exact same name. You should only use blastY as a public variable and blastX as a private one.

Just replacing your function by this one will make it work.

void shootBlaster(float x, float y) {
  fill(0, 0, 200);
  triangle (x, blastY+495, x+5, blastY+490, x+10, blastY+495);
  if (mousePressed) blastY += -5;
}
3 Likes