Having a bit of trouble with the logic of my program
in
Programming Questions
•
6 months ago
I'm making a Billiards game for a project for my university. Right now I have a class named Ball that I use for both my cueBall and targetBall objects. Right now I have the variables centerX1 and centerY1 for the cueBall object and centerX2 and centerY2 for the targetBall object. I want to set the place x and y coordinates of where the mouse clicks the first time to be the x and y of my cueBall object. I want the second click to set the x and y coordinates for my targetBall object. I think the problem may have something to do with the parameters I'm initializing the objects of cueBall and targetBall with in setup(). Any suggestions on improving my code are appreciated. :)
//////////////////////////////Beginning of Code////////////////////////////
//Code by D. Witt.
int ballPlaced = 0;
float centerX1, centerY1, centerX2, centerY2;
float rise, run;
boolean isLaunched;
Ball cueBall, targetBall;
float currentDist;
void setup()
{
size(800, 400);
background(0,100,0);
rise = 0;
run = 0;
cueBall = new Ball(centerX1, centerY1, color(255,255,255));
targetBall = new Ball(centerX2, centerY2, color(255,255,0));
isLaunched = false;
}
void draw()
{
background(0,100,0);
if (ballPlaced > 0)
{
cueBall.display();
}
if (ballPlaced > 1)
{
targetBall.display();
}
if (isLaunched)
{
currentDist = dist(centerX2, centerY2, centerX1, centerY1);
while(currentDist > 100){
cueBall.launch();
}
if(currentDist <= 100){
targetBall.launch();
}
}
}
void mouseClicked()
{
if (ballPlaced == 0)
{
centerX1 = mouseX;
centerY1 = mouseY;
ballPlaced += 1;
}
else if (ballPlaced == 1)
{
centerX2 = mouseX;
centerY2 = mouseY;
ballPlaced += 1;
}
else if ((ballPlaced == 2) && (isLaunched == false))
{
isLaunched = true;
rise = centerY2 - centerY1;
run = centerX2 - centerX1;
float distance = dist(centerX2, centerY2, centerX1, centerY1);
rise = rise / distance;
run = run / distance;
}
}
void keyPressed()
{
if (key == 'c')
{
ballPlaced = 0;
isLaunched = false;
}
}
class Ball{
float currentX;
float currentY;
float xpos;
float ypos;
color currentColor;
Ball(float tempX, float tempY, color tempC){
xpos = tempX;
ypos = tempY;
currentColor = tempC;
}
void display(){
ellipse(xpos, ypos, 50, 50);
}
void launch(){
xpos += run*2.0;
ypos += rise*2.0;
}
}
1