Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Pymunk with matplotlib.animation.FuncAnimation()

i'm tring to modify this tutorial for using matplotlib_util module (FuncAnimation). When i try to run the code below, i get this result. I tried to add "ax.clear()" inside the animate function but then I couldn't see anything. I couldn't find the reason.

I couldn't find any samples that use "Pymuyk" and "Matplotlib FuncAnimation" together, either. if you know any examples could you please share with us.

import matplotlib.pyplot as plt
from matplotlib import animation

import pymunk
from pymunk.vec2d import Vec2d
import pymunk.matplotlib_util

def setup_space():
    space = pymunk.Space()
    space.gravity = 0,-9820
    space.damping = 0.99
    return space

def setup_balls(space):
    width = 600
    height = 600
    for x in range(-100,150,50):
        x += width / 2
        offset_y = height/2
        mass = 10
        radius = 25
        moment = pymunk.moment_for_circle(mass, 0, radius, (0,0))
        body = pymunk.Body(mass, moment)
        body.position = x, -125+offset_y
        body.start_position = Vec2d(body.position)
        shape = pymunk.Circle(body, radius)
        shape.elasticity = 0.9999999
        space.add(body, shape)
        pj = pymunk.PinJoint(space.static_body, body, (x, 125+offset_y), (0,0))
        space.add(pj)

fig = plt.figure()
ax = plt.axes(xlim=(0, 600), ylim=(0, 600))
ax.set_aspect("equal")

space = setup_space()
setup_balls(space)

o = pymunk.matplotlib_util.DrawOptions(ax)

space.shapes[1].body.apply_impulse_at_local_point((-12000, 0))

def init():
    space.debug_draw(o)
    return []

def animate(dt):
    #ax.clear()
    for x in range(10):
        space.step(1 / 50 / 10 / 2)

    space.debug_draw(o)
    return space,

frames = 30
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=frames, interval=20, blit=False)

plt.show()
like image 784
omeroguztemel Avatar asked May 04 '26 18:05

omeroguztemel


1 Answers

Try re-setting xlim and ylim. It seems like at least when I use %matplotlib notebook magic ax.clear() also clears the xlim and ylim (I dont have ffmpeg to try the exact newtons code right now). So the reason nothing is shown is because the x and y axis are 0,1 and not 0,600.

So, try something like this:

ax.clear()
ax.set_xlim(0,600)
ax.set_ylim(0,600)

Note that the matplotlib helper class in pymunk is quite basic and more of a proof of concept. Depending on your needs you might get better result by plotting the space/shapes "manually".

like image 132
viblo Avatar answered May 06 '26 07:05

viblo