I am trying to make a square in tkinter that can move vertically (according to W and S keystrokes) and rotate about the centre of the canvas (according to A and D keystrokes), where there is a small circle (the canvas is 500x400, so the centre is at (250, 200)) so I made a transform() function which essentially (to account for tkinter's weird coordinate system) translates the square to (0, 0), then uses a rotation matrix to rotate it, and then translate it back, and also also add the vertical translation. My problem is that when it uses the rotation matrix, it's rotating about the centre of the square even after it moves. I want it to rotate about the centre of the canvas (250, 200) always, no matter it's vertical displacement.
here is my code for the keystrokes to change the variables:
def movement():
global originy, angle
if 'w' in keysp:
if(-200 < originy+20 < 200):
originy += 3
print(originy)
if 's' in keysp:
if(-200 < originy-20 < 200):
originy -= 3
print(originy)
if 'a' in keysp:
angle += 3
if 'd' in keysp:
angle -= 3
update()
window.after(10, movement)
(keysp is a set with the keys that are currently being pressed)
and here is the code for the transform function and updating canvas to draw new square:
def transform(x, y):
ox = 250
oy = 200
global angle
rad = math.radians(angle)
rotx = (((x-ox)*math.cos(rad))-((y-oy)*math.sin(rad)))
roty = (((x-ox)*math.sin(rad))+((y-oy)*math.cos(rad)))
newx = rotx+ox
newy = roty+oy-originy
return(newx, newy)
def update():
canvas.delete('all')
canvas.create_polygon(transform((250-50), (200-50)), transform((250+50), (200-50)), transform((250+50), (200+50)), transform((250-50), (200+50)), fill = 'white', outline = 'black')
canvas.create_oval((250-r), (200-r), (250+r), (200+r), fill = 'white')