Start stimuli in random location and move with arrows

What are you trying to achieve?
I’m trying to have a stimulus appear at a random location in each trial and then be movable using the arrow keys.

So far I’ve added a Code Component that makes the stimulus start in a random location:
Begin routine tab
import random
targetPos=[random.uniform(-.9,.9), 0.0]

The stimulus has it’s Position[x,y] $ set to $targetPos and ‘Set every frame’.

So far so good - the stimulus appears in a random location each trial. I’ve tried to follow How to move stimuli receiving the key but I can’t the stimulus to move with key press.

What did you try to make it work? and What specifically went wrong when you tried that?:
In a second Code Component, I tried a couple different ways of updating targetPos based on the keys pressed, but I keep getting errors relating to which type of variable targetPos is.

if ‘left’ in event.getKeys():
targetPos =targetPos-.1
if ‘right’ in event.getKeys():
targetPos =targetPos+.1
targetPos =targetPos-.1
TypeError: unsupported operand type(s) for -: ‘list’ and ‘float’

keys = event.getKeys()
if ‘left’ in event.getKeys():
targetPos -=.1
if ‘right’ in event.getKeys():
targetPos +=.1
TypeError: unsupported operand type(s) for -=: ‘list’ and ‘float’

keys = event.getKeys()
if keys:
if keys[0] == ‘left’:
targetPos = targetPos-.1
if keys[0] == ‘right’:
targetPos = targetPos+.1
targetPos = targetPos+.1
TypeError: can only concatenate list (not “float”) to list

Does the second (movement) code component have access to the targetPos variable from the first (random start location) code component?

Is there something else preventing my stimuli from moving on key press?

Thanks in advance!

I solved this. Sharing for anyone else that might be trying to do the same.

Firstly, I combined both into the same code component. Secondly, targetPos is a co-ordinate (‘string’ type in Python), so you wan’t just add or subtract from it - you need to index which part of the string you want to change. For me it was the x-position, the 0th item in the list. So I have:

Begin Routine tab:

import random
targetPos=[random.uniform(-.8,.8), 0.0]

Each Frame tab:

keys = event.getKeys()
if keys:
    if 'left' in keys:
        targetPos[0] = targetPos[0]-.01
    if 'right' in keys:
        targetPos[0] = targetPos[0]+.01
1 Like