0
My code restarts at the beginning. How can I make it bounce?
I want my code to have the boxes bounce off the wall and go back and forth. Right now, when it hits the wall it restarts and goes again. I’d appreciate any help. Been stuck on this one. https://code.sololearn.com/W6yAnGFTfSac/?ref=app
2 ответов
+ 3
You had the right idea. On line 7 you add 1 to posBox, but once you want to change direction, you actually need to subtract 1.
So I would make a variable `delta = 1;` somewhere at the top, and then replace `posBox += 1;` with `posBox += delta;`
Then, on line 10, replace `posBox = posBox * -1;` with `delta = delta * -1;` and it should do what you want!
+ 4
I think you probably didn't understand Kirk's response in your original post completely: https://www.sololearn.com/Discuss/1575746/?ref=app
The idea is to use a variable "velocity", initialized as 1. In line 7 and line 20, increment the posBox and posContainer by velocity. When you hit a wall, just change velocity to -velocity. (velocity *= -1)