how to make an object disappear upon collision

edited December 2014 in Questions about Code

How do I get the objects (Asteroids) to disappear when they contact the base object (alien) and reappear in another place?

HELP!!

PImage space, alien, asteroid, asteroid2;
PFont font;
int base = 225; //where the asteroid hits the alien
int x, y, x1, y1, gameScore = 0;
int changeX = -3;
int changeY = -3;
int gameOver = 0;


void setup() {
//background of space image
  space = loadImage("space.jpg");
  size(space.width, space.height); //Dimensions: 1131 x 707

 // whirl = loadImage("whirl.jpg");
 // size(space.width, space.height);

//variables for images  
  x = (int)random(width);
  y = height-base;
  x1 = (int)random(width);
  y1 = height-base; 

//alien image
  alien = loadImage("alien.png"); 
//asteroid images
  asteroid = loadImage("asteroid.png");
  asteroid2 = loadImage("asteroid2.png");
}


void draw() {
  if(gameOver==0) {
  background(space); 

//font and score   
  font = loadFont("Candara-Bold-48.vlw");
  textFont(font);
  fill(255);
  text("score: "+gameScore, width - 200, height - 50);

//alien moving   
  image(alien, mouseX, 520);

//asteroid bouncing  
  image(asteroid, x, y);
  image(asteroid2, x1, y1);

  x = x + changeX;
  y = y + changeY;


  if (x < 0 | x > width) {
    changeX = -changeX;

  }
  if (y < 0) {
    changeY = -changeY;
  }

  if (y > height-base) {
    //check whether it is falling inside space or not
    if (x > mouseX && x < mouseX + 200) {
      changeY = -changeY; //bounce back
      gameScore++;
    }

    else {
      gameOverSplash();
    }
  }


  x1 = x1 + changeX;
  y1 = y1 + changeY;


  if (x1 < 0 | x1 > width) {
    changeX = -changeX;

  }
  if (y1 < 0) {
    changeY = -changeY;
  }

  if (y1 > height-base) {
    //check whether it is falling inside space or not
    if (x1 > mouseX && x1 < mouseX + 200) {
      changeY = -changeY; //bounce back
      gameScore++;
    }

    else {
      gameOverSplash();
    }
  }
 }

//game over and restart function
  else {
    background(0);
    text("Game Over!",width/2,height/2);
    text("CLICK TO RESTART",width/2,height/2+50);
  }
}


void gameOverSplash() {
  gameOver=1;
}


void mouseClicked() { //click the black screen or double click the regular screen to restart the game
  changeY=-changeY;
  gameScore=0;
  gameOver=0;

Answers

  • Start by formatting your code correctly on the forums. Edit your post, highlight code, hit Ctrl-K.

  • To make an object to disappear... you just stop drawing them! You have have a boolean variable (per object) telling if it must be displayed or not.

    To make it to reappear somewhere else, just toggle again the boolean, after changing the coordinates of the object.

Sign In or Register to comment.