forked from pybox2d/pybox2d
-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple_cv.py
63 lines (49 loc) · 1.65 KB
/
simple_cv.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
A small self contained example showing how to use OpencvDrawFuncs
to integrate pybox2d into an opencv mainloop
In short:
One static body:
+ One fixture: big polygon to represent the ground
Two dynamic bodies:
+ One fixture: a polygon
+ One fixture: a circle
And some drawing code that extends the shape classes.
John Stowers
"""
import cv2
import Box2D
from Box2D.b2 import (polygonShape, world)
from opencv_draw import OpencvDrawFuncs
# --- constants ---
# Box2D deals with meters, but we want to display pixels,
# so define a conversion factor:
TARGET_FPS = 60
TIME_STEP = 1.0 / TARGET_FPS
# --- pybox2d world setup ---
# Create the world
world = world(gravity=(0, -10), doSleep=True)
# And a static body to hold the ground shape
ground_body = world.CreateStaticBody(
position=(0, 0),
shapes=polygonShape(box=(50, 1)),
)
# Create a couple dynamic bodies
bodyc = world.CreateDynamicBody(position=(20, 45))
circle = bodyc.CreateCircleFixture(radius=0.5, density=1, friction=0.3)
bodyb = world.CreateDynamicBody(position=(30, 45), angle=15)
box = bodyb.CreatePolygonFixture(box=(2, 1), density=1, friction=0.3)
world.CreateWeldJoint(bodyA=bodyc, bodyB=bodyb, anchor=bodyb.worldCenter)
drawer = OpencvDrawFuncs(w=640, h=480, ppm=20)
drawer.install()
while True:
key = 0xFF & cv2.waitKey(int(TIME_STEP * 1000)) # milliseconds
if key == 27:
break
drawer.clear_screen()
drawer.draw_world(world)
# Make Box2D simulate the physics of our world for one step.
world.Step(TIME_STEP, 10, 10)
# Flip the screen and try to keep at the target FPS
cv2.imshow("world", drawer.screen)