问题
I am currently studying computer science in university doing a foundation year, so I'm new to programming, we are doing a python unit and I'm doing my own project outside of the course content.
I've been trying to make a bouncing ball animation using Tkinter. However I have two balls, red and green, for some reason they don't seem to touch the top or left side of the canvas before the bouncing, and the distance from the edge seems to constantly increase.
from tkinter import *
import random
import time
root = Tk()
def balls():
#speeds
xspeed = 5
yspeed = 3
canvas = Canvas(root, width = 1000, height = 1000, bg="grey")
root.title("collision detection")
canvas.grid()
greenBall = canvas.create_oval(5, 5, 35, 35, fill="green")
redBall = canvas.create_oval(970, 970, 1000, 1000, fill="red")
while True:
#greenball
canvas.move(greenBall, xspeed, yspeed)
posgreen = canvas.coords(greenBall)
if posgreen[3] >= 1000 or posgreen[1] <= 0:
yspeed = -yspeed
if posgreen[2] >= 1000 or posgreen[0] <= 0:
xspeed = -xspeed
#redball
canvas.move(redBall, -xspeed, -yspeed)
posred = canvas.coords(redBall)
if posred[3] >= 1000 or posred[1] <= 0:
yspeed = -yspeed
if posred[2] >= 1000 or posred[0] <= 0:
xspeed = -xspeed
root.update()
time.sleep(0.01)
pass
balls()
root.mainloop()
I have seen youtube videos of people showing how to do this and they seem to code it the same way but dont have this issue.
回答1:
I made some modifications in you code. Problem was in speed definition, in you code speed is changed globally 2 times instead of each time for each ball. Here you go:
from tkinter import *
import time
root = Tk()
def balls():
# define speed for each ball
green_x_speed, green_y_speed = [5,3]
red_x_speed, red_y_speed = [5,3]
canvas = Canvas(root, width=800, height=800, bg="grey")
root.title("collision detection")
canvas.grid()
green_ball = canvas.create_oval(20, 20, 30, 10, fill="green")
red_ball = canvas.create_oval(780, 780, 790, 790, fill="red")
while True:
# green ball
canvas.move(green_ball, green_x_speed, green_y_speed)
green_coordinates = canvas.coords(green_ball)
if green_coordinates[3] >= 800 or green_coordinates[1] <= 0:
green_y_speed = -green_y_speed
if green_coordinates[2] >= 800 or green_coordinates[0] <= 0:
green_x_speed = -green_x_speed
# red ball
canvas.move(red_ball, red_x_speed, red_y_speed)
red_coordinates = canvas.coords(red_ball)
if red_coordinates[3] >= 800 or red_coordinates[1] <= 0:
red_y_speed = -red_y_speed
if red_coordinates[2] >= 800 or red_coordinates[0] <= 0:
red_x_speed = -red_x_speed
time.sleep(0.01)
root.update()
balls()
root.mainloop()
来源:https://stackoverflow.com/questions/59988214/tkinter-bouncing-ball