Trouble with collision of my ball
in
Programming Questions
•
6 months ago
Coding a billiards game for a class project. My goal is to click the mouse once to place a cue ball, again to place a target ball, and then a third click will send the cue ball towards the target ball. When the cue ball collides with the target ball, the cue ball is supposed to stop and the target ball should start moving. The cue ball launches and collides with the target ball but does not stop. Any suggestions?
/////////////////////////////////Code Starts Here////////////////////////////////////////////////////////////////
//Code by D. Witt.
int ballPlaced = 0;
float rise, run;
boolean isLaunched;
Ball cueBall, targetBall;
float currentDist;
boolean hasCollided;
boolean go;
void setup()
{
size(800, 400);
background(0,100,0);
rise = 0;
run = 0;
cueBall = new Ball(-50, -50, color(255,255,255));
targetBall = new Ball(-50, -50, color(255,255,0));
cueBall.isLaunched = false;
targetBall.isLaunched = false;
hasCollided = false;
cueBall.hasTouched = false;
}
void draw()
{
background(0,100,0);
if (ballPlaced > 0)
{
cueBall.display();
}
if (ballPlaced > 1)
{
targetBall.display();
}
if(go){
float distance = dist(targetBall.xpos, targetBall.ypos, cueBall.xpos, cueBall.ypos);
rise = targetBall.ypos - cueBall.ypos;
run = targetBall.xpos - cueBall.xpos;
rise = rise / distance;
run = run / distance;
cueBall.launch(rise, run, distance);
}
if (cueBall.isLaunched)
{
currentDist = dist(targetBall.xpos, targetBall.ypos, cueBall.xpos, cueBall.ypos);
checkCollision(currentDist);
if(hasCollided == false && !cueBall.hasTouched){
cueBall.launch(rise, run, currentDist);
checkCollision(currentDist);
}
else if(hasCollided == true){
cueBall.stopBall();
targetBall.launch(rise, run, currentDist);
}
}
}
void mouseClicked()
{
if (ballPlaced == 0)
{
cueBall.placeBall();
ballPlaced += 1;
}
else if (ballPlaced == 1)
{
targetBall.placeBall();
ballPlaced += 1;
}
else if ((ballPlaced == 2) && (cueBall.isLaunched == false))
{
go = true;
}
}
void keyPressed()
{
if (key == 'c')
{
ballPlaced = 0;
setup();
}
}
void checkCollision(float tempDist){
if(tempDist > 50){
hasCollided = false;
}
else if(tempDist <= 50){
hasCollided = true;
}
}
class Ball{
float xpos;
float ypos;
color currentColor;
boolean isLaunched;
boolean hasTouched;
Ball(float tempX, float tempY, color tempC){
xpos = tempX;
ypos = tempY;
currentColor = tempC;
}
void display(){
ellipse(xpos, ypos, 50, 50);
}
void placeBall(){
xpos = mouseX;
ypos = mouseY;
}
void stopBall(){
hasTouched = true;
}
void launch(float tempRise, float tempRun, float tempDistance){
if(tempDistance > 0){
xpos += run*2.0;
ypos += rise*2.0;
isLaunched = true;
}
}
}
1