polygonsOverlap and .overlaps not working?

I’m trying to move the position of a rectangle when it overlaps with another rectangle. I’m doing the most basic rendition of it right now but I just can’t get the overlap methods to work - I’ve tried both visual.helpers.polygonsOverlap and .overlaps() and they both return False even when the rectangles are overlapping or even right on top of each other. However, it works as expected when I have a triangle overlapping a rectangle.

OS (e.g. Win10): Windows 10
PsychoPy version (e.g. 1.84.x): 2020.2.10

Thanks in advance and apologies if I missed something obvious, I’m relatively new to PsychoPy.

Here is the code I wrote in the code snippet.

print(visual.helpers.polygonsOverlap(target1, target2))

if (triangle.overlaps(target1)):
    triangle.pos += (0.2,0.2)

if (target2.overlaps(target1)):
    target2.pos += (0.2,0.2)

This is the full code, since it’s compiled from Builder it’s quite long

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v2020.2.10),
    on April 27, 2021, at 15:41
If you publish work using this script the most relevant publication is:

    Peirce J, Gray JR, Simpson S, MacAskill M, Höchenberger R, Sogo H, Kastman E, Lindeløv JK. (2019) 
        PsychoPy2: Experiments in behavior made easy Behav Res 51: 195. 
        https://doi.org/10.3758/s13428-018-01193-y

"""

from __future__ import absolute_import, division

from psychopy import locale_setup
from psychopy import prefs
from psychopy import sound, gui, visual, core, data, event, logging, clock
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
                                STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)

import numpy as np  # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average,
                   sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os  # handy system and path functions
import sys  # to get file system encoding

from psychopy.hardware import keyboard



# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)

# Store info about the experiment session
psychopyVersion = '2020.2.10'
expName = 'vogel_images'  # from the Builder filename that created this script
expInfo = {'participant': '', 'session': '001'}
dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
if dlg.OK == False:
    core.quit()  # user pressed cancel
expInfo['date'] = data.getDateStr()  # add a simple timestamp
expInfo['expName'] = expName
expInfo['psychopyVersion'] = psychopyVersion

# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
filename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])

# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
    extraInfo=expInfo, runtimeInfo=None,
    originPath='C:\\Users\\qhua300\\Documents\\Vogel image generator\\vogel_images.py',
    savePickle=True, saveWideText=True,
    dataFileName=filename)
# save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING)  # this outputs to the screen, not a file

endExpNow = False  # flag for 'escape' or other condition => quit the exp
frameTolerance = 0.001  # how close to onset before 'same' frame

# Start Code - component code to be run after the window creation

# Setup the Window
win = visual.Window(
    size=(1024, 768), fullscr=True, screen=0, 
    winType='pyglet', allowGUI=False, allowStencil=False,
    monitor='testMonitor', color=[0,0,0], colorSpace='rgb',
    blendMode='avg', useFBO=True, 
    units='height')
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
    frameDur = 1.0 / round(expInfo['frameRate'])
else:
    frameDur = 1.0 / 60.0  # could not measure, so guess

# create a default keyboard (e.g. to check for escape)
defaultKeyboard = keyboard.Keyboard()

# Initialize components for Routine "trial"
trialClock = core.Clock()
target1 = visual.Rect(
    win=win, name='target1',
    width=(0.1, 0.2)[0], height=(0.1, 0.2)[1],
    ori=0, pos=(0, 0),
    lineWidth=1, lineColor=[255,0,0], lineColorSpace='rgb',
    fillColor=[255,0,0], fillColorSpace='rgb',
    opacity=1, depth=0.0, interpolate=True)
target2 = visual.Rect(
    win=win, name='target2',
    width=(0.1, 0.2)[0], height=(0.1, 0.2)[1],
    ori=0, pos=(0.0, 0.0),
    lineWidth=1, lineColor=[255,0,0], lineColorSpace='rgb',
    fillColor=[255,0,0], fillColorSpace='rgb',
    opacity=1, depth=-1.0, interpolate=True)
key_resp = keyboard.Keyboard()
triangle = visual.ShapeStim(
    win=win, name='triangle',
    vertices=[[-(0.1, 0.1)[0]/2.0,-(0.1, 0.1)[1]/2.0], [+(0.1, 0.1)[0]/2.0,-(0.1, 0.1)[1]/2.0], [0,(0.1, 0.1)[1]/2.0]],
    ori=0, pos=(0, 0),
    lineWidth=1, lineColor=[1,1,1], lineColorSpace='rgb',
    fillColor=[1,1,1], fillColorSpace='rgb',
    opacity=1, depth=-4.0, interpolate=True)

# Create some handy timers
globalClock = core.Clock()  # to track the time since experiment started
routineTimer = core.CountdownTimer()  # to track time remaining of each (non-slip) routine 

# ------Prepare to start Routine "trial"-------
continueRoutine = True
# update component parameters for each repeat
print(visual.helpers.polygonsOverlap(target1, target2))

if (triangle.overlaps(target1)):
    triangle.pos += (0.2,0.2)
    print("hello")

if (target2.overlaps(target1)):
    target2.pos += (0.2,0.2)
    print("hello")
key_resp.keys = []
key_resp.rt = []
_key_resp_allKeys = []
# keep track of which components have finished
trialComponents = [target1, target2, key_resp, triangle]
for thisComponent in trialComponents:
    thisComponent.tStart = None
    thisComponent.tStop = None
    thisComponent.tStartRefresh = None
    thisComponent.tStopRefresh = None
    if hasattr(thisComponent, 'status'):
        thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
trialClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
frameN = -1

# -------Run Routine "trial"-------
while continueRoutine:
    # get current time
    t = trialClock.getTime()
    tThisFlip = win.getFutureFlipTime(clock=trialClock)
    tThisFlipGlobal = win.getFutureFlipTime(clock=None)
    frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
    # update/draw components on each frame
    
    # *target1* updates
    if target1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
        # keep track of start time/frame for later
        target1.frameNStart = frameN  # exact frame index
        target1.tStart = t  # local t and not account for scr refresh
        target1.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(target1, 'tStartRefresh')  # time at next scr refresh
        target1.setAutoDraw(True)
    if target1.status == STARTED:
        # is it time to stop? (based on global clock, using actual start)
        if tThisFlipGlobal > target1.tStartRefresh + 1.0-frameTolerance:
            # keep track of stop time/frame for later
            target1.tStop = t  # not accounting for scr refresh
            target1.frameNStop = frameN  # exact frame index
            win.timeOnFlip(target1, 'tStopRefresh')  # time at next scr refresh
            target1.setAutoDraw(False)
    
    # *target2* updates
    if target2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
        # keep track of start time/frame for later
        target2.frameNStart = frameN  # exact frame index
        target2.tStart = t  # local t and not account for scr refresh
        target2.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(target2, 'tStartRefresh')  # time at next scr refresh
        target2.setAutoDraw(True)
    if target2.status == STARTED:
        # is it time to stop? (based on global clock, using actual start)
        if tThisFlipGlobal > target2.tStartRefresh + 1.0-frameTolerance:
            # keep track of stop time/frame for later
            target2.tStop = t  # not accounting for scr refresh
            target2.frameNStop = frameN  # exact frame index
            win.timeOnFlip(target2, 'tStopRefresh')  # time at next scr refresh
            target2.setAutoDraw(False)
    
    # *key_resp* updates
    waitOnFlip = False
    if key_resp.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
        # keep track of start time/frame for later
        key_resp.frameNStart = frameN  # exact frame index
        key_resp.tStart = t  # local t and not account for scr refresh
        key_resp.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(key_resp, 'tStartRefresh')  # time at next scr refresh
        key_resp.status = STARTED
        # keyboard checking is just starting
        waitOnFlip = True
        win.callOnFlip(key_resp.clock.reset)  # t=0 on next screen flip
        win.callOnFlip(key_resp.clearEvents, eventType='keyboard')  # clear events on next screen flip
    if key_resp.status == STARTED and not waitOnFlip:
        theseKeys = key_resp.getKeys(keyList=['space'], waitRelease=False)
        _key_resp_allKeys.extend(theseKeys)
        if len(_key_resp_allKeys):
            key_resp.keys = _key_resp_allKeys[-1].name  # just the last key pressed
            key_resp.rt = _key_resp_allKeys[-1].rt
            # a response ends the routine
            continueRoutine = False
    
    # *triangle* updates
    if triangle.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
        # keep track of start time/frame for later
        triangle.frameNStart = frameN  # exact frame index
        triangle.tStart = t  # local t and not account for scr refresh
        triangle.tStartRefresh = tThisFlipGlobal  # on global time
        win.timeOnFlip(triangle, 'tStartRefresh')  # time at next scr refresh
        triangle.setAutoDraw(True)
    if triangle.status == STARTED:
        # is it time to stop? (based on global clock, using actual start)
        if tThisFlipGlobal > triangle.tStartRefresh + 1.0-frameTolerance:
            # keep track of stop time/frame for later
            triangle.tStop = t  # not accounting for scr refresh
            triangle.frameNStop = frameN  # exact frame index
            win.timeOnFlip(triangle, 'tStopRefresh')  # time at next scr refresh
            triangle.setAutoDraw(False)
    
    # check for quit (typically the Esc key)
    if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
        core.quit()
    
    # check if all components have finished
    if not continueRoutine:  # a component has requested a forced-end of Routine
        break
    continueRoutine = False  # will revert to True if at least one component still running
    for thisComponent in trialComponents:
        if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
            continueRoutine = True
            break  # at least one component has not yet finished
    
    # refresh the screen
    if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
        win.flip()

# -------Ending Routine "trial"-------
for thisComponent in trialComponents:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)
thisExp.addData('target1.started', target1.tStartRefresh)
thisExp.addData('target1.stopped', target1.tStopRefresh)
thisExp.addData('target2.started', target2.tStartRefresh)
thisExp.addData('target2.stopped', target2.tStopRefresh)
thisExp.addData('triangle.started', triangle.tStartRefresh)
thisExp.addData('triangle.stopped', triangle.tStopRefresh)
# the Routine "trial" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()

# Flip one final time so any remaining win.callOnFlip() 
# and win.timeOnFlip() tasks get executed before quitting
win.flip()

# these shouldn't be strictly necessary (should auto-save)
thisExp.saveAsWideText(filename+'.csv', delim='auto')
thisExp.saveAsPickle(filename)
logging.flush()
# make sure everything is closed down
thisExp.abort()  # or data files will save again on exit
win.close()
core.quit()

Here’s a post from 2018 about a similar issue