Move A Ball Inside Tkinter Canvas Widget (simple Arkanoid Game)
Solution 1:
To move an object you need to use the coords
method or the move
method, which changes the coordinates of the object. You can use the coords
method to get the current coordinates.
To do the animation you can use after
. Call a function, then have it use after
to call itself again a short time in the future. How far in the future will determine your frame rate (ie: every 10ms means roughly 100 frames per second)
For example:
def moveit(self):
# move the object
<get the existing coordinates using the coords method>
<adjust the coordinates relative to the direction of travel>
<give the object new coordinates using the coords method>
# cause this movement to happen again in 10 milliseconds
self.after(10, self.moveit)
Once you call moveit()
just once, the cycle begins. That same method can be used to update more than one object, or you can have different methods for different objects.
edit: You've completely changed your question from "how do I move something on a canvas?" to "why does it move in the wrong direction?". The answer to the latter is simple: you're telling it to move in the wrong direction. Use a debugger or some print statements to see where and how you are calculating delta_y.
Solution 2:
here is a simple hack for this problem:
delta_x = delta_y = 3
while True:
objects = canv.find_overlapping(canv.coords(ball)[0], canv.coords(ball)[1], canv.coords(ball)[2], canv.coords(ball)[3])
for obj in objects:
if obj == 1:
delta_y = -delta_y
if obj == 2:
delta_x = -delta_x
if obj == 3:
delta_x = -delta_x
if obj == 4:
delta_y = -delta_y
new_x, new_y = delta_x, delta_y
canv.move(ball, new_x, new_y)
canv.update()
time.sleep(0.025)
root.bind('<Right>', move_right)
root.bind('<Left>', move_left)
Post a Comment for "Move A Ball Inside Tkinter Canvas Widget (simple Arkanoid Game)"