我试图创建一个围绕屏幕移动的点,从边缘反弹,每50帧左右以随机方向弯曲。
我所做的是让球不断移动并从屏幕边缘反弹。请注意,这使用了PsychoPy:
win = visual.Window(size=(1600, 900), fullscr=False, screen=0, allowGUI=False, allowStencil=False, units='pix',
monitor='testMonitor', colorSpace=u'rgb', color=[0.51,0.51,0.51])
keys = event.BuilderKeyResponse()
dot1 = visual.Circle(win=win, name='dot1',units='pix',
radius=10, edges=32,
ori=0, pos=(0,0),
lineWidth=1, lineColor='red', lineColorSpace='rgb',
fillColor='red', fillColorSpace='rgb',
opacity=1,interpolate=True)
x_change = 10
y_change = 10
while True:
dot1.pos+=(x_change,y_change)
if dot1.pos[0] > 790 or dot1.pos[0] < -790:
x_change = x_change * -1
if dot1.pos[1] > 440 or dot1.pos[1] < -440:
y_change = y_change * -1
dot1.draw()
win.flip()
if event.getKeys(keyList=["escape"]):
core.quit()
我想这会需要一些触发,我几乎无法理解。 有人能指出我正确的方向吗?我需要哪些变量,以及如何操纵它们?
答案 0 :(得分:2)
一般策略是:计算循环内的帧并将x_change
和y_change
改变为所需帧上的新角度(例如,每50帧)。我会明确使用角度和速度来使用三角函数设置x_change
和y_change
的值:
# New stuff:
import numpy as np
frameN = 50 # To set angle in first loop iteration
speed = 14 # initial speed in whatever unit the stimulus use.
angle = 45 # initial angle in degrees
x_change = np.cos(angle) * speed # initial
y_change = np.sin(angle) * speed # initial
while True:
# More new stuff: Change direction angle (in degrees)
if frameN == 50:
angle_current = np.rad2deg(np.arctan(y_change / float(x_change))) # float to prevent integer division
angle_change = np.random.randint(-180, 180) # change interval to your liking or set to a constant value or something
angle = angle_current + angle_change # new angle
x_change = np.cos(angle) * speed
y_change = np.sin(angle) * speed
frameN = 0
frameN += 1
dot1.pos+=(x_change,y_change)
if dot1.pos[0] > 790 or dot1.pos[0] < -790:
x_change = x_change * -1
if dot1.pos[1] > 440 or dot1.pos[1] < -440:
y_change = y_change * -1
dot1.draw()
win.flip()
if event.getKeys(keyList=["escape"]):
core.quit()
更多随机性的选项:
speed = np.random.randint(1, 20)
)frameN = np.random.randint(40, 60)