Hi everyone, I’m unsure on how to code collision detection in processing. I have watched tutorials on YouTube however they mainly show collision detection of changing colour rather than making the object disappear once it hits. Also, I would like to know how to do it without using classes. This is my code so far.
int x = 30;
int y = 60;
float gunX = x+20;
float gunY = y+20;
float circleY;
float circleX;
float circleRadius;
float circleDiameter;
boolean bulletFlies=false;
float bulletX;
float bulletY;
void setup() {
size(500, 500);
circleY = random(25, 480);
circleX = 450;
circleRadius = 80;
circleDiameter = circleRadius * 2;
}
void draw() {
background(0);
fill(255, 56, 99);
ellipse(x, y, 60, 60);
ellipse(bulletX, bulletY, 6, 6);
gunY = y;
fill(255);
circle(circleX, circleY, circleDiameter);
circleX=circleX-0.5;
bullet();
}
void keyPressed() {
if (key == 's') y = y + 8;
else if (key == 'w') y = y - 8;
else if (key == ' ') {
if (!bulletFlies) {
bulletFlies=true;
bulletX = gunX+14;
bulletY = gunY+4;
}
}
}
void bullet() {
if (bulletFlies) {
//check the bullet hasn't left the screen
if (bulletX > width) {
bulletFlies = false;
return;
}
bulletX = bulletX+5;
//calculate the distance between the bullet and the circle
float dx = bulletX - circleX;
float dy = bulletY - circleY;
float dist = sqrt(dx * dx + dy * dy);
if (dist < circleRadius) {
bulletFlies = false;
}
}
}int x = 30;
int y = 60;
float gunX = x+30;
float gunY = y+30;
float circleY;
float circleX;
boolean bulletFlies=false;
float bulletX = 30;
float bulletY = 30;
//--------------------------------------------------------------------
void setup() {
size(500, 500);
circleY = random(20,460);
circleX = 450;
}//func
void draw() {
background(0);
// player / cannon
fill(255, 56, 99);
ellipse(x, y, 60, 60);
fill(255);
circle(circleX,circleY, 80);
circleX=circleX-0.5;
// GUN
fill(255, 56, 99); // RED
noStroke();
gunX = x+12;
gunY = y;
rect(gunX, gunY, 14, 16);
// bullet
bullet();
}//func
//--------------------------------------------------------------------
void keyPressed() {
if (key == 's') y = y + 8;
else if (key == 'w') y = y - 8;
else if (key == ' ') {
if (bulletFlies)
return;
bulletFlies=true;
bulletX = gunX+14;
bulletY = gunY+4;
}//else if
}//func
void bullet() {
if (bulletFlies) {
fill(255); // WHITE
ellipse(bulletX, bulletY, 6, 6);
bulletX = bulletX+4; // speed
// bullet stops
if (bulletX>width+12) {
bulletFlies=false;
}
}
}