Issues with ball intersecting example from book Algorithms chapter 10
in
Programming Questions
•
10 months ago
I'm trying to do the example from the book on algorithm in the intersection part for some reason when my balls intersect they are not being highlighted was wondering if somebody can tell me where I'm going wrong
- //Global Variables
//------------------\\
Catcher myCatcher;
Ball ball1;
Ball ball2;
//------------------\\
void setup(){
size(1000,700);
myCatcher = new Catcher();
ball1 = new Ball(64);
ball2 = new Ball(32);
smooth();
}
void draw(){
background(0);
myCatcher.display();
myCatcher.moveRight();
myCatcher.moveLeft();
myCatcher.moveUp();
myCatcher.moveDown();
ball1.move();
ball2.move();
if (ball1.intersect(ball2)){
ball1.hightlight();
ball2.hightlight();
}
ball1.display();
ball2.display();
}
void keyPressed(){
if (key == CODED) {
if (keyCode == RIGHT && myCatcher.catcherX < width - 50){
myCatcher.moveRight();
}
if (keyCode == LEFT && myCatcher.catcherX > 0){
myCatcher.moveLeft();
}
if (keyCode == UP && myCatcher.catcherY > 0){
myCatcher.moveUp();
}
if (keyCode == DOWN && myCatcher.catcherY < height -50){
myCatcher.moveDown();
}
}
}
class Ball{
float r; //radius
float x,y; //location
float xspeed,yspeed; //speed
color c = color(100,50); // color
//constructor
Ball(float tempR){
r = tempR;
x = random(width);
y = random(height);
xspeed = random(-5,5);
yspeed = random(-5,5);
}
void move(){
x += xspeed; //Inrements x
y += yspeed; //Increments y
// check horizontal edges
if(x > width || x < 0){
xspeed *= -1;
}
// check vertical edges
if(y > height || y < 0){
yspeed *= -1;
}
}
//highlight whenever balls are touching
void hightlight(){
c = color(255,0,0);
}
//Draw Ball
void display(){
stroke(255);
fill(100,50);
ellipse(x,y,r*2,r*2);
c = color(100,50);
}
//A function that returns true or false based on whether two circle intersect
//If distance is less than the sum of radii the circles touch
boolean intersect(Ball b){
float distance = dist(x,y,b.x,b.y); //calculate distance
if (distance < r + b.r){ //compare distance to sum of radius
return true;
}
else{
return false;
}
}
}
1