Search code examples
pythonjupyter-labanaconda3

How to I animate this object to move from first input point to second input point


So, I have this Brezenhema algorithm that generates this line from users input. And I have an object a the begining of the line and I need it to move to the end of the line and back. Object can move with an animation or user dragging it or with arrow keys- how ever you please and know the solution. Thanks!


import matplotlib
import numpy as np                
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation


x1=input("Ievadiet x1 kordinātes")
y1=input("Ievadiet y1 kordinātes")
x2=input("Ievadiet x2 kordinātes")
y2=input("Ievadiet y2 kordinātes")

a=int(x1)
b=int(y1)
c=int(x2)
d=int(y2)



img=np.ones((600,600,3))



def DrawLine(x1,y1,x2,y2):

    dx = abs(x2-x1) 
    dy = abs(y2-y1) 


    if x1<x2:
        xs=1 

    else:
        xs=-1   
        

    if y1<y2:
        ys=1

    else:
        ys=-1
     
    
    x=x1
    y=y1  
    

    p=2*dy-dx   
    


    if dx>dy:
        while x!=x2:
            x=x+xs
            if p > 0:
                y=y+ys
                p=p+2*dy-2*dx

            else:
                p=p+2*dy  
            img[y,x]= 0

    
    else:
        while y!=y2:
            y=y+ys

            if p > 0:
                x=x+xs
                p=p+2*dx-2*dy

            else:
                p=p+2*dx  
            img[y,x]= 0
     
    return          



%matplotlib notebook

DrawLine(a,b,c,d)

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
circ = plt.Circle((a,b), radius=10, edgecolor='b', facecolor='blue')
ax.add_patch(circ)

plt.imshow(img)

plt.show()
...

Dont know really how to start with problem


Solution

  • In matplotlib, you can detect keyboard events and mouse events. For example, we might have something like this:

    def on_move(event):
        if event.inaxes:
            #Whatever you want to do here
    
    
    def on_click(event):
        if event.button is MouseButton.LEFT:
            #Whatever you want to do here
    
    #Somewhere in your code
    binding_id = plt.connect('motion_notify_event', on_move)
    plt.connect('button_press_event', on_click)
    

    The same thing goes for the keyboard too. All you have to do is detect the position of the mouse, and if it was clicked, and move the object correspondingly. For more info, you can read the docs on matplotlib: mouse, and keyboard.