How to make polygons change color when pressed

Hi There,

I think the initial reason this wouldn’t work is because the first ‘if’ statement would need a double == to test for equality (rather than assign a variable). (i.e. if thisPolygon.color == white: )

However, this is a little tricker because the ‘isPressedIn’ method will check for mouse presses every time your screen refreshes (16.66 ms on a 60Hz monitor). So, if the participant continues to hold the mouse the polygon will appear to flicker (as it transitions from one colour to the other very quickly).

A work around for this it to add a time window in which you will register ‘new’ clicks.

So, in your ‘begin routine’ you would use something like:


polygons = [polygon, polygon_2]

bufferTime=.2
clickClock=core.Clock()
lastClickTime = 0

Then in your each frame you would use something like:


for thisPolygon in polygons:
    if mouse.isPressedIn(thisPolygon):
        thisClickTime = clickClock.getTime()
        if (thisClickTime - lastClickTime) > bufferTime:
            if thisPolygon.fillColor =='red':
                thisPolygon.fillColor = 'white'
            else:
                thisPolygon.fillColor = 'red'
        lastClickTime = thisClickTime

This will only register clicks seperated by 200ms as ‘new’ clicks, and avoid the flicker effect. Here is an updated demo file polyChangeCol.psyexp (12.1 KB)

Hope this helps,
Becca

PS. I noticed that the color attribute has actually been changed to fillColor in the recent release (probably to be consistent with PsychoJS - so updated accordingly)

2 Likes