Newbie question about updating multiple objects ...

fivenastydisco at hotmail.com fivenastydisco at hotmail.com
Thu Jun 8 03:52:17 EDT 2006


All,

Apologies in advance: I'm new to Python and OO, and I'm sure this is a
really simple question, but I just can't seem to crack it on my own, or
through looking at examples. I'm playing around with VPython
(http://www.vypthon.org) to try and teach myself about objects: I've
got a box that I've put some balls in, and I'm trying to get said balls
to move around and bounce off the walls of the box -- that's literally
it. I can put multiple balls in the box, but I can't get them to update
their position -- it works when I have one ball, but now that I have a
list of balls, I can't get them to move.

I've copied in the code I'm using below, as it's not very long -- can
anyone help me?

<--START-->

from visual import *
from random import randrange # to create random numbers

numballs = 5 # number of balls
balls = [] # a list to contain the balls

# set up a box to collide with
side_length = 100
minx = side_length * -10
maxx = side_length * 10
miny = side_length * -4
maxy = side_length * 4

# create a wireframe of space
left = curve(pos=[(minx, miny),(minx, maxy)], color = color.white)
top = curve(pos = [(minx, maxy),(maxx, maxy)], color = color.white)
right = curve(pos = [(maxx, maxy),(maxx, miny)], color = color.white)
bottom = curve(pos = [(maxx, miny),(minx,miny)], color = color.white)

#create some balls
for b in range(numballs): #  for each ball
    x = randrange(minx, maxx)
    y = randrange(miny, maxy)

    balls.append(sphere(pos = (x,y), radius = 50, color = color.red)) #
add balls

dt = 0.05 # time interval
velocity = vector(2,0.2,1) # velocity of the balls

while (1==1): # forever ...
    rate(50)
    for b in range(numballs): # for each ball ...

        if balls[b].x < minx: # check it hasn't overrun a boundary
            balls[b].x = maxx
        if balls[b].x > maxx:
            balls[b].minx
        if balls[b].y < miny:
            balls[b].y = maxy
        if balls[b].y > maxy:
            balls[b].y = miny

        # NB betting this is where it's going wrong ...
        balls[b].pos = balls[b].pos + (velocity * dt) # update the
position of the ball

<--END-->

Any ideas? I've run out of options. Any help would be very *gratefully*
appreciatedd!!

Thanks in advance

JW




More information about the Python-list mailing list