0

I need to make the blue circle move in a straight line with animation. The straight line code needs to stay as is. I just can't figure out the code for object animation. The circle can be in any shape and colour it just need to move from point A to point B in a straight line.

import numpy as np                
import matplotlib.pyplot as plt
from matplotlib import pyplot as plt, patches

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


c=plt.Circle((50, 100))

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
        
DrawLine(150,100,50,100)


fig = plt.figure()


plt.imshow(img)
plt.gca().add_artist(c)
plt.show()


Bud
  • 1

1 Answers1

1

Matplotlib has animations for this purpose:

enter image description here

import numpy as np
from matplotlib import pyplot as plt, animation

img = np.ones((200, 200, 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

DrawLine(150, 100, 50, 100)
fig, ax = plt.subplots()
ax.imshow(img)

# define animation function
def animate(i):
    c = plt.Circle((50+i % 100, 100))
    circle = ax.add_artist(c)
    return circle,

# define animation properties, see
# https://matplotlib.org/stable/api/_as_gen/matplotlib.animation.FuncAnimation.html
ani = animation.FuncAnimation(fig, animate, interval=20, blit=True)

plt.show()
Christian Karcher
  • 2,533
  • 1
  • 12
  • 17
  • When I run the code the circle doesn't move. Maybe I need to download some additional plugins? I use anaconda and jupyter notebook. – Bud Dec 10 '22 at 11:42
  • please see https://stackoverflow.com/questions/43445103/inline-animations-in-jupyter for a possible modification of my script to make it work in jupyter – Christian Karcher Dec 12 '22 at 07:54