Hello! I’m a bit stuck with my conditional statement for this basic program I’m working on. Two objects at different y coordinates start moving towards the width of the screen at varying speeds. When they approach each other at a specific distance, both objects need to slow down and once they get past that distance, their original speed also returns.
Here’s the function I created to compute the distance between the objects and adjust the speed accordingly:
void closingDist(Bubble other) {
float d = dist(xpos, 0, other.xpos, 0); //declared a float d which computes the distance between the xpos of the two objects
if (d <= 4) { //made a conditional statement dependent on the value of d
xspeed--; //if d<=4 (ie if the objects are within 4 pixels horizontally), speed will slow down
//having a problem since both bubbles start of at the place and the bubble just starts going backwards or just maintains that speed
stroke(255, 0, 0);
line(xpos, ypos, other.xpos, other.ypos);
}
}
I also tried multiplying the speed by a percentage but it never returns to the original speed even when the distance is more than 4 pixels. I believe my condition works since the part of the code that connects the two bubbles when in the same range works but I’m just stuck with how I can adjust the speed.
Any clarifications would be greatly appreciated.
Oh sorry! I didn’t think it was necessary at first because I thought I only need to compute the distance between the x coordinates so I set it to 0. Noob mistake.
Unfortunately, the instructions for the project require that the objects must slow down once they’re within 4 pixels of each other so I don’t really know how I should work around that.
Apologies if I used the wrong terms–I’m still familiarizing myself with the concepts!
Thank you for your reply! I tried doing that but I don’t know how I can return the original value when it uses a value that was put in my main line of code (this function was written in my class). xspeed = xspeed as an else - statement, for example, shows the error that it has no effect. I’ve written in a previous reply the arguments for the constructor that I made if that helps.
To have this in your constructor won’t help, since it is called only once and not throughout. You need to repeat this line, eg in an else-part of your if-clause
It’s alright!! I tried doing your earlier advice about changing the condition from 4 since it’s too small to actually see the difference and you’re right! I also added a new variable that replaces xspeed (slows it down to half its value). Thank you so much for helping me!