bupsychtech
bupsychtech

Reputation: 3

Detect object at mouse click location

I have a large number of different image stimuli presented in various locations on screen.

When the participant clicks on a stimulus, I need the name of that stimulus item available for use in the rest of the script. For example, you can achieve this in E-Prime with the SlideState.HitTest(x, y) method, where x and y are mouse coordinates.

The only similar thing I've been able to see in Psychopy is the mouse.isPressedIn(shape) method. However because you must supply a specific object as an argument, it seems you would need an if clause for each of the stimuli, which seems messy (especially for larger numbers of items)

Is there a better way of doing this? I'm still learning so I might be missing something.

Thanks!

Upvotes: 0

Views: 721

Answers (1)

Jonas Lindeløv
Jonas Lindeløv

Reputation: 5683

No, I think not. However, if you just add all objects to a list and loop over them, the code will be neat enough.

# List of (pointers to) stimulus objects
shapes = [shape1, shape2, shape3, shape4, shape5]

# Loop over them and check if mouse is pressed on each one of them
for shape in shapes:
    if mouse.isPressedIn(shape):
        # Set this variable to point to the latest pressed shape
        pressed_shape = shape

# Now you can do stuff with this object
pressed_shape.fillColor = 'red'
pressed_shape.draw()
print pressed_shape.name

Note that if the mouse clicks at a location where there are two objects, pressed_shape is the latest in the list for this solution.

Upvotes: 2

Related Questions