Warm tip: This article is reproduced from serverfault.com, please click

Graphics.py circle won't bounce off walls

发布于 2020-11-29 23:22:54

I am trying to get a ball to bounce off of the walls of my bounds. Currently, my circle is supposed to hit the wall and then change velocities and move in the opposite direction but this is not happening. I would appreciate some help :) Thank you

from graphics import*
from random import*
from time import*

win = GraphWin('My Program', 600, 600)
win.setBackground('pink')
my_circle = Circle(Point(200,300),30)
my_circle.setFill('blue')
my_circle.setOutline('darkorchid1')
my_circle.draw(win)

key = win.checkKey()
while key == '':  
    
    vel_x = randint(-30,30)
    vel_y = randint(-30,30)
    my_circle.move(vel_x, vel_y)
    sleep(0.1)
    
    
    for bounce in range(600):
    
        find_center = my_circle.getCenter()
        center_x = find_center.getX()
        center_y = find_center.getY()
        
        if center_x == 600 or center_y == 600:
            vel_x = -randint(30,-30)
            vel_y = -randint(30,-30)
            my_circle.move(vel_x, vel_y)
            sleep(0.1)
    key = win.checkKey()
Questioner
lizzie_lolz
Viewed
0
IsolatedSushi 2020-11-30 08:00:51

Several things that may affect the problem.

  1. You should set your velocities once, as you're doing in the first lines in the while loop. Whenever it bounces you should move in the opposite direction using vel_x = -vel_x and vel_y = -vel_y.

  2. Right now you're updating both of velocities which might lead to some wierd bounces when only one of the centeres hits a wall.

  3. It might be more logical to check wether the distance from the center to the wall is less than the radius of the circle. This will prevent the issue when the ball moves from x=599 to x=601 in one iteration, skipping the if statement. (This would also make it so that the circle bounces when its edge hits the wall instead of the center)

  1. Currently you're only checking 2 walls, unless you meant to do this you should add the if statements for the other walls aswell.
  1. Small other thing, the second time you draw the random velocities you draw from the range 30 to -30, which is invalid.