We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I have created a bouncing ball going back and forth (left to right). It works but I was wondering if there is a way to clean up some of the code to make it more efficient. The print statements are to help me out and the move is set to 50 so I didn't need to scroll through the console to see how it was doing. Move=5 if necessary.
diam=10
move=50
def setup():
size(500,500)
background(50,50,50)
startover()
def startover():
global placementY, x
x=width/2
placementY=int(random(10, 490))
def draw():
global x, move
background(50,50,50)
fill(255)
ellipse(x, placementY, diam, diam)
if x <=0:
print("value of X: ", x)
print("change over from left to right, reached ZERO")
move*=-1
x=x+move
elif (x < width):
print("value of X: ", x)
print("in between everything")
x=x+move
elif (x > 490):
print("made it here to 500: ", x)
move*=-1
x=x+move
Answers
You need to do the same for y so I suggest you write a function named keepinrange for this which changes move (which should be called moveX or so)
I also don't like *-1 and use -abs(move) OR abs(move) instead which is not likely to cause ball stuttering
1) Do you mean so that is can bounce on the ceiling and floor as well, along the y axis?
2) I was thinking about adding a way to make it go at an angle as well, but I haven't figured that out yet.
3) I used the -1 because I wanted it to move the opposite direction. If I use ABS, that will get rid of the negative, right? I am not sure how that would work...
1 yes
2 when you have something to add to y as well we have an angle
3 yeah abs ( move ) always positive, we want this on reflection on the left side
-abs always negative, we want this on the right side
You can encapsulate both the data and the functions which act upon them inside a
class
structure:http://py.Processing.org/reference/class.html
I've just converted a very old Java/JS Cross-Mode bounce sketch example to Python Mode. :bz
Here's its online link: http://Studio.ProcessingTogether.com/sp/pad/export/ro.9oyKfI9kOIa77
Um, if all the of your paths end with
x += move
then you can move that out of the condition.And I second chrisir's directional stuff, don't just flip the direction, that's too prone to errors. (This must be a FAQ by now, surely)
Koogs : great point. I have taken that out of the conditionals and placed it right after where the ellipse is created.
GotoLoop : I know I should be using OOP, but I am not there yet.
Chrisir : I am still trying to wrap my head around the abs stuff. I don't see any stuttering - maybe my monitor? could you be so kind as to show me the code for the abs stuff?
move=abs(move)
move=-abs(move)
Ok, here is the fixed version with the suggestions implemented from Chrisir and Koogs
i would make a function for the collision
also, you don't take into account diam, which means that half of the ball is crossing the border at 0 and at width