From 6e6bb2a3aae6a3e8b58ba91eed380e062fa8616f Mon Sep 17 00:00:00 2001 From: merijn Date: Tue, 5 Jan 2021 12:18:56 +0100 Subject: [PATCH] added restrict_cursor.py and hexagon.html testpage --- hexagon.html | 53 ++++++++++++++++++++++++++++++++ restrict_cursor.py | 76 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 129 insertions(+) create mode 100644 hexagon.html create mode 100644 restrict_cursor.py diff --git a/hexagon.html b/hexagon.html new file mode 100644 index 0000000..f530e69 --- /dev/null +++ b/hexagon.html @@ -0,0 +1,53 @@ + + + + + + + + + + + + + diff --git a/restrict_cursor.py b/restrict_cursor.py new file mode 100644 index 0000000..2f3fd6f --- /dev/null +++ b/restrict_cursor.py @@ -0,0 +1,76 @@ +import math +from pynput import mouse +from pynput.mouse import Button, Controller + + + +ct = Controller() + +# mouse position +start_pos = (500, 200) +ct.position = start_pos + +# displacement margin (px) +d_margin = 2 + +# hexagon parameters +centerX=400 +centerY=300 +radius=200 + + + +def hexa_points(cx, cy, r): + points=[None]*6 + points[0]=(cx+r*math.cos(0), cy+r*math.sin(0)) + for i in range(1,6): + points[i]=( int(cx+r*math.cos(i*2*math.pi/6)), int(cy+r*math.sin(i*2*math.pi/6)) ) + return points + + +hexagon = hexa_points(centerX, centerY, radius) +# print(hexagon) + + +def update_position(p, pi, pj): + relative=(pj[0]-pi[0], pj[1]-pi[1]) + normal=(relative[1],-relative[0]) + magnitude=math.sqrt((normal[0]*normal[0])+(normal[1]*normal[1])) + normal_unit=(normal[0]/magnitude, normal[1]/magnitude) + displacement=((p[0]-pi[0])*normal_unit[0])+((p[1]-pi[1])*normal_unit[1]) + # print(displacement) + if (displacement > d_margin): + return ( int(p[0]-normal_unit[0]*displacement), int(p[1]-normal_unit[1]*displacement) ) + else: + return False + + +def keep_in_hexagon(point, hexagon): + for i in range(0,6): + j=i+1 + if j==6: + j=0 + # print("point: "+str(point)+" pi: "+str(hexagon[i])+" pj: "+str(hexagon[j])) + updated_point=update_position(point, hexagon[i], hexagon[j]) + if updated_point: + print("[OOB] "+str(point)+' => '+str(updated_point)) + ct.position = updated_point + + +def on_move(x, y): + keep_in_hexagon((x, y), hexagon) + + +# click to stop listening +def on_click(x, y, button, pressed): + print('{0} at {1}'.format( + 'Pressed' if pressed else 'Released', + (x, y))) + if not pressed: + return False + + +with mouse.Listener( + on_move=on_move, + on_click=on_click) as listener: + listener.join()