I want to write a code that moves a sphere in a zig-zag way across the screen from the upper left to the lower right. this is my attempt.
scene= canvas(width=500, height=500, autoscale=False)
xpos=-10
ypos=8
totaldistance=15
stepsize=0.1
nsteps=int(totaldistance/stepsize)
totaltime=20
timebetween=int(nsteps/totaltime)
s=sphere(pos=vector(-10,0,0), axis=vector(0,2,0))
for i in range(nsteps):
rate(timebetween)
xpos=xpos stepsize
xpos=xpos stepsize
if xpos==10:
xpos=xpos-stepsize
if xpos==1:
xpos=xpos stepsize
ypos=ypos-stepsize
s.pos=vector(xpos,ypos,0)
I don't know how to tell the sphere to move in the other direction when it reaches certain position so that it forms a zig zag motion.
CodePudding user response:
Popular method is to change direction
stepsize = -stepsize
And it needs to use separated x_stepsize
and y_stepsize
like this
x_stepsize = stepsize
y_stepsize = -stepsize
for i in range(nsteps):
xpos = x_stepsize
ypos = y_stepsize
if xpos >= 10:
xpos = 10
x_stepsize = -x_stepsize
if xpos <= 1:
xpos = 1
x_stepsize = -x_stepsize
s.pos = vector(xpos, ypos, 0)