Today i started an activity called scientific programming at college, which is an extra activity that visual python to program movement, momentum, etc. Well, i finished an activity today, but think i could shorten the code a bit.
#Importing Visual
from visual import*
#Generates the ball's and right, left, ceiling, floor, and back walls
ball1 = sphere(pos=(0,0,0), radius=0.5, color=color.yellow)
ball2 = sphere(pos=(0,1,0), radius=1, color=color.red)
ball3 = sphere(pos=(0,0,0), radius=2, color=color.blue)
wallR = box(pos=(6,0,0), size=(0.2,12,12), color=color.green)
wallL = box(pos=(-6,0,0), size=(0.2,12,12), color=color.green)
wallC = box(pos=(0,6,0), size=(12,0.2,12), color=color.green)
wallB = box(pos=(0,0,-6), size=(12,12,0.2), color=color.red)
wallF = box(pos=(0,-6,0), size=(12,0.2,12), color=color.green)
#Sets the time interval to 0.05 and velocity to (1,1.5,2)
dt=0.05
ball1.velocity = vector(1,1,2)
ball2.velocity = vector(2,4,1)
ball3.velocity = vector(1,2,3)
while (1==1):
#Ball1 collision controlls
rate(100)
ball1.pos = ball1.pos + ball1.velocity*dt
if ball1.pos.x > wallR.pos.x:
ball1.velocity.x = -ball1.velocity.x
if ball1.pos.x < wallL.pos.x:
ball1.velocity.x = -ball1.velocity.x
if ball1.pos.y > wallC.pos.y:
ball1.velocity.y = -ball1.velocity.y
if ball1.pos.y < wallF.pos.y:
ball1.velocity.y = -ball1.velocity.y
if ball1.pos.z < wallB.pos.z:
ball1.velocity.z = -ball1.velocity.z
if ball1.pos.z > 6:
ball1.velocity.z = -ball1.velocity.z
#Ball2 collision controlls
ball2.pos = ball2.pos + ball2.velocity*dt
if ball2.pos.x > wallR.pos.x:
ball2.velocity.x = -ball2.velocity.x
if ball2.pos.x < wallL.pos.x:
ball2.velocity.x = -ball2.velocity.x
if ball2.pos.y > wallC.pos.y:
ball2.velocity.y = -ball2.velocity.y
if ball2.pos.y < wallF.pos.y:
ball2.velocity.y = -ball2.velocity.y
if ball2.pos.z < wallB.pos.z:
ball2.velocity.z = -ball2.velocity.z
if ball2.pos.z > 6:
ball2.velocity.z = -ball2.velocity.z
#Ball3 collision controlls
ball3.pos = ball3.pos + ball3.velocity*dt
if ball3.pos.x > wallR.pos.x - 1:
ball3.velocity.x = -ball3.velocity.x
if ball3.pos.x < wallL.pos.x + 1:
ball3.velocity.x = -ball3.velocity.x
if ball3.pos.y > wallC.pos.y - 1:
ball3.velocity.y = -ball3.velocity.y
if ball3.pos.y < wallF.pos.y+1:
ball3.velocity.y = -ball3.velocity.y
if ball3.pos.z < wallB.pos.z -1:
ball3.velocity.z = -ball3.velocity.z
if ball3.pos.z > 5:
ball3.velocity.z = -ball3.velocity.z
As you can see, it is very long for something so simple. My main question is, is there a way to make a general if command, such as
if x.pos.y < wallF.pos.y:
x.velocity.y = -x.velocity.y
And set x to represent one of the balls, and switch it between several objects., eg
x=ball1
if x.pos.y > wall.pos.y
x.velocity.y = -x.velocity.y
?