Search code examples
pythonpsychopy

How to create a continuous visual.Window background/wrapping of background?


For instance, in my case, a cluster of random dots derived from ElementArrayStim spreaded across the stimulus window with the cluster centred on (0,0) moving at x=5. Eventually, each of these dots will hit the window's right boundary. How do I make these dots reappear on the left window boundary in a smooth transition?


Solution

  • The strategy is to look into psychopy.visual.ElementArrayStim.xys which is an Nx2 numpy.array of the current coordinates of all N elements. You can get the N indicies where the x-coordinate exceeds some value and for these indicies change the x-coordinate to another value. In your case, you flip it around the y-axis.

    So:

    # Set up stimuli
    from psychopy import visual
    win = visual.Window(units='norm')
    stim = visual.ElementArrayStim(win, sizes=0.05)
    
    BORDER_RIGHT = 1  # for 'norm' units, this is the coordinate of the right border
    
    # Animation
    for frame in range(360):
        # Determine location of elements on next frame
        stim.xys += (0.01, 0)  # move all to the right
        exceeded = stim.xys[:,0] > BORDER_RIGHT  # index of elements whose x-value exceeds the border
        stim.xys[exceeded] *= (-1, 1)  # for these indicies, mirror the x-coordinate but keep the y-coordinate
    
        # Show it 
        stim.draw()
        win.flip()