Restricting mouse cursor movement

Hi all,

I’m coding an experiment where participants need to move an object (a box) along an horizontal line. I managed to constraint the mouse movements so that they don’t stretch all the way across the screen:

x = mouse.getPos()[0] 
if x < left_x_limit: 
   x = left_x_limit 
elif x > right_x_limit: 
   x = right_x_limit 
box.pos = [x, 0]

The problem is that I would also like to constraint their mouse movement so that they can move the object in one direction, from left to right only, and not back from right to left.

Thanks!

Martin

See the ‘customMouse’ demo. Here is the code for it…

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Demo of CustomMouse(), showing movement limits, click detected upon release,
and ability to change the pointer.
"""

from __future__ import absolute_import, division, print_function

# author Jeremy Gray

from psychopy import visual, event

win = visual.Window()

# a virtual mouse, vm, :
vm = visual.CustomMouse(win,
    leftLimit=-0.2, topLimit=0, rightLimit=0.2, bottomLimit=-0.4,
    showLimitBox=True, clickOnUp=True)

instr = visual.TextStim(win, text="move the mouse around.\n"
    "click to give the mouse more room to move.", pos=(0, .3))
new_pointer = visual.TextStim(win, text='o')
print("[getPos] [getWheelRel] click time")
while not event.getKeys():
    instr.draw()
    vm.draw()
    win.flip()
    if vm.getClicks():
        vm.resetClicks()
        # vm.setVisible(not vm.getVisible())
        print("click at [%.2f, %.2f]" % (vm.getPos()[0], vm.getPos()[1]))
        print(vm.getWheelRel())
        print("%.3f sec"%vm.mouseMoveTime())

        # can set some limits, others are unchanged:
        vm.setLimit(leftLimit=-0.7, rightLimit=0.7, bottomLimit=-0.8)
        instr.setText("any key to quit")

        # can switch the pointer to anything with a .draw() and setPos() method
        vm.pointer = new_pointer

win.close()

# The contents of this file are in the public domain.

Thanks mdc, but this is not exactly what I was asking. I already managed to constraint the mouse movements to a specific area (in this case, along a line, so that they cannot move the object up or down, but only along that line). What I need now is to limit the mouse movements to one direction only, in this case from left to right (and not back, from right to left). Does it make more sense now?

Sorry I misread the last part. Try setting the left limit to the last known mouse position each frame.

    x = myMouse.getPos()[0]
    if x < left_x_limit:
        x = left_x_limit
    elif x > right_x_limit:
        x = right_x_limit
    box.pos = [x, 0]
    left_x_limit = x  # <<<< add this
1 Like