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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html dir="ltr" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" lang="en"><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="robots" content="noindex,follow">
<meta name="keywords" content="Python Manual,Python Manual,Box2D with Python,Hello.py">
<link rel="shortcut icon" href="http://www.box2d.org/favicon.ico">
<link rel="search" type="application/opensearchdescription+xml" href="http://www.box2d.org/wiki/opensearch_desc.php" title="Box2D Wiki (English)">
<link rel="alternate" type="application/rss+xml" title="Box2D Wiki RSS Feed" href="http://www.box2d.org/wiki/index.php?title=Special:Recentchanges&feed=rss">
<link rel="alternate" type="application/atom+xml" title="Box2D Wiki Atom Feed" href="http://www.box2d.org/wiki/index.php?title=Special:Recentchanges&feed=atom">
<title>Python Manual - Box2D Wiki</title>
<style type="text/css" media="screen, projection">/*<![CDATA[*/
@import "/wiki/skins/common/shared.css?116";
@import "/wiki/skins/monobook/main.css?116";
/*]]>*/</style>
<link rel="stylesheet" type="text/css" href="manual_files/commonPrint.css">
<!--[if lt IE 5.5000]><style type="text/css">@import "/wiki/skins/monobook/IE50Fixes.css?116";</style><![endif]-->
<!--[if IE 5.5000]><style type="text/css">@import "/wiki/skins/monobook/IE55Fixes.css?116";</style><![endif]-->
<!--[if IE 6]><style type="text/css">@import "/wiki/skins/monobook/IE60Fixes.css?116";</style><![endif]-->
<!--[if IE 7]><style type="text/css">@import "/wiki/skins/monobook/IE70Fixes.css?116";</style><![endif]-->
<!--[if lt IE 7]><script type="text/javascript" src="/wiki/skins/common/IEFixes.js?116"></script>
<meta http-equiv="imagetoolbar" content="no" /><![endif]-->
<script type="text/javascript" src="manual_files/wikibits.js"><!-- wikibits js --></script>
<!-- Head Scripts -->
<script type="text/javascript" src="manual_files/ajax.js"></script>
<script type="text/javascript" src="manual_files/ajaxwatch.js"></script>
<style type="text/css">/*<![CDATA[*/
.source-python {line-height: normal;}
.source-python li {line-height: normal;}
/**
* GeSHi Dynamically Generated Stylesheet
* --------------------------------------
* Dynamically generated stylesheet for python
* CSS class: source-python, CSS id:
* GeSHi (C) 2004 - 2007 Nigel McNie (http://qbnz.com/highlighter)
*/
.source-python .de1, .source-python .de2 {font-family: 'Courier New', Courier, monospace; font-weight: normal;}
.source-python {}
.source-python .head {}
.source-python .foot {}
.source-python .imp {font-weight: bold; color: red;}
.source-python .ln-xtra {color: #cc0; background-color: #ffc;}
.source-python li {font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;}
.source-python li.li2 {font-weight: bold;}
.source-python .kw1 {color: #ff7700;font-weight:bold;}
.source-python .kw2 {color: #008000;}
.source-python .kw3 {color: #dc143c;}
.source-python .kw4 {color: #0000cd;}
.source-python .co1 {color: #808080; font-style: italic;}
.source-python .coMULTI {color: #808080; font-style: italic;}
.source-python .es0 {color: #000099; font-weight: bold;}
.source-python .br0 {color: #66cc66;}
.source-python .st0 {color: #483d8b;}
.source-python .nu0 {color: #ff4500;}
.source-python .me1 {color: black;}
/*]]>*/
</style>
<style type="text/css">/*<![CDATA[*/
@import "/wiki/index.php?title=MediaWiki:Geshi.css&usemsgcache=yes&action=raw&ctype=text/css&smaxage=18000";
/*]]>*/
</style> <script type="text/javascript" src="manual_files/index.php"><!-- site js --></script>
<style type="text/css">/*<![CDATA[*/
@import "/wiki/index.php?title=MediaWiki:Common.css&usemsgcache=yes&action=raw&ctype=text/css&smaxage=18000";
@import "/wiki/index.php?title=MediaWiki:Monobook.css&usemsgcache=yes&action=raw&ctype=text/css&smaxage=18000";
@import "/wiki/index.php?title=-&action=raw&gen=css&maxage=18000&smaxage=0";
/*]]>*/</style>
</head><body class="mediawiki ns-0 ltr page-Python_Manual">
<div id="globalWrapper">
<div id="column-content">
<div id="content">
<a name="top" id="top"></a>
<h1 class="firstHeading">Python Manual</h1>
<div id="bodyContent">
<h3 id="siteSub">From Box2D Wiki<br>
Latest version <a href="http://www.box2d.org/wiki/index.php?title=Python_Manual">http://www.box2d.org/wiki/index.php?title=Python_Manual</a>
</h3>
<div id="contentSub"></div>
<div id="jump-to-nav">Jump to: <a href="#column-one">navigation</a>, <a href="#searchInput">search</a></div> <!-- start content -->
<table id="toc" class="toc" summary="Contents"><tbody><tr><td><div id="toctitle"><h2>Contents</h2> <span class="toctoggle">[<a href="javascript:toggleToc()" class="internal" id="togglelink">hide</a>]</span></div>
<ul>
<li class="toclevel-1"><a href="#Box2D_v2.0.1_User_Manual"><span class="tocnumber">1</span> <span class="toctext">Box2D v2.0.1 User Manual</span></a></li>
<li class="toclevel-1"><a href="#About"><span class="tocnumber">2</span> <span class="toctext">About</span></a>
<ul>
<li class="toclevel-2"><a href="#Prerequisites"><span class="tocnumber">2.1</span> <span class="toctext">Prerequisites</span></a></li>
<li class="toclevel-2"><a href="#Core_Concepts"><span class="tocnumber">2.2</span> <span class="toctext">Core Concepts</span></a></li>
</ul>
</li>
<li class="toclevel-1"><a href="#Hello_Box2D"><span class="tocnumber">3</span> <span class="toctext">Hello Box2D</span></a>
<ul>
<li class="toclevel-2"><a href="#Creating_a_World"><span class="tocnumber">3.1</span> <span class="toctext">Creating a World</span></a></li>
<li class="toclevel-2"><a href="#Creating_a_Ground_Box"><span class="tocnumber">3.2</span> <span class="toctext">Creating a Ground Box</span></a></li>
<li class="toclevel-2"><a href="#Creating_a_Dynamic_Body"><span class="tocnumber">3.3</span> <span class="toctext">Creating a Dynamic Body</span></a></li>
<li class="toclevel-2"><a href="#Simulating_the_World_.28of_Box2D.29"><span class="tocnumber">3.4</span> <span class="toctext">Simulating the World (of Box2D)</span></a></li>
<li class="toclevel-2"><a href="#The_Testbed"><span class="tocnumber">3.5</span> <span class="toctext">The Testbed</span></a></li>
</ul>
</li>
<li class="toclevel-1"><a href="#API_Design"><span class="tocnumber">4</span> <span class="toctext">API Design</span></a>
<ul>
<li class="toclevel-2"><a href="#Memory_Management"><span class="tocnumber">4.1</span> <span class="toctext">Memory Management</span></a></li>
<li class="toclevel-2"><a href="#Factories_and_Definitions"><span class="tocnumber">4.2</span> <span class="toctext">Factories and Definitions</span></a></li>
<li class="toclevel-2"><a href="#Units"><span class="tocnumber">4.3</span> <span class="toctext">Units</span></a></li>
<li class="toclevel-2"><a href="#User_Data"><span class="tocnumber">4.4</span> <span class="toctext">User Data</span></a></li>
<li class="toclevel-2"><a href="#Dealing_with_C.2B.2B"><span class="tocnumber">4.5</span> <span class="toctext">Dealing with C++</span></a></li>
<li class="toclevel-2"><a href="#Strawman"><span class="tocnumber">4.6</span> <span class="toctext">Strawman</span></a></li>
</ul>
</li>
<li class="toclevel-1"><a href="#The_World"><span class="tocnumber">5</span> <span class="toctext">The World</span></a>
<ul>
<li class="toclevel-2"><a href="#About_2"><span class="tocnumber">5.1</span> <span class="toctext">About</span></a></li>
<li class="toclevel-2"><a href="#Creating_and_Destroying_a_World"><span class="tocnumber">5.2</span> <span class="toctext">Creating and Destroying a World</span></a></li>
<li class="toclevel-2"><a href="#Using_a_World"><span class="tocnumber">5.3</span> <span class="toctext">Using a World</span></a></li>
<li class="toclevel-2"><a href="#Simulation"><span class="tocnumber">5.4</span> <span class="toctext">Simulation</span></a></li>
<li class="toclevel-2"><a href="#Exploring_the_World"><span class="tocnumber">5.5</span> <span class="toctext">Exploring the World</span></a></li>
<li class="toclevel-2"><a href="#AABB_Queries"><span class="tocnumber">5.6</span> <span class="toctext">AABB Queries</span></a></li>
</ul>
</li>
<li class="toclevel-1"><a href="#Bodies"><span class="tocnumber">6</span> <span class="toctext">Bodies</span></a>
<ul>
<li class="toclevel-2"><a href="#About_3"><span class="tocnumber">6.1</span> <span class="toctext">About</span></a></li>
<li class="toclevel-2"><a href="#Body_Definition"><span class="tocnumber">6.2</span> <span class="toctext">Body Definition</span></a></li>
<li class="toclevel-2"><a href="#Mass_Properties"><span class="tocnumber">6.3</span> <span class="toctext">Mass Properties</span></a></li>
<li class="toclevel-2"><a href="#Position_and_Angle"><span class="tocnumber">6.4</span> <span class="toctext">Position and Angle</span></a></li>
<li class="toclevel-2"><a href="#Damping"><span class="tocnumber">6.5</span> <span class="toctext">Damping</span></a></li>
<li class="toclevel-2"><a href="#Sleep_Parameters"><span class="tocnumber">6.6</span> <span class="toctext">Sleep Parameters</span></a></li>
<li class="toclevel-2"><a href="#Bullets"><span class="tocnumber">6.7</span> <span class="toctext">Bullets</span></a></li>
<li class="toclevel-2"><a href="#Body_Factory"><span class="tocnumber">6.8</span> <span class="toctext">Body Factory</span></a></li>
<li class="toclevel-2"><a href="#Using_a_Body"><span class="tocnumber">6.9</span> <span class="toctext">Using a Body</span></a></li>
<li class="toclevel-2"><a href="#Mass_Data"><span class="tocnumber">6.10</span> <span class="toctext">Mass Data</span></a></li>
<li class="toclevel-2"><a href="#State_Information"><span class="tocnumber">6.11</span> <span class="toctext">State Information</span></a></li>
<li class="toclevel-2"><a href="#Position_and_Velocity"><span class="tocnumber">6.12</span> <span class="toctext">Position and Velocity</span></a></li>
<li class="toclevel-2"><a href="#Forces_and_Impulses"><span class="tocnumber">6.13</span> <span class="toctext">Forces and Impulses</span></a></li>
<li class="toclevel-2"><a href="#Coordinate_Transformations"><span class="tocnumber">6.14</span> <span class="toctext">Coordinate Transformations</span></a></li>
<li class="toclevel-2"><a href="#Lists"><span class="tocnumber">6.15</span> <span class="toctext">Lists</span></a></li>
</ul>
</li>
<li class="toclevel-1"><a href="#Shapes"><span class="tocnumber">7</span> <span class="toctext">Shapes</span></a>
<ul>
<li class="toclevel-2"><a href="#About_4"><span class="tocnumber">7.1</span> <span class="toctext">About</span></a></li>
<li class="toclevel-2"><a href="#The_Shape_Definition"><span class="tocnumber">7.2</span> <span class="toctext">The Shape Definition</span></a></li>
<li class="toclevel-2"><a href="#Friction_and_Restitution"><span class="tocnumber">7.3</span> <span class="toctext">Friction and Restitution</span></a></li>
<li class="toclevel-2"><a href="#Density"><span class="tocnumber">7.4</span> <span class="toctext">Density</span></a></li>
<li class="toclevel-2"><a href="#Filtering"><span class="tocnumber">7.5</span> <span class="toctext">Filtering</span></a></li>
<li class="toclevel-2"><a href="#Sensors"><span class="tocnumber">7.6</span> <span class="toctext">Sensors</span></a></li>
<li class="toclevel-2"><a href="#Circle_Definitions"><span class="tocnumber">7.7</span> <span class="toctext">Circle Definitions</span></a></li>
<li class="toclevel-2"><a href="#Polygon_Definitions"><span class="tocnumber">7.8</span> <span class="toctext">Polygon Definitions</span></a></li>
<li class="toclevel-2"><a href="#Shape_Factory"><span class="tocnumber">7.9</span> <span class="toctext">Shape Factory</span></a></li>
<li class="toclevel-2"><a href="#Using_a_Shape"><span class="tocnumber">7.10</span> <span class="toctext">Using a Shape</span></a></li>
</ul>
</li>
<li class="toclevel-1"><a href="#Joints"><span class="tocnumber">8</span> <span class="toctext">Joints</span></a>
<ul>
<li class="toclevel-2"><a href="#About_5"><span class="tocnumber">8.1</span> <span class="toctext">About</span></a></li>
<li class="toclevel-2"><a href="#The_Joint_Definition"><span class="tocnumber">8.2</span> <span class="toctext">The Joint Definition</span></a></li>
<li class="toclevel-2"><a href="#Distance_Joint"><span class="tocnumber">8.3</span> <span class="toctext">Distance Joint</span></a></li>
<li class="toclevel-2"><a href="#Revolute_Joint"><span class="tocnumber">8.4</span> <span class="toctext">Revolute Joint</span></a></li>
<li class="toclevel-2"><a href="#Prismatic_Joint"><span class="tocnumber">8.5</span> <span class="toctext">Prismatic Joint</span></a></li>
<li class="toclevel-2"><a href="#Pulley_Joint"><span class="tocnumber">8.6</span> <span class="toctext">Pulley Joint</span></a></li>
<li class="toclevel-2"><a href="#Gear_Joint"><span class="tocnumber">8.7</span> <span class="toctext">Gear Joint</span></a></li>
<li class="toclevel-2"><a href="#Mouse_Joint"><span class="tocnumber">8.8</span> <span class="toctext">Mouse Joint</span></a></li>
<li class="toclevel-2"><a href="#Joint_Factory"><span class="tocnumber">8.9</span> <span class="toctext">Joint Factory</span></a></li>
<li class="toclevel-2"><a href="#Using_Joints"><span class="tocnumber">8.10</span> <span class="toctext">Using Joints</span></a></li>
<li class="toclevel-2"><a href="#Using_Distance_Joints"><span class="tocnumber">8.11</span> <span class="toctext">Using Distance Joints</span></a></li>
<li class="toclevel-2"><a href="#Using_Revolute_Joints"><span class="tocnumber">8.12</span> <span class="toctext">Using Revolute Joints</span></a></li>
<li class="toclevel-2"><a href="#Using_Prismatic_Joints"><span class="tocnumber">8.13</span> <span class="toctext">Using Prismatic Joints</span></a></li>
<li class="toclevel-2"><a href="#Using_Pulley_Joints"><span class="tocnumber">8.14</span> <span class="toctext">Using Pulley Joints</span></a></li>
<li class="toclevel-2"><a href="#Using_Gear_Joints"><span class="tocnumber">8.15</span> <span class="toctext">Using Gear Joints</span></a></li>
<li class="toclevel-2"><a href="#Using_Mouse_Joints"><span class="tocnumber">8.16</span> <span class="toctext">Using Mouse Joints</span></a></li>
</ul>
</li>
<li class="toclevel-1"><a href="#Contacts"><span class="tocnumber">9</span> <span class="toctext">Contacts</span></a>
<ul>
<li class="toclevel-2"><a href="#About_6"><span class="tocnumber">9.1</span> <span class="toctext">About</span></a></li>
<li class="toclevel-2"><a href="#Contact_Listener"><span class="tocnumber">9.2</span> <span class="toctext">Contact Listener</span></a></li>
<li class="toclevel-2"><a href="#Contact_Filtering"><span class="tocnumber">9.3</span> <span class="toctext">Contact Filtering</span></a></li>
</ul>
</li>
<li class="toclevel-1"><a href="#Loose_Ends"><span class="tocnumber">10</span> <span class="toctext">Loose Ends</span></a>
<ul>
<li class="toclevel-2"><a href="#World_Boundary"><span class="tocnumber">10.1</span> <span class="toctext">World Boundary</span></a></li>
<li class="toclevel-2"><a href="#Implicit_Destruction"><span class="tocnumber">10.2</span> <span class="toctext">Implicit Destruction</span></a></li>
</ul>
</li>
<li class="toclevel-1"><a href="#Settings"><span class="tocnumber">11</span> <span class="toctext">Settings</span></a>
<ul>
<li class="toclevel-2"><a href="#About_7"><span class="tocnumber">11.1</span> <span class="toctext">About</span></a></li>
<li class="toclevel-2"><a href="#Tolerances"><span class="tocnumber">11.2</span> <span class="toctext">Tolerances</span></a></li>
<li class="toclevel-2"><a href="#Memory_Allocation"><span class="tocnumber">11.3</span> <span class="toctext">Memory Allocation</span></a></li>
</ul>
</li>
<li class="toclevel-1"><a href="#Rendering"><span class="tocnumber">12</span> <span class="toctext">Rendering</span></a>
<ul>
<li class="toclevel-2"><a href="#Debug_Drawing"><span class="tocnumber">12.1</span> <span class="toctext">Debug Drawing</span></a></li>
</ul>
</li>
</ul>
</td></tr></tbody></table><script type="text/javascript"> if (window.showTocToggle) { var tocShowText = "show"; var tocHideText = "hide"; showTocToggle(); } </script>
<a name="Box2D_v2.0.1_User_Manual"></a><h1><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-1" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Box2D v2.0.1 User Manual</span></h1>
<table>
<tbody><tr>
<td> <a href="http://www.box2d.org/wiki/index.php?title=Image:Icon-manual.png" class="image" title="Image:Icon-manual.png"><img alt="Image:Icon-manual.png" src="manual_files/Icon-manual.png" border="0" width="64" height="64"></a>
</td><td> Copyright 2007-2009 Erin Catto
</td></tr></tbody></table>
<a name="About"></a><h1><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-2" title="Template:Manual">edit</a>]</span> <span class="mw-headline">About</span></h1>
<p>Box2D is a 2D rigid body simulation library for games. Programmers
can use it in their games to make objects move in believable ways and
make the world seem more interactive. From the game's point of view a
physics engine is just a system for procedural animation. Rather than
paying (or begging) an animator to move your actors around, you can let
Sir Isaac Newton do the directing.
Box2D is written in portable C++ and bound to Python by <a href="http://www.swig.org/" class="external text" title="http://www.swig.org" rel="nofollow">SWIG</a>. Most of the types defined in the engine begin with the <b>b2</b>
prefix. Hopefully this is sufficient to avoid name clashing with your
game engine if you choose to import it to your global namespace (which
you probably shouldn't do in the first place).
</p>
<a name="Prerequisites"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-3" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Prerequisites</span></h2>
<p>In this manual I'll assume you are familiar with basic physics
concepts, such as mass, force, torque, and impulses. If not, please
first consult the many tutorials provided by Chris Hecker and David
Baraff (google these names). You do not need to understand their
tutorials in great detail, but they do a good job of laying out the
basic concepts that will help you use Box2D.
</p><p><a href="http://wikipedia.org/" class="external text" title="http://wikipedia.org" rel="nofollow">Wikipedia</a>
is also an excellent source of physics and mathematics knowledge. In
some ways it is more useful than Google, because it has carefully
crafted content.
</p><p>This is not a prerequisite, but if you are curious about the about the inner workings of Box2D, you can look at these <a href="http://www.gphysics.com/downloads" class="external text" title="http://www.gphysics.com/downloads" rel="nofollow">articles</a>.
</p><p>You can get by knowing the basics of Python.
</p><p>The current release of pybox2d, 2.0.2b1, offers much more
functionality and ease of use compared to previous versions. It's
difficult to support older versions, so please take the time to upgrade
and update your code.
</p>
<a name="Core_Concepts"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-4" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Core Concepts</span></h2>
<p>Box2D works with several fundamental objects. We briefly define
these objects here and more details are given later in this document.
</p>
<dl><dt> rigid body
</dt><dd> A chunk of matter that is so strong that the distance between
any two bits of matter on the chunk is completely constant. They are
hard like a diamond. In the following discussion we use <b>body</b> interchangably with rigid body.
</dd><dt> shape
</dt><dd> A 2D piece of collision geometry that is rigidly attached to
a body. Shapes have material properties of friction and restitution.
</dd><dt> constraint
</dt><dd> A constraint is a physical connection that removes degrees of
freedom from bodies. In 2D a body has 3 degrees of freedom. If we take
a body and pin it to the wall (like a pendulum) we have <b>constrained</b> the body to the wall. At this point the body can only rotate about the pin, so the constraint has removed 2 degrees of freedom.
</dd><dt> contact constraint
</dt><dd> A special constraint designed to prevent penetration of rigid
bodies and to simulate friction and restitution. You will never create
a contact constraint, they are created automatically by Box2D.
</dd><dt> joint
</dt><dd> This is a contraint used to hold two or more bodies together.
Box2D supports these joint types: revolute, prismatic, distance, and
more. Joints may support <b>limits</b> and <b>motors</b>.
</dd><dt> joint limit
</dt><dd> A joint limit restricts the range of motion of a joint. For example, the human elbow only allows a certain range of angles.
</dd><dt> joint motor
</dt><dd> A joint motor drives the motion of the connected bodies
according to the joint's degrees of freedom. For example, you can use a
motor to drive the rotation of an elbow.
</dd><dt> world
</dt><dd> A physics world is a collection of bodies, shapes, and
constraints that interact together. Box2D supports the creation of
multiple worlds, but this is usually not necessary or desirable.
</dd></dl>
<a name="Hello_Box2D"></a><h1><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-5" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Hello Box2D</span></h1>
<p>There is a <a href="http://www.box2d.org/wiki/index.php?title=Hello.py" title="Hello.py">Hello World</a>
project on the wiki. The program creates a large ground box and a small
dynamic box. This code does not contain any graphics, so prepare to be
underwhelmed. :)
</p><p>For simplicity's sake, the Hello World program imports Box2D as:
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python"><span class="kw1">from</span> Box2D2 <span class="kw1">import</span> *</pre></div>
<p>However, it's recommended that you import Box2D as follows:
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python"><span class="kw1">import</span> Box2D2 as box2d</pre></div>
<p>Or something similar. You will experience problems importing Box2D from multiple modules otherwise. (See the <i>Multiple Source Files</i> section of <a href="http://www.box2d.org/wiki/index.php?title=Box2D_with_Python#Multiple_Source_Files" class="mw-redirect" title="Box2D with Python">Box2D with Python</a>)
</p>
<a name="Creating_a_World"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-6" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Creating a World</span></h2>
<p>Every Box2D program begins with the creation of a world object. This
is the physics hub that manages memory, objects, and simulation.
</p><p>To create a world object, first we need to define a bounding
box for the world. Box2D uses the bounding box to accelerate collision
detection. The size isn't critical, but a better fit will improve
performance. It is better to make the box too big than to make it too
small.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">worldAABB=b2AABB<span class="br0">(</span><span class="br0">)</span>
worldAABB.<span class="me1">lowerBound</span>.<span class="me1">Set</span><span class="br0">(</span><span class="nu0">-100</span>, <span class="nu0">-100</span><span class="br0">)</span>
worldAABB.<span class="me1">upperBound</span>.<span class="me1">Set</span><span class="br0">(</span><span class="nu0">100</span>, <span class="nu0">100</span><span class="br0">)</span></pre></div>
<p>From pybox2d 2.0.2b1 onward, you will now be able to use a slightly simpler syntax:
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">worldAABB=b2AABB<span class="br0">(</span><span class="br0">)</span>
worldAABB.<span class="me1">lowerBound</span> = <span class="br0">(</span><span class="nu0">-100</span>, <span class="nu0">-100</span><span class="br0">)</span>
worldAABB.<span class="me1">upperBound</span> = <span class="br0">(</span><span class="nu0">100</span>, <span class="nu0">100</span><span class="br0">)</span></pre></div>
<p>For more information on b2Vec2 -- Box2D 2D vectors -- see <a href="http://www.box2d.org/wiki/index.php?title=Box2D_with_Python#b2Vec2" class="mw-redirect" title="Box2D with Python">here</a>.
</p><p><b>Caution</b>
</p><p>The <b>world AABB</b> should always be bigger then the region
where your bodies are located. It is better to make the world AABB too
big than too small. If a body reaches the boundary of the world AABB it
will be frozen and will stop simulating.
</p><p>Next we define the gravity vector. Yes, you can make gravity go
sideways (or you could just rotate your monitor). Also we tell the
world to allow bodies to sleep when they come to rest. A sleeping body
doesn't require any simulation.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">gravity = <span class="br0">(</span><span class="nu0">0</span>, <span class="nu0">-10</span><span class="br0">)</span> <span class="co1"># for pybox2d < 2.0.2b1, this must be a b2Vec2</span>
doSleep = <span class="kw2">True</span></pre></div>
<p>Now we create the world object.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">world = b2World<span class="br0">(</span>worldAABB, gravity, doSleep<span class="br0">)</span></pre></div>
<p>So now we have our physics world, let's start adding some stuff to it.
</p>
<a name="Creating_a_Ground_Box"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-7" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Creating a Ground Box</span></h2>
<p>Bodies are built using the following steps:
</p>
<ol><li> Define a body with a position, damping, etc.
</li><li> Use the world object to create the body.
</li><li> Define shapes with geometry, friction, density, etc.
</li><li> Create shapes on the body.
</li><li> Optionally adjust the body's mass to match the attached shapes.
</li></ol>
<p>For step 1 we create the ground body. For this we need a <b>body definition</b>. With the body definition we specify the initial position of the ground body.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">groundBodyDef = b2BodyDef<span class="br0">(</span><span class="br0">)</span>
groundBodyDef.<span class="me1">position</span> = <span class="br0">(</span><span class="nu0">0</span>, <span class="nu0">-10</span><span class="br0">)</span></pre></div>
<p>For step 2 the body definition is passed to the world object to
create the ground body. The world object does not keep a reference to
the body definition. The ground body is created as a static body.
Static bodies don't collide with other static bodies and are immovable.
Box2D determines that a body is static when it has zero mass. Bodies
have zero mass by default, therefore they are static by default.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">groundBody = world.<span class="me1">CreateBody</span><span class="br0">(</span>groundBodyDef<span class="br0">)</span></pre></div>
<p>For step 3 we create a ground polygon definition. We use the <i>SetAsBox</i> shortcut to form the ground polygon into a box shape, with the box centered on the origin of the parent body.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">groundShapeDef = b2PolygonDef<span class="br0">(</span><span class="br0">)</span>
groundShapeDef.<span class="me1">SetAsBox</span><span class="br0">(</span><span class="nu0">50</span>, <span class="nu0">10</span><span class="br0">)</span></pre></div>
<p>The <i>SetAsBox</i> function takes the half-width and half-height.
So in this case the ground box is 100 units wide (x-axis) and 20 units
tall (y-axis). Box2D is tuned for meters, kilograms, and seconds. So
you can consider the extents to be in meters. However, it is possible
to change unit systems, as discussed later in this document.
</p><p>We finish the ground body in step 4 by creating the ground polygon shape on the ground body.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">groundBody.<span class="me1">CreateShape</span><span class="br0">(</span>groundShapeDef<span class="br0">)</span></pre></div>
<p>Again, Box2D does not keep a reference to the shape or body definitions. It copies the data into the <i>b2Body</i> structure.
</p><p>Note that every shape must have a parent body, even shapes that
are static. However, you can attach all static shapes to a single
static body. This need for static bodies is done to make the Box2D code
more uniform internally, reducing the number of potential bugs.
</p><p>You might notice a pattern here. Most Box2D types are prefixed with <i>b2</i>. This is done to reduce the chance for naming conflicts with your code.
</p>
<a name="Creating_a_Dynamic_Body"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-8" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Creating a Dynamic Body</span></h2>
<p>So now we have a ground body. We can use the same technique to
create a dynamic body. The main difference, besides dimensions, is that
we must establish the dynamic body's mass properties.
</p><p>First we create the body using <i>CreateBody</i>.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">bodyDef = b2BodyDef<span class="br0">(</span><span class="br0">)</span>
bodyDef.<span class="me1">position</span> = <span class="br0">(</span><span class="nu0">0</span>, <span class="nu0">4</span><span class="br0">)</span>
body = world.<span class="me1">CreateBody</span><span class="br0">(</span>bodyDef<span class="br0">)</span></pre></div>
<p>Next we create and attach a polygon shape. Notice that we set
density to 1. The default density is zero. Also, the friction on the
shape is set to 0.3. Once the shape is attached, we instruct the body
to compute it's mass properties from the attached shapes using the
method <i>SetMassFromShapes</i>. This gives you a hint that you can
attach more than one shape per body. If the computed mass is zero, then
the body becomes truly static. Bodies have a mass of zero by default,
that's why we didn't need to call <i>SetMassFromShapes</i> for the ground body.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">shapeDef = b2PolygonDef<span class="br0">(</span><span class="br0">)</span>
shapeDef.<span class="me1">SetAsBox</span><span class="br0">(</span><span class="nu0">1</span>, <span class="nu0">1</span><span class="br0">)</span>
shapeDef.<span class="me1">density</span> = <span class="nu0">1</span>
shapeDef.<span class="me1">friction</span> = <span class="nu0">0.3</span>
body.<span class="me1">CreateShape</span><span class="br0">(</span>shapeDef<span class="br0">)</span>
body.<span class="me1">SetMassFromShapes</span><span class="br0">(</span><span class="br0">)</span></pre></div>
<p>That's it for initialization. We are now ready to begin simulating.
</p>
<a name="Simulating_the_World_.28of_Box2D.29"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-9" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Simulating the World (of Box2D)</span></h2>
<p>So we have initialized the ground box and a dynamic box. Now we are
ready to set Newton loose to do his thing. We just have a couple more
issues to consider.
</p><p>Box2D uses a bit of numerical code called an <b>integrator</b>.
Integrators simulate the physics equations at discrete points of time.
This goes along with the traditional game loop where we essentially
have a flip book of movement on the screen. So we need to pick a time
step for Box2D. Generally physics engines for games like a time step at
least as fast as 60Hz or 1/60 seconds. You can get away with larger
time steps, but you will have to be more careful about setting up the
definitions for your world. We also don't like the time step to change
much. So don't tie the time step to your frame rate (unless you really,
really have to). Without further ado, here is the time step.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">timeStep = <span class="nu0">1.0</span> / <span class="nu0">60.0</span></pre></div>
<p>In addition to the integrator, Box2D also uses a larger bit of code called a <b>constraint solver</b>.
The constraint solver solves all the constraints in the simulation, one
at a time. A single constraint can be solved perfectly. However, when
we solve one constraint, we slightly disrupt other constraints. To get
a good solution, we need to iterate over all constraints a number of
times. The suggested iteration count for Box2D is 10. You can tune this
number to your liking, just keep in mind that this has a trade-off
between speed and accuracy. Using fewer iterations increases
performance but accuracy suffers. Likewise, using more iterations
decreases performance but improves the quality of your simulation. Here
is our chosen iteration count.
</p><p>For newer versions of pyBox2D (2.0.2 and beyond), general iterations have been broken up into velocity and position iterations.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">velocityIterations = <span class="nu0">10</span>
positionIterations = <span class="nu0">8</span></pre></div>
<p>For previous versions of pyBox2D (<= 2.0.1):
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">iterations = <span class="nu0">10</span></pre></div>
<p>Note that the time step and the iteration count are completely
unrelated. An iteration is not a sub-step. One iteration is a single
pass over all the constraints withing a time step. You can have
multiple passes over the constraints within a single time step.
</p><p>We are now ready to begin the simulation loop. In your game the
simulation loop can be merged with your game loop. In each pass through
your game loop you call <i>b2World.Step</i>. Just one call is usually enough, depending on your frame rate and your physics time step.
</p><p>The Hello World program was designed to be dead simple, so it
has no graphical output. Rather that being utterly boring by producing
no output, the code prints out the position and rotation of the dynamic
body. Yay! Here is the simulation loop that simulates 60 time steps for
a total of 1 second of simulated time.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python"><span class="kw1">for</span> i <span class="kw1">in</span> <span class="kw2">range</span><span class="br0">(</span><span class="nu0">60</span><span class="br0">)</span>:
world.<span class="me1">Step</span><span class="br0">(</span>timeStep, velocityIterations, positionIterations<span class="br0">)</span>
<span class="kw1">print</span> body.<span class="me1">position</span>, body.<span class="me1">angle</span></pre></div>
<p>For previous versions of pyBox2D (<= 2.0.1):
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python"><span class="kw1">for</span> i <span class="kw1">in</span> <span class="kw2">range</span><span class="br0">(</span><span class="nu0">60</span><span class="br0">)</span>:
world.<span class="me1">Step</span><span class="br0">(</span>timeStep, iterations<span class="br0">)</span>
position = body.<span class="me1">GetPosition</span><span class="br0">(</span><span class="br0">)</span>
angle = body.<span class="me1">GetAngle</span><span class="br0">(</span><span class="br0">)</span>
<span class="kw1">print</span> position, angle</pre></div>
<p><br>
</p>
<a name="The_Testbed"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-11" title="Template:Manual">edit</a>]</span> <span class="mw-headline">The Testbed</span></h2>
<p>Once you have conquered the HelloWorld example, you should start
looking at pybox2d's testbed. The testbed is a unit-testing framework
and demo environment. Here are some of the features:
</p>
<ul><li> Camera with pan and zoom.
</li><li> Mouse picking of shapes attached to dynamic bodies.
</li><li> Extensible set of tests.
</li><li> GUI for parameter tuning, and debug drawing options.
</li><li> Pause and single step simulation.
</li><li> Pygame/pyglet support, both with debug drawing code for reference.
</li><li> Save/load architecture built in with Pickle
</li></ul>
<p><a href="http://www.box2d.org/wiki/index.php?title=Image:Python_testbed.png" class="image" title="Image:python_testbed.png"><img alt="Image:python_testbed.png" src="manual_files/Python_testbed.png" border="0" width="646" height="505"></a>
</p><p>The testbed has many examples of Box2D usage in the test cases
and the framework itself. I encourage you to explore and tinker with
the testbed as you learn Box2D.
</p><p><b>Note:</b> the Python testbed is written using <a href="http://www.pygame.org/" class="external text" title="http://www.pygame.org" rel="nofollow">pygame</a>.
The testbed is not part of the Box2D library, though it is included in
the distribution. Box2D is agnostic about rendering. As shown by the
HelloWorld example, you don't need a renderer to use Box2D.
</p>
<a name="API_Design"></a><h1><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-12" title="Template:Manual">edit</a>]</span> <span class="mw-headline">API Design</span></h1>
<a name="Memory_Management"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-13" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Memory Management</span></h2>
<p>Fortunately, the memory management is taken care of for us on the
C++ side of things, so in general there is no need to worry about
memory. The only problem you might run into is if you are using
cyclical references with userData. Using circular references will
likely cause the garbage collector to not properly collect your objects
until the application has ended.
</p><p>In order to work around this, before destroying a body with a
circular reference is to clear its userData: body.ClearUserData().
Destroy it, and then your Python object should be deallocated properly
(as in, its __del__ is called and then freed).
</p>
<a name="Factories_and_Definitions"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-14" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Factories and Definitions</span></h2>
<p>As mentioned above, memory management plays a central role in the design of the Box2D API. So when you create a <i>b2Body</i> or a <i>b2Joint</i>, you need to call the factory functions on <i>b2World</i>.
</p><p>There are creation functions:
</p><p><b>Note</b>: Indicated are the types that should be used (or will be returned). Do NOT name your variables b2Body, b2World, etc.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">b2Body = b2World.<span class="me1">CreateBody</span><span class="br0">(</span>b2BodyDef<span class="br0">)</span>
b2Joint = b2World.<span class="me1">CreateJoint</span><span class="br0">(</span>b2JointDef<span class="br0">)</span></pre></div>
<p>b2World.CreateJoint returns a b2Joint, which can represent any type
of joint. If you want to access the joint parameters specific to the
joint you created, however, you must use:
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">typecasted_joint = b2World.<span class="me1">CreateJoint</span><span class="br0">(</span>b2JointDef<span class="br0">)</span>.<span class="me1">getAsType</span><span class="br0">(</span><span class="br0">)</span></pre></div>
<p>The above will return a <i>b2DistanceJoint</i>, for example, if the definition passed in described a distance joint.
</p><p>And there are corresponding destruction functions:
</p><p>b2World.DestroyBody(<i>b2Body</i>)
</p>
<pre>b2World.DestroyJoint(<i>b2Joint</i>)
</pre>
<p>When you create a body or joint, you need to provide a <b>definition</b> or <b>def</b>
for short. These definitions contain all the information needed to
build the body or joint. By using this approach we can prevent
construction errors, keep the number of function parameters small,
provide sensible defaults, and reduce the number of accessors.
</p><p>Since shapes must be parented to a body, they are created and destroyed using a factory method on <i>b2Body</i>:
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">b2Shape = b2Body.<span class="me1">CreateShape</span><span class="br0">(</span>b2ShapeDef<span class="br0">)</span>
b2Body.<span class="me1">DestroyShape</span><span class="br0">(</span>b2Shape<span class="br0">)</span></pre></div>
<p>Factories do not retain references to the definitions. So you can
create definitions on the stack and keep them in temporary resources.
</p>
<a name="Units"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-15" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Units</span></h2>
<p>Box2D works with floating point numbers, so some tolerances have to
be used to make Box2D perform well. These tolerance have been tuned to
work well with meters-kilogram-second (MKS) units. In particular, Box2D
has been tuned to work well with moving objects between 0.1 and 10
meters. So this means objects between soup cans and buses in size
should work well.
</p><p>Being a 2D physics engine it is tempting to use pixels as your
units. Unfortunately this will lead to a poor simulation and possibly
weird behavior. An object of length 200 pixels would be seen by Box2D
as the size of a 45 story building. Imagine trying to simulate the
movement of a high-rise building with an engine that is tuned to
simulate ragdolls and barrels. It isn't pretty.
</p><p><b>*** Caution ***</b>
</p><p>Box2D is tuned for MKS units. Keep the size of moving objects
roughly between 0.1 and 10 meters. You'll need to use some scaling
system when you render your environment and actors. The Box2D examples
do this by using an OpenGL viewport transform.
</p>
<a name="User_Data"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-16" title="Template:Manual">edit</a>]</span> <span class="mw-headline">User Data</span></h2>
<p>The <i>b2Shape</i>, <i>b2Body</i>, and <i>b2Joint</i> classes allow
you to attach any Python object as user data. This is handy when you
are examining Box2D data structures and you want to determine how they
relate to the data structures in your game engine.
</p><p>For example, it is typical to attach an <b>actor</b> to the
rigid body on that actor. This sets up a circular reference. If you
have the actor, you can get the body. If you have the body, you can get
the actor.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">actor = GameCreateActor<span class="br0">(</span><span class="br0">)</span>
bodyDef = b2BodyDef<span class="br0">(</span><span class="br0">)</span>
bodyDef.<span class="me1">userData</span> = actor <span class="co1"># you could just as well use a dictionary, tuple, integer, etc.</span>
actor.<span class="me1">body</span> = world.<span class="me1">CreateBody</span><span class="br0">(</span>bodyDef<span class="br0">)</span></pre></div>
<p>Here are some examples of cases where you would need the user data:
</p>
<ul><li> Applying damage to an actor using a collision result.
</li><li> Playing a scripted event if the player is inside an axis-aligned box.
</li><li> Accessing a game structure when Box2D notifies you that a joint is going to be destroyed.
</li></ul>
<p>Keep in mind that user data is optional and you can put anything in
it. However, you should be consistent. For example, if you want to
store an actor on one body, you should probably keep an actor on all
bodies.
</p><p><b>Caution</b>
If you use userData, be sure to see the <i>Working with userData' section of <a href="http://www.box2d.org/wiki/index.php?title=Box2D_with_Python#Working_with_userData" class="mw-redirect" title="Box2D with Python">Box2D with Python</a>.</i>
</p>
<a name="Dealing_with_C.2B.2B"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-17" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Dealing with C++</span></h2>
<p>C++ is great for encapsulation and polymorphism, but it's not so
great for API design. There are always significant trade-offs when
creating a C++ library.
</p><p>Should we use abstract factories or the <b>pimpl</b> idiom? These make the API look cleaner, but they ultimately get in the way of debugging and efficient development.
</p><p>Should we use private data and friends as necessary? Perhaps, but eventually the number of friends can become ridiculous.
</p><p>Should we just wrap the C++ code with a C-API? Perhaps, but this
is extra work and may lead to internal choices that are non-optimal.
Also, C-APIs are harder to debug and maintain. A C-API also breaks
encapsulation.
</p><p>For Box2D I have chosen the path of least resistance. For some
cases a class is well contained in its design and function, so I use
public functions and private data. For everything else I use classes or
structs with all public members. These choices let me develop the code
rapidly, it is easy to debug, and it creates minimal internal clutter
while maintaining tight encapsulation. The downside is that you don't
see a clean, simple API. Of course, you have this nice manual to help
you out. :)
</p><p>The Python bindings expose only public members of the C++ classes.
</p>
<a name="Strawman"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-18" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Strawman</span></h2>
<p>If you don't like this API design, that's ok! You have the source
code! Seriously, if you have feedback about anything related to Box2D,
please leave a comment in the <a href="http://www.box2d.org/forum" class="external text" title="http://www.box2d.org/forum" rel="nofollow">forum</a>.
</p>
<a name="The_World"></a><h1><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-19" title="Template:Manual">edit</a>]</span> <span class="mw-headline">The World</span></h1>
<a name="About_2"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-20" title="Template:Manual">edit</a>]</span> <span class="mw-headline">About</span></h2>
<p>The <i>b2World</i> class contains the bodies and joints. It manages
all aspects of the simulation and allows for asynchronous queries (like
AABB queries). Much of your interactions with Box2D will be with a <i>b2World</i> object.
</p>
<a name="Creating_and_Destroying_a_World"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-21" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Creating and Destroying a World</span></h2>
<p>Creating a world is fairly simple. You need to provide a bounding box and a gravity vector.
</p><p>The axis-aligned bounding box should encapsulate the world. You
can improve performance by making the bounding box a bit bigger than
your world, say 2x just to be safe. If you have lots of bodies that
fall into the abyss, your application should detect this and remove the
bodies. This will improve performance and prevent floating point
overflow.
</p><p><br>
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">myWorld = b2World<span class="br0">(</span>aabb, gravity, doSleep<span class="br0">)</span>
When myWorld goes out of use, it will automatically be deleted by the garbage collector.</pre></div>
<p><b>Caution</b>
</p><p>Recall that the <b>world AABB</b> should always be bigger then
the region where your bodies are located. If bodies leave the world
AABB, then they will be frozen. This is not a bug.
</p>
<a name="Using_a_World"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-22" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Using a World</span></h2>
<p>The world class contains factories for creating and destroying
bodies and joints. These factories are discussed later in the sections
on bodies and joints. There are some other interactions with <i>b2World</i> that I will cover now.
</p>
<a name="Simulation"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-23" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Simulation</span></h2>
<p>The world class is used to drive the simulation. You specify a time step and an iteration count. For example:
</p><p>For versions of pyBox2D <= 2.0.1:
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">timeStep = <span class="nu0">1.0</span> / <span class="nu0">60</span>
iterations = <span class="nu0">10</span>
world.<span class="me1">Step</span><span class="br0">(</span>timeStep, iterations<span class="br0">)</span></pre></div>
<p>For newer versions of pyBox2D (2.0.2 and beyond):
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">timeStep = <span class="nu0">1.0</span> / <span class="nu0">60</span>
velocityIterations = <span class="nu0">10</span>
positionIterations = <span class="nu0">8</span>
world.<span class="me1">Step</span><span class="br0">(</span>timeStep, velocityIterations, positionIterations<span class="br0">)</span></pre></div>
<p>After the time step you can examine your bodies and joints for
information. Most likely you will grab the position off the bodies so
that you can update your actors and render them. You can perform the
time step anywhere in your game loop, but you should be aware of the
order of things. For example, you must create bodies before the time
step if you want to get collision results for the new bodies in that
frame.
</p><p>As I discussed above in the HelloWorld tutorial, you should use
a fixed time step. By using a larger time step you can improve
performance in low frame rate scenarios. But generally you should use a
time step no larger than 1/30 seconds. A time step of 1/60 seconds will
usually deliver a high quality simulation.
</p><p>The iteration count controls how many times the constraint
solver sweeps over all the contacts and joints in the world. More
iterations always yields a better simulation. But don't trade a small
time step for a large iteration count. 60Hz and 10 iterations is far
better than 30Hz and 20 iterations.
</p>
<a name="Exploring_the_World"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-24" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Exploring the World</span></h2>
<p>As mentioned before, the world is a container for bodies and joints.
You can grab the body and joint lists off the world and iterate over
them. For example, this code wakes up all the bodies in the world.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python"><span class="kw1">for</span> body <span class="kw1">in</span> world:
body.<span class="me1">WakeUp</span><span class="br0">(</span><span class="br0">)</span>
body = body.<span class="me1">GetNext</span><span class="br0">(</span><span class="br0">)</span></pre></div>
<p>As you can see, iterating over a world iterates over the bodies; the list itself is available as world.bodyList.
</p><p><br>
</p><p><br>
</p>
<a name="AABB_Queries"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-25" title="Template:Manual">edit</a>]</span> <span class="mw-headline">AABB Queries</span></h2>
<p>Sometimes you want to determine all the shapes in a region. The <i>b2World</i> class has a fast log(N) method for this using the <b>broad-phase</b> data structure. You provide an AABB in world coordinates and <i>b2World</i>
returns an array of all the shapes that potentially intersect the AABB.
This is not exact because what the function actually does is return all
the shapes whose AABBs intersect the specified AABB. For example, the
following code finds all the shapes that potentially intersect a
specified AABB and wakes up all of the associated bodies.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">aabb = b2AABB<span class="br0">(</span><span class="br0">)</span>
aabb.<span class="me1">lowerBound</span>.<span class="me1">Set</span><span class="br0">(</span><span class="nu0">-1.0</span>, <span class="nu0">-1.0</span><span class="br0">)</span>
aabb.<span class="me1">upperBound</span>.<span class="me1">Set</span><span class="br0">(</span><span class="nu0">1.0</span>, <span class="nu0">1.0</span><span class="br0">)</span>
<span class="br0">(</span>count, shapes<span class="br0">)</span> = b2World.<span class="me1">Query</span><span class="br0">(</span>aabb, <span class="nu0">10</span><span class="br0">)</span> <span class="co1"># maximum of 10 shapes</span>
<span class="kw1">for</span> shape <span class="kw1">in</span> shapes:
shape.<span class="me1">GetBody</span><span class="br0">(</span><span class="br0">)</span>.<span class="me1">WakeUp</span><span class="br0">(</span><span class="br0">)</span></pre></div>
<a name="Bodies"></a><h1><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-26" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Bodies</span></h1>
<a name="About_3"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-27" title="Template:Manual">edit</a>]</span> <span class="mw-headline">About</span></h2>
<p>Bodies have position and velocity. You can apply forces, torques,
and impulses to bodies. Bodies can be static or dynamic. Static bodies
never move and don't collide with other static bodies.
</p><p>Bodies are the backbone for shapes. Bodies carry shapes and move them around in the world. Bodies are always <b>rigid bodies</b> in Box2D. That means that two shapes attached to the same rigid body never move relative to each other.
</p><p>You usually keep pointers to all the bodies you create. This way
you can query the body positions to update the positions of your
graphical entities. You should also keep body pointers so you can
destroy them when you are done with them.
</p>
<a name="Body_Definition"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-28" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Body Definition</span></h2>
<p>Before a body is created you must create a body definition (<i>b2BodyDef</i>). You can create a body definition on the stack or build it into your game's data structures. The choice is up to you.
</p><p>Box2D copies the data out of the body definition, it does not
keep a pointer to the body definition. This means you can recycle a
body definition to create multiple bodies.
</p><p>Lets go over some of the key members of the body definition.
</p>
<a name="Mass_Properties"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-29" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Mass Properties</span></h2>
<p>There are a few ways to establish the mass properties for a body.
</p>
<ol><li> Set the mass properties explicitly in the body definition.
</li><li> Set the mass properties explicitly on the body (after it has been created).
</li><li> Set the mass properties based on the density of the attaced shapes.
</li></ol>
<p>In many game scenarios it makes sense to compute mass based on shape
densities. This helps to ensure that bodies have reasonable and
consistent mass values.
</p><p>However, other game scenarios may require specific mass values.
For example, you may have a mechanism, like a scale that needs precise
mass values.
</p><p>You can explicitly set the mass properties in the body definition as follows:
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">bodyDef.<span class="me1">massData</span>.<span class="me1">mass</span> = <span class="nu0">2.0</span> <span class="co1"># the body's mass in kg</span>
bodyDef.<span class="me1">massData</span>.<span class="me1">center</span> = <span class="br0">(</span><span class="nu0">0</span>,<span class="nu0">0</span><span class="br0">)</span> <span class="co1"># the center of mass in local coordinates</span>
bodyDef.<span class="me1">massData</span>.<span class="me1">I</span> = <span class="nu0">3.0</span> <span class="co1"># the rotational inertia in kg*m^2.</span></pre></div>
<p>The other methods of setting the mass properties are covered elsewhere in this document.
</p>
<a name="Position_and_Angle"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-30" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Position and Angle</span></h2>
<p>The body definition gives you the chance to initialize the position
of the body on creation. This has better performance than creating the
body at the world origin and then moving the body.
</p><p>A body has two main points of interest. The first point is the body's <b>origin</b>. Shapes and joints are attached relative to the body's origin. The second point of interest is the <b>center of mass</b>. The center of mass is determined from mass distribution of the attached shapes or is explicitly set with <i>b2MassData</i>. Much of Box2D's internal computations use the center of mass position. For example <i>b2Body</i> stores the linear velocity for the center of mass.
</p><p>When you are building the body definition, you may not know
where the center of mass is located. Therefore you specify the position
of the body's origin. You may also specify the body's angle in radians,
which is not affected by the position of the center of mass. If you
later change the mass properties of the body, then the center of mass
may move on the body, but the origin position does not change and the
attached shapes and joints do not move.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">bodyDef.<span class="me1">position</span> = <span class="br0">(</span><span class="nu0">0.0</span>, <span class="nu0">2.0</span><span class="br0">)</span> <span class="co1"># the body's origin position.</span>
bodyDef.<span class="me1">angle</span> = <span class="nu0">0.25</span> * b2_pi <span class="co1"># the body's angle in radians.</span></pre></div>
<a name="Damping"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-31" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Damping</span></h2>
<p>Damping is used to reduce the world velocity of bodies. Damping is
different than friction because friction only occurs with contact and
damping is much cheaper to simulate than friction. However, damping is
not a replacement for friction and the two effects should be used
together.
</p><p>Damping parameters should be between 0 and infinity, with 0
meaning no damping, and infinity meaning full damping. Normally you
will use a damping value between 0 and 1.0. I generally do not use
linear damping because it makes bodies look <b>floaty</b>.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">bodyDef.<span class="me1">linearDamping</span> = <span class="nu0">0.0</span>
bodyDef.<span class="me1">angularDamping</span> = <span class="nu0">0.1</span></pre></div>
<p>Damping is approximated for stability and performance. At small
damping values the damping effect is mostly independent of the time
step. At larger damping values, the damping effect will vary with the
time step. This is not an issue if you use a fixed time step
(recommended).
</p>
<a name="Sleep_Parameters"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-32" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Sleep Parameters</span></h2>
<p>What does sleep mean? Well it is expensive to simulate bodies, so
the less we have to simulate the better. When a body comes to rest we
would like to stop simulating it.
</p><p>When Box2D determines that a body (or group of bodies) has come
to rest, the body enters a sleep state which has very little CPU
overhead. If an awake body collides with a sleeping body, then the
sleeping body wakes up. Bodies will also wake up if a joint or contact
attached to them is destroyed. You can also wake a body manually.
</p><p>The body definition lets you specify whether a body can <b>sleep</b> and whether a body is created sleeping.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">bodyDef.<span class="me1">allowSleep</span> = <span class="kw2">True</span>
bodyDef.<span class="me1">isSleeping</span> = <span class="kw2">False</span></pre></div>
<a name="Bullets"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-33" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Bullets</span></h2>
<p>Game simulation usually generates a sequence of images that are
played at some frame rate. In this setting rigid bodies can move by a
large amount in one time step. If a physics engine doesn't account for
the large motion, you may see some objects incorrectly pass through
each other. This effect is called <b>tunneling</b>.
</p><p>By default, Box2D uses continuous collision detection (CCD) to
prevent dynamic bodies from tunneling through static bodies. This is
done by sweeping shapes from their old position to their new positions.
The engine looks for new collisions during the sweep and computes the
time of impact (TOI) for these collisions. Bodies are moved to their
first TOI and then simulated to the end of the original time step. This
process is repeated as necessary.
</p><p>Normally CCD is not used between dynamic bodies. This is done
to keep performance reasonable. In some game scenarios you need dynamic
bodies to use CCD. For example, you may want to shoot a high speed
bullet at a thin wall. Without CCD, the bullet my tunnel through the
wall.
</p><p>Fast moving objects in Box2D are called bullets. You should
decide what bodies should be bullets based on your game design. If you
decide a body should be treated as a bullet, use the following setting.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">bodyDef.<span class="me1">isBullet</span> = <span class="kw2">True</span></pre></div>
<p><br>
The bullet flag only affects dynamic bodies.
</p><p>CCD is expensive so you probably don't want all moving bodies to
be bullets. So by default Box2D only uses CCD between moving bodies and
static bodies. This is an effective approach to prevent bodies from
escaping your game world. However, you may have some fast moving bodies
that that require CCD all the time.
</p>
<a name="Body_Factory"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-34" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Body Factory</span></h2>
<p>Bodies are created and destroyed using a body factory provided by
the world class. This lets the world create the body with an efficient
allocator and add the body to the world data structure.
</p><p>Bodies can be dynamic or static depending on the mass properties. Both body types use the same creation and destruction methods.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">dynamicBody = myWorld.<span class="me1">CreateBody</span><span class="br0">(</span>bodyDef<span class="br0">)</span>
<span class="co1"># ... do stuff ...</span>
myWorld.<span class="me1">DestroyBody</span><span class="br0">(</span>dynamicBody<span class="br0">)</span>
dynamicBody = <span class="kw2">None</span></pre></div>
<p><br>Static bodies do not move under the influence of other bodies.
You may manually move static bodies, but you should be careful so that
you don't squash dynamic bodies between two or more static bodies.
Friction will not work correctly if you move a static body. Static
bodies never simulate on their own and they never collide with other
static bodies. It is faster to attach several shapes to a static body
than to create several static bodies with a single shape on each one.
Internally, Box2D sets the mass and inverse mass of static bodies to
zero. This makes the math work out so that most algorithms don't need
to treat static bodies as a special case.
</p><p>Box2D does not keep a reference to the body definition or any
of the data it holds (except user data pointers). So you can create
temporary body definitions and reuse the same body definitions.
</p><p>Box2D allows you to avoid destroying bodies by deleting your <i>b2World</i>
object, which does all the cleanup work for you. However, you should be
mindful to nullify any body pointers that you keep in your game engine.
</p><p>When you destroy a body, the attached shapes and joints are
automatically destroyed. This has important implications for how you
manage shape and joint pointers. See
[[Python_Manual#Implicit_Destruction|Implicit Destruction] for details.
</p><p>Suppose you want to connect a dynamic body to ground with a
joint. You'll need to connect the joint to a static body. If you don't
have a static body, you can get a shared ground body from your world
object. You can also attach static shapes to the ground body.
</p><p><br>
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">ground = myWorld.<span class="me1">GetGroundBody</span><span class="br0">(</span><span class="br0">)</span>
<span class="co1"># ... build a joint using the ground body ...</span></pre></div>
<a name="Using_a_Body"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-35" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Using a Body</span></h2>
<p>After creating a body, there are many operations you can perform on
the body. These include setting mass properties, accessing position and
velocity, applying forces, and transforming points and vectors.
</p>
<a name="Mass_Data"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-36" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Mass Data</span></h2>
<p>You can adjust the mass of a body at run-time. This is usually done
when you create or destroy shapes on a body. You may want to adjust the
mass of the body based on the current shapes.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">b2Body.<span class="me1">SetMassFromShapes</span><span class="br0">(</span><span class="br0">)</span></pre></div>
<p>You may also want to set the mass properties directly. For example,
you may change the shapes, but want to use your own mass formulas.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">b2Body.<span class="me1">massData</span> = b2MassData</pre></div>
<p>The body's mass data is available through the following functions:
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python"><span class="kw2">float</span> = b2Body.<span class="me1">GetMass</span><span class="br0">(</span><span class="br0">)</span> <span class="co1"># returns a float</span>
<span class="kw2">float</span> = b2Body.<span class="me1">GetInertia</span><span class="br0">(</span><span class="br0">)</span>
b2Vec2= b2Body.<span class="me1">GetLocalCenter</span><span class="br0">(</span><span class="br0">)</span></pre></div>
<a name="State_Information"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-37" title="Template:Manual">edit</a>]</span> <span class="mw-headline">State Information</span></h2>
<p>There are many aspects to the body's state. You can access this state data efficient through the following functions:
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">bool_value = b2Body.<span class="me1">isBullet</span>
b2Body.<span class="me1">isBullet</span> = <span class="kw2">True</span>
bool_value = b2Body.<span class="me1">IsStatic</span><span class="br0">(</span><span class="br0">)</span>
bool_value = b2Body.<span class="me1">IsDynamic</span><span class="br0">(</span><span class="br0">)</span>
bool_value = b2Body.<span class="me1">IsFrozen</span><span class="br0">(</span><span class="br0">)</span>
bool_value = b2Body.<span class="me1">IsSleeping</span><span class="br0">(</span><span class="br0">)</span>
b2Body.<span class="me1">AllowSleeping</span><span class="br0">(</span><span class="kw2">True</span><span class="br0">)</span>
b2Body.<span class="me1">WakeUp</span><span class="br0">(</span><span class="br0">)</span></pre></div>
<p>The bullet state is described in <a href="#Bullets" title="">Bullets</a>. The frozen state is described in <a href="#World_Boundary" title="">World Boundary</a>.
</p>
<a name="Position_and_Velocity"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-38" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Position and Velocity</span></h2>
<p>You access the position and rotation of a body. This is common when
rendering your associated game actor. You can also set the position,
although this is less common since you will normally use Box2D to
simulate movement.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python"><span class="kw2">bool</span> = b2Body.<span class="me1">SetXForm</span><span class="br0">(</span>position, radian_angle<span class="br0">)</span>
b2XForm = b2Body.<span class="me1">GetXForm</span><span class="br0">(</span><span class="br0">)</span>
b2Vec2 = b2Body.<span class="me1">position</span>
<span class="kw2">float</span> = b2Body.<span class="me1">angle</span></pre></div>
<p>You can access the center of mass position in world coordinates.
Much of the internal simulation in Box2D uses the center of mass.
However, you should normally not need to access it. Instead you will
usually work with the body transform.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">b2Vec2 = b2Body.<span class="me1">GetWorldCenter</span><span class="br0">(</span><span class="br0">)</span></pre></div>
<p>You can access the linear and angular velocity. The linear velocity is for the center of mass.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">b2Body.<span class="me1">linearVelocity</span> = linvel_vec
linvel_vec = b2Body.<span class="me1">linearVelocity</span>
b2Body.<span class="me1">angularVelocity</span> = <span class="kw2">float</span><span class="br0">(</span>angvel<span class="br0">)</span>
angvel = b2Body.<span class="me1">angularVelocity</span></pre></div>
<a name="Forces_and_Impulses"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-39" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Forces and Impulses</span></h2>
<p>You can apply forces, torques, and impulses to a body. When you
apply a force or an impulse, you provide a world point where the load
is applied. This often results in a torque about the center of mass.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">b2Body.<span class="me1">ApplyForce</span><span class="br0">(</span>force_vector, point<span class="br0">)</span>
b2Body.<span class="me1">ApplyTorque</span><span class="br0">(</span>torque<span class="br0">)</span>
b2Body.<span class="me1">ApplyImpulse</span><span class="br0">(</span>impulse_vector, point<span class="br0">)</span></pre></div>
<p>Applying a force, torque, or impulse wakes the body. Sometimes this
is undesirable. For example, you may be applying a steady force and
want to allow the body to sleep to improve performance. In this case
you can use the following code.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python"><span class="kw1">if</span> <span class="kw1">not</span> myBody.<span class="me1">IsSleeping</span><span class="br0">(</span><span class="br0">)</span>:
myBody.<span class="me1">ApplyForce</span><span class="br0">(</span>myForce, myPoint<span class="br0">)</span></pre></div>
<a name="Coordinate_Transformations"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-40" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Coordinate Transformations</span></h2>
<p>The body class has some utility functions to help you transform
points and vectors between local and world space. If you don't
understand these concepts, please read "Essential Mathematics for Games
and Interactive Applications" by Jim Van Verth and Lars Bishop. These
functions are efficient, so use them with impunity.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">b2Vec2 = b2Body.<span class="me1">GetWorldPoint</span><span class="br0">(</span>localPoint<span class="br0">)</span>
b2Vec2 = b2Body.<span class="me1">GetWorldVector</span><span class="br0">(</span>localVector<span class="br0">)</span>
b2Vec2 = b2Body.<span class="me1">GetLocalPoint</span><span class="br0">(</span>worldPoint<span class="br0">)</span>
b2Vec2 = b2Body.<span class="me1">GetLocalVector</span><span class="br0">(</span>worldVector<span class="br0">)</span></pre></div>
<a name="Lists"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-41" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Lists</span></h2>
<p>You can iterate over a body's shapes. This is mainly useful if you need to access the shape's user data.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python"><span class="kw1">for</span> shape <span class="kw1">in</span> body: <span class="co1"># iterates over body.shapeList</span>
data = shape.<span class="me1">userData</span>
<span class="co1"># ... do something with data ...</span></pre></div>
<p>You can similarly iterate over the body's joint list.
</p>
<a name="Shapes"></a><h1><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-42" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Shapes</span></h1>
<a name="About_4"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-43" title="Template:Manual">edit</a>]</span> <span class="mw-headline">About</span></h2>
<p>Shapes are the collision geometry attached to bodies. Shapes are
also used to define the mass of a body. This lets you specify the
density and let Box2D do the work of computing the mass properties.
</p><p>Shapes have properties of friction and restitution. Shapes
carry collision filtering information to let you prevent collisions
between certain game objects.
</p><p>Shapes are always owned by a body. You can attach multiple
shapes to a single body. Shapes are abstract classes so that many types
of shapes can be implemented in Box2D. If you are brave, you can
implement your own shape type (and collision algorithms).
</p>
<a name="The_Shape_Definition"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-44" title="Template:Manual">edit</a>]</span> <span class="mw-headline">The Shape Definition</span></h2>
<p>Shape definitions are used to create shapes. There is common shape data held by <i>b2ShapeDef</i> and specific shape data held by derived classes.
</p>
<a name="Friction_and_Restitution"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-45" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Friction and Restitution</span></h2>
<p>Friction is used to make objects slide along each other
realistically. Box2D supports static and dynamic friction, but uses the
same parameter for both. Friction is simulated accurately in Box2D and
the friction strength is proportional to the normal force (this is
called <b>Coulomb friction</b>). The friction parameter is usually set
between 0 and 1. A value of zero turns off friction and a value of one
makes the friction strong. When the friction is computed between two
shapes, Box2D must combine the friction parameters of the two shapes.
This is done with the following formula:
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python"><span class="kw1">from</span> <span class="kw3">math</span> <span class="kw1">import</span> sqrt
friction = sqrt<span class="br0">(</span>shape1.<span class="me1">friction</span> * shape2.<span class="me1">friction</span><span class="br0">)</span></pre></div>
<p>Restitution is used to make objects bounce. The restitution value is
usually set to be between 0 and 1. Consider dropping a ball on a table.
A value of zero means the ball won't bounce. This is called an <b>inelastic</b> collision. A value of one means the ball's velocity will be exactly reflected. This is called a <b>perfectly elastic</b> collision. Restitution is combined using the following formula.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">restitution = b2Max<span class="br0">(</span>shape1.<span class="me1">restitution</span>, shape2.<span class="me1">restitution</span><span class="br0">)</span></pre></div>
<p>When a shape develops multiple contacts, restitution is simulated
approximately. This is because Box2D uses an iterative solver. Box2D
also uses inelastic collisions when the collision velocity is small.
This is done to prevent jitter.
</p>
<a name="Density"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-46" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Density</span></h2>
<p>Box2D optionally computes the mass and rotational inertia of bodies
using the mass distribution implied by the attached shapes. Specifying
mass directly can often lead to poorly tuned simulations. Therefore,
the recommended way of specifying body mass is by setting the shape
densities and calling <i>b2Body.SetMassFromShape</i> once all the shapes are attached to the body.
</p>
<a name="Filtering"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-47" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Filtering</span></h2>
<p>Collision filtering is a system for preventing collision between
shapes. For example, say you make a character that rides a bicycle. You
want the bicycle to collide with the terrain and the character to
collide with the terrain, but you don't want the character to collide
with the bicycle (because they must overlap). Box2D supports such
collision filtering using categories and groups.
</p><p>Box2D supports 16 collision categories. For each shape you can
specify which category it belongs to. You also specify what other
categories this shape can collide with. For example, you could specify
in a multiplayer game that all players don't collide with each other
and monsters don't collide with each other, but players and monsters
should collide. This is done with <b>masking bits</b>. For example:
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">playerShapeDef.<span class="kw2">filter</span>.<span class="me1">categoryBits</span> = 0x0002
monsterShapeDef.<span class="kw2">filter</span>.<span class="me1">categoryBits</span> = 0x0004
playerShape.<span class="kw2">filter</span>.<span class="me1">maskBits</span> = 0x0004
monsterShapeDef.<span class="kw2">filter</span>.<span class="me1">maskBits</span> = 0x0002</pre></div>
<p>Collision groups let you specify an integral group index. You can
have all shapes with the same group index always collide (positive
index) or never collide (negative index). Group indices are usually
used for things that are somehow related, like the parts of a bicycle.
In the following example, shape1 and shape2 always collide, but shape3
and shape4 never collide.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">shape1Def.<span class="kw2">filter</span>.<span class="me1">groupIndex</span> = <span class="nu0">2</span>
shape2Def.<span class="kw2">filter</span>.<span class="me1">groupIndex</span> = <span class="nu0">2</span>
shape3Def.<span class="kw2">filter</span>.<span class="me1">groupIndex</span> = <span class="nu0">-8</span>
shape4Def.<span class="kw2">filter</span>.<span class="me1">groupIndex</span> = <span class="nu0">-8</span></pre></div>
<p>Collisions between shapes of different group indices are filtered
according the category and mask bits. In other words, group filtering
has higher precendence than category filtering.
</p><p>Note that additional collision filtering occurs in Box2D. Here is a list:
</p>
<ul><li> A shape on a static body never collides with a shape on another static body.
</li><li> Shapes on the same body never collide with each other.
</li><li> You can optionally enable/disable collision between shapes on bodies connected by a joint.
</li></ul>
<p>Sometimes you might need to change collision filtering after a shape
has already been created. You can get and set the b2FilterData
structure on an existing shape using <i>b2Shape.GetFilterData</i> and <i>b2Shape.SetFilterData</i>. Box2D caches filtering results, so you must manually re-filter a shape using <i>b2World.Refilter</i>.
</p>
<a name="Sensors"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-48" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Sensors</span></h2>
<p>Some times game logic needs to know when two shapes overlap yet
there should be no collision response. This is done by using sensors. A
sensor is a shape that detects collision but does not produce a
response.
</p><p>You can flag any shape as being a sensor. Sensors may be static
or dynamic. Remember that you may have multiple shapes per body and you
can have any mix of sensors and solid shapes.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">myShapeDef.<span class="me1">isSensor</span> = <span class="kw2">True</span></pre></div>
<a name="Circle_Definitions"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-49" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Circle Definitions</span></h2>
<p><i>b2CircleDef</i> extends <i>b2ShapeDef</i> and adds a radius and a local position.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">cdef = b2CircleDef<span class="br0">(</span><span class="br0">)</span>
cdef.<span class="me1">radius</span> = <span class="nu0">1.5</span>
cdef.<span class="me1">localPosition</span>.<span class="me1">Set</span><span class="br0">(</span><span class="nu0">1.0</span>, <span class="nu0">0.0</span><span class="br0">)</span></pre></div>
<a name="Polygon_Definitions"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-50" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Polygon Definitions</span></h2>
<p><i>b2PolyDef</i> is used to implement convex polygons. They are a
bit tricky to use correctly, so please read closely. The maximum vertex
count is defined by <i>b2_maxPolyVertices</i> which is currently 8. If you need to use more vertices, you must modify <i>b2_maxPolyVertices</i> in file <i>b2Settings</i>.
</p><p>When you build a polygon definition you must specify the number of vertices you will use. The vertices must be specified in <b>counter-clockwise</b>
(CCW) order about the z-axis of a right-handed coordinate system. This
might turn out to be clockwise on your screen, depending on your
coordinate system conventions.
</p><p>Polygons must be <b>convex</b>. In other words, each vertex
must point outwards to some degree. Finally, you must not overlap any
vertices. Box2D will automatically close the loop.
</p><p><img src="manual_files/convex_concave.gif" alt="convex_concave.gif">
</p><p>Here is an example of a polygon definition of a triangle:
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">triangleDef = b2PolygonDef<span class="br0">(</span><span class="br0">)</span>
triangleDef.<span class="me1">setVertices</span><span class="br0">(</span> <span class="br0">[</span> <span class="br0">(</span><span class="nu0">-1.0</span>, <span class="nu0">0.0</span><span class="br0">)</span>, <span class="br0">(</span><span class="nu0">1.0</span>, <span class="nu0">0.0</span><span class="br0">)</span>, <span class="br0">(</span><span class="nu0">0.0</span>, <span class="nu0">2.0</span><span class="br0">)</span> <span class="br0">]</span> <span class="br0">)</span></pre></div>
<p><br>The vertices are defined in the coordinate system of the parent
body. If you need to offset a polygon within the parent body, then just
offset all the vertices.
</p><p>For convenience, there are functions to initialize polygons as
boxes. You can have either an axis-aligned box centered at the body
origin or an oriented box offset from the body origin.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">alignedBoxDef = b2PolygonDef<span class="br0">(</span><span class="br0">)</span>
hx = <span class="nu0">1.0</span> <span class="co1"># half-width</span>
hy = <span class="nu0">2.0</span> <span class="co1"># half-height</span>
alignedBoxDef.<span class="me1">SetAsBox</span><span class="br0">(</span>hx, hy<span class="br0">)</span>
orientedBoxDef = b2PolygonDef<span class="br0">(</span><span class="br0">)</span>
center = <span class="br0">(</span><span class="nu0">-1.5</span>, <span class="nu0">0.0</span><span class="br0">)</span>
angle = <span class="nu0">0.5</span> * b2_pi
orientedBoxDef.<span class="me1">SetAsBox</span><span class="br0">(</span>hx, hy, center, angle<span class="br0">)</span></pre></div>
<a name="Shape_Factory"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-51" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Shape Factory</span></h2>
<p>Shapes are created by initializing a shape definition and then passing the definition to the parent body.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">circleDef = b2CircleDef<span class="br0">(</span><span class="br0">)</span>
circleDef.<span class="me1">radius</span> = <span class="nu0">3.0</span>
circleDef.<span class="me1">density</span> = <span class="nu0">2.5</span>
myShape = myBody.<span class="me1">CreateShape</span><span class="br0">(</span>circleDef<span class="br0">)</span>
<span class="co1"># [optionally store the shape object somewhere]</span></pre></div>
<p>This creates the shape and attaches it to the body. You do not need
to store the shape pointer since the shape will automatically be
destroyed when the parent body is destroyed (see <a href="http://www.box2d.org/wiki/index.php?title=Python_Manual#Implicit_Destruction" title="Python Manual">Implicit Destruction</a>).
</p><p>After you finish adding shapes to a body, you may want to recompute the mass properties of the body based on the child shapes.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">myBody.<span class="me1">SetMassFromShapes</span><span class="br0">(</span><span class="br0">)</span></pre></div>
<p>This function is expensive, so you should only call it when necessary.
</p><p>You can destroy a shape on the parent body easily. You may do
this to model a breakable object. Otherwise you can just leave the
shape alone and let the body destruction take care of destroying the
attached shapes.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">myBody.<span class="me1">DestroyShape</span><span class="br0">(</span>myShape<span class="br0">)</span></pre></div>
<p>After removing shapes from a body, you may want to call <i>SetMassFromShapes</i> again.
</p>
<a name="Using_a_Shape"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-52" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Using a Shape</span></h2>
<p>There's not much to say here. You can get a shape's type and its
parent body. You can also test a point to see if it is contained within
the shape. Look at <i>b2Shape.h</i> for details.
</p>
<a name="Joints"></a><h1><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-53" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Joints</span></h1>
<a name="About_5"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-54" title="Template:Manual">edit</a>]</span> <span class="mw-headline">About</span></h2>
<p>Joints are used to constrain bodies to the world or to each other.
Typical examples in games include ragdolls, teeters, and pulleys.
Joints can be combined in many different ways to create interesting
motions.
</p><p>Some joints provide limits so you can control the range of
motion. Some joints provide motors which can be used to drive the joint
at a prescribed speed until a prescribed force/torque is exceeded.
</p><p>Joint motors can be used in many ways. You can use motors to
control position by specifying a joint velocity that is proportional to
the difference between the actual and desired position. You can also
use motors to simulate joint friction: set the joint velocity to zero
and provide a small, but significant maximum motor force/torque. Then
the motor will attempt to keep the joint from moving until the load
becomes too strong.
</p>
<a name="The_Joint_Definition"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-55" title="Template:Manual">edit</a>]</span> <span class="mw-headline">The Joint Definition</span></h2>
<p>Each joint type has a definition that derives from <i>b2JointDef</i>.
All joints are connected between two different bodies. One body may
static. If you want to waste memory, then create a joint between two
static bodies. :)
</p><p>You can specify user data for any joint type and you can
provide a flag to prevent the attached bodies from colliding with each
other. This is actually the default behavior and you must set the <i>collideConnected</i> Boolean to allow collision between to connected bodies.
</p><p>Many joint definitions require that you provide some geometric data. Often a joint will be defined by <b>anchor points</b>.
These are points fixed in the attached bodies. Box2D requires these
points to be specified in local coordinates. This way the joint can be
specified even when the current body transforms violate the joint
constraint --- a common ocurrence when a game is saved and reloaded.
Additionally, some joint definitions need to know the default relative
angle between the bodies. This is necessary to constraint rotation
correctly via joint limits or a fixed relative angle.
</p><p>Initializing the geometric data can be tedious, so many joints
have initialization functions that use the current body transforms to
remove much of the work. However, these initialization functions should
usually only be used for prototyping. Production code should define the
geometry directly. This will make joint behavior more robust.
</p><p>The rest of the joint definition data depends on the joint type. We cover these now.
</p>
<a name="Distance_Joint"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-56" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Distance Joint</span></h2>
<p>One of the simplest joint is a distance joint which says that the
distance between two points on two bodies must be constant. When you
specify a distance joint the two bodies should already be in place.
Then you specify the two <b>anchor</b> points in world coordinates.
The first anchor point is connected to body 1, and the second anchor
point is connected to body 2. These points imply the length of the
distance constraint.
</p><p><img src="manual_files/distanceJoint.gif" alt="distanceJoint.gif">
</p><p>Here is an example of a distance joint definition. In this case we decide to allow the bodies to collide.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">jointDef = b2DistanceJointDef<span class="br0">(</span><span class="br0">)</span>
jointDef.<span class="me1">Initialize</span><span class="br0">(</span>myBody1, myBody2, worldAnchorOnBody1, worldAnchorOnBody2<span class="br0">)</span>
jointDef.<span class="me1">collideConnected</span> = <span class="kw2">True</span></pre></div>
<a name="Revolute_Joint"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-57" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Revolute Joint</span></h2>
<p>A revolute joint forces two bodies to share a common anchor point, often called a <b>hinge point</b>. The revolute joint has a single degree of freedom: the relative rotation of the two bodies. This is called the <b>joint angle</b>.
</p><p><img src="manual_files/revoluteJoint.gif" alt="revoluteJoint.gif">
</p><p>To specify a revolute you need to provide two bodies and a
single anchor point in world space. The initialization function assumes
that the bodies are already in the correct position.
</p><p>In this example, two bodies are connected by a revolute joint at the first body's center of mass.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">jointDef = b2RevoluteJointDef<span class="br0">(</span><span class="br0">)</span>
jointDef.<span class="me1">Initialize</span><span class="br0">(</span>myBody1, myBody2, myBody1.<span class="me1">GetWorldCenter</span><span class="br0">(</span><span class="br0">)</span><span class="br0">)</span></pre></div>
<p>The revolute joint angle is positive when body2 rotates CCW about
the angle point. Like all angles in Box2D, the revolute angle is
measured in radians. By convention the revolute joint angle is zero
when the joint is created using <i>Initialize()</i>, regardless of the current rotation of the two bodies.
</p><p>In some cases you might wish to control the joint angle. For
this, the revolute joint can optionally simulate a joint limit and/or a
motor.
</p><p>A joint limit forces the joint angle to remain between an lower
and upper bound. The limit will apply as much torque as needed to make
this happen. The limit range should include zero, otherwise the joint
will lurch when the simulation begins.
</p><p>A joint motor allows you to specify the joint speed (the time
derivative of the angle). The speed can be negative or positive. A
motor can have infinite force, but this is usually not desirable. Have
you ever heard the expression:
</p><p><b>Caution</b>
</p><p>"What happens when an irresistible force meets an immovable object?"
</p><p>I can tell you it's not pretty. So you can provide a maximum
torque for the joint motor. The joint motor will maintain the specified
speed unless the required torque exceeds the specified maximum. When
the maximum torque is exceeded, the joint will slow down and can even
reverse.
</p><p>You can use a joint motor to simulate joint friction. Just set
the joint speed to zero, and set the maximum torque to some small, but
significant value. The motor will try to prevent the joint from
rotating, but will yield to a significant load.
</p><p>Here's a revision of the revolute joint definition above; this
time the joint has a limit and a motor enabled. The motor is setup to
simulate joint friction.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">jointDef = b2RevoluteJointDef<span class="br0">(</span><span class="br0">)</span>
jointDef.<span class="me1">Initialize</span><span class="br0">(</span>body1, body2, myBody1.<span class="me1">GetWorldCenter</span><span class="br0">(</span><span class="br0">)</span><span class="br0">)</span>
jointDef.<span class="me1">lowerAngle</span> = <span class="nu0">-0.5</span> * b2_pi <span class="co1"># -90 degrees</span>
jointDef.<span class="me1">upperAngle</span> = <span class="nu0">0.25</span> * b2_pi <span class="co1"># 45 degrees</span>
jointDef.<span class="me1">enableLimit</span> = <span class="kw2">True</span>
jointDef.<span class="me1">maxMotorTorque</span>= <span class="nu0">10.0</span>
jointDef.<span class="me1">motorSpeed</span> = <span class="nu0">0.0</span>
jointDef.<span class="me1">enableMotor</span> = <span class="kw2">True</span></pre></div>
<a name="Prismatic_Joint"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-58" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Prismatic Joint</span></h2>
<p>A prismatic joint allows for relative translation of two bodies
along a specified axis. A prismatic joint prevents relative rotation.
Therefore, a prismatic joint has a single degree of freedom.
</p><p><img src="manual_files/prismaticJoint.gif" alt="prismaticJoint.gif">
</p><p>The prismatic joint definition is similar to the revolute joint
description; just substitute translation for angle and force for
torque. Using this analogy provides an example prismatic joint
definition with a joint limit and a friction motor:
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">jointDef = b2PrismaticJointDef<span class="br0">(</span><span class="br0">)</span>
worldAxis = <span class="br0">(</span><span class="nu0">1.0</span>, <span class="nu0">0.0</span><span class="br0">)</span>
jointDef.<span class="me1">Initialize</span><span class="br0">(</span>myBody1, myBody2, myBody1.<span class="me1">GetWorldCenter</span><span class="br0">(</span><span class="br0">)</span>, worldAxis<span class="br0">)</span>
jointDef.<span class="me1">lowerTranslation</span> = <span class="nu0">-5.0</span>
jointDef.<span class="me1">upperTranslation</span> = <span class="nu0">2.5</span>
jointDef.<span class="me1">enableLimit</span> = <span class="kw2">True</span>
jointDef.<span class="me1">maxMotorForce</span> = <span class="nu0">1.0</span>
jointDef.<span class="me1">motorSpeed</span> = <span class="nu0">0.0</span>
jointDef.<span class="me1">enableMotor</span> = <span class="kw2">True</span></pre></div>
<p>The revolute joint has an implicit axis coming out of the screen.
The prismatic joint needs an explicit axis parallel to the screen. This
axis is fixed in the two bodies and follows their motion.
</p><p>Like the revolute joint, the prismatic joint translation is zero when the joint is created using <i>Initialize()</i>. So be sure zero is between your lower and upper translation limits.
</p>
<a name="Pulley_Joint"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-59" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Pulley Joint</span></h2>
<p>A pulley is used to create an idealized pulley. The pulley connects
two bodies to ground and to each other. As one body goes up, the other
goes down. The total length of the pulley rope is conserved according
to the initial configuration.
</p>
<pre>length1 + length2 == constant
</pre>
<p><img src="manual_files/pulleyJoint.gif" alt="pulleyJoint.gif">
</p><p>You can supply a ratio that simulates a <b>block and tackle</b>.
This causes one side of the pulley to extend faster than the other. At
the same time the constraint force is smaller on one side than the
other. You can use this to create mechanical leverage.
</p>
<pre>length1 + ratio * length2 == constant
</pre>
<p>For example, if the ratio is 2, then length1 will vary at twice the
rate of length2. Also the force in the rope attached to body1 will have
half the constraint force as the rope attached to body2.
</p><p>Pulleys can be troublesome when one side is fully extended. The
rope on the other side will have zero length. At this point the
constraint equations become singular (bad). Therefore the pulley joint
constrains the maximum length that either side can attain. Also, you
may want to control the maximum lengths for gameplay reasons. So the
maximum lengths improve stability and give you more control.
</p><p>Here is an example pulley definition:
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">anchor1 = myBody1.<span class="me1">GetWorldCenter</span><span class="br0">(</span><span class="br0">)</span>
anchor2 = myBody2.<span class="me1">GetWorldCenter</span><span class="br0">(</span><span class="br0">)</span>
groundAnchor1 = <span class="br0">(</span>p1.<span class="me1">x</span>, p1.<span class="me1">y</span> + <span class="nu0">10.0</span><span class="br0">)</span>
groundAnchor2 = <span class="br0">(</span>p2.<span class="me1">x</span>, p2.<span class="me1">y</span> + <span class="nu0">12.0</span><span class="br0">)</span>
ratio = <span class="nu0">1.0</span>
jointDef = b2PulleyJointDef<span class="br0">(</span><span class="br0">)</span>
jointDef.<span class="me1">Initialize</span><span class="br0">(</span>myBody1, myBody2, groundAnchor1, groundAnchor2, anchor1, anchor2, ratio<span class="br0">)</span>
jointDef.<span class="me1">maxLength1</span> = <span class="nu0">18.0</span>
jointDef.<span class="me1">maxLength2</span> = <span class="nu0">20.0</span></pre></div>
<a name="Gear_Joint"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-60" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Gear Joint</span></h2>
<p>If you want to create a sophisticated mechanical contraption you
might want to use gears. In principle you can create gears in Box2D by
using compound shapes to model gear teeth. This is not very efficient
and might be tedious to author. You also have to be careful to line up
the gears so the teeth mesh smoothly. Box2D has a simpler method of
creating gears: the <b>gear joint</b>.
</p><p><img src="manual_files/gearJoint.gif" alt="gearJoint.gif">
</p><p>The gear joint requires that you have two bodies connected to a
ground by a revolute or prismatic joint. You can use any combination of
those joint types. Also, Box2D requires that the revolute and prismatic
joints were created with the ground as body1.
</p><p>Like the pulley ratio, you can specify a gear ratio. However,
in this case the gear ratio can be negative. Also keep in mind that
when one joint is a revolute joint (angular) and the other joint is
prismatic (translation), then the gear ratio will have units of length
or one over length.
</p>
<pre>coordinate1 + ratio * coordinate2 == constant
</pre>
<p>Here is an example gear joint:
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">jointDef = b2GearJointDef<span class="br0">(</span><span class="br0">)</span>
jointDef.<span class="me1">body1</span> = myBody1
jointDef.<span class="me1">body2</span> = myBody2
jointDef.<span class="me1">joint1</span> = myRevoluteJoint
jointDef.<span class="me1">joint2</span> = myPrismaticJoint
jointDef.<span class="me1">ratio</span> = <span class="nu0">2.0</span> * b2_pi / myLength</pre></div>
<p>Note that the gear joint depends on two other joints. This creates a
fragile situation. What happens if those joints are deleted?
</p><p><b>Caution</b>
</p><p>Always delete gear joints before the revolute/prismatic joints
on the gears. Otherwise your code will crash in a bad way due to the
orphaned joint pointers in the gear joint. You should also delete the
gear joint before you delete any of the bodies involved.
</p>
<a name="Mouse_Joint"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-61" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Mouse Joint</span></h2>
<p>The mouse joint is used in the testbed to manipulate bodies with the
mouse. Please see the testbed and b2MouseJoint.h for details.
</p>
<a name="Joint_Factory"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-62" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Joint Factory</span></h2>
<p>Joints are created and destroyed using the world factory methods. This brings up an old issue:
</p><p><b>Caution</b>
</p><p>Don't try to create a body or joint on the stack or on the heap using <i>new</i> or <i>malloc</i>. You must create and destroy bodies and joints using the create and destroy methods of the <i>b2World</i> class.
</p><p>Here's an example of the lifetime of a revolute joint:
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">jointDef = b2RevoluteJointDef<span class="br0">(</span><span class="br0">)</span>
jointDef.<span class="me1">body1</span> = myBody1
jointDef.<span class="me1">body2</span> = myBody2
jointDef.<span class="me1">anchorPoint</span> = myBody1.<span class="me1">GetCenterPosition</span><span class="br0">(</span><span class="br0">)</span>
joint = myWorld.<span class="me1">CreateJoint</span><span class="br0">(</span>jointDef<span class="br0">)</span>.<span class="me1">getAsType</span><span class="br0">(</span><span class="br0">)</span>
<span class="co1"># ... do stuff ...</span>
myWorld.<span class="me1">DestroyJoint</span><span class="br0">(</span>joint<span class="br0">)</span>
joint = <span class="kw2">None</span></pre></div>
<p>It is always good to nullify your pointer after they are destroyed.
This will make the program crash in a controlled manner if you try to
reuse the pointer.
</p><p>The lifetime of a joint is not simple. Heed this warning well:
</p><p><b>Caution</b>
</p><p>Joints are destroyed when an attached body is destroyed.
</p><p>This precaution is not always necessary. You may organize your
game engine so that joints are always destroyed before the attached
bodies. In this case you don't need to implement the listener class.
See <a href="http://www.box2d.org/wiki/index.php?title=Python_Manual#Implicit_Destruction" title="Python Manual">Implicit Destruction</a> for details.
</p>
<a name="Using_Joints"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-63" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Using Joints</span></h2>
<p>Many simulations create the joints and don't access them again until
they are detroyed. However, there is a lot of useful data contained in
joints that you can use to create a rich simulation.
</p><p>First of all, you can get the bodies, anchor points, and user data from a joint.
</p><p><i>b2Body</i> = b2Joint.body1
</p>
<pre><i>b2Body</i> = b2Joint.body2
<i>b2Vec2</i> = b2Joint.GetAnchor1()
<i>b2Vec2</i> = b2Joint.GetAnchor2()
anyType = b2Joint.userData
</pre>
<p>All joints have a reaction force and torque. This the reaction force
applied to body 2 at the anchor point. You can use reaction forces to
break joints or trigger other game events. These functions may do some
computations, so don't call them if you don't need the result.
</p><p><i>b2Vec2</i> = b2Joint.GetReactionForce()
</p>
<pre><i>float</i> = b2Joint.GetReactionTorque()
</pre>
<a name="Using_Distance_Joints"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-64" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Using Distance Joints</span></h2>
<p>Distance joints don't have motors or limits, so there are no extra runtime methods for distance joints.
</p>
<a name="Using_Revolute_Joints"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-65" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Using Revolute Joints</span></h2>
<p>You can access a revolute joint's angle, speed, and motor torque.
</p><p><i>float</i> = b2RevoluteJoint.GetJointAngle()
</p>
<pre><i>float</i> = b2RevoluteJoint.GetJointSpeed()
<i>float</i> = b2RevoluteJoint.GetMotorTorque()
</pre>
<p>You also update the motor parameters each step.
</p>
<pre>b2RevoluteJoint.SetMotorSpeed(float(speed))
b2RevoluteJoint.SetMaxMotorTorque(float(torque))
</pre>
<p>Joint motors have some interesting abilities. You can update the
joint speed every time step so you can make the joint move
back-and-forth like a sine-wave or according to whatever function you
want.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python"><span class="kw1">from</span> <span class="kw3">math</span> <span class="kw1">import</span> cos
<span class="co1"># ...</span>
<span class="co1"># ... Game Loop Begin ...</span>
myJoint.<span class="me1">SetMotorSpeed</span><span class="br0">(</span>cos<span class="br0">(</span><span class="nu0">0.5</span> * <span class="kw3">time</span><span class="br0">)</span><span class="br0">)</span>
<span class="co1"># ... Game Loop End ...</span></pre></div>
<p>You can also use joint motors to track a desired joint angle. For example:
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python"><span class="co1">#... Game Loop Begin ...</span>
angleError = myJoint.<span class="me1">GetJointAngle</span><span class="br0">(</span><span class="br0">)</span> - angleTarget
gain = <span class="nu0">0.1</span>
myJoint.<span class="me1">SetMotorSpeed</span><span class="br0">(</span>-gain * angleError<span class="br0">)</span>
<span class="co1"># ... Game Loop End ...</span></pre></div>
<p>Generally your gain parameter should not be too large. Otherwise your joint may become unstable.
</p>
<a name="Using_Prismatic_Joints"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-66" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Using Prismatic Joints</span></h2>
<p>Using a prismatic joint is similar to using a revolute joint. Here are the relevant member functions:
</p><p><i>float</i> = b2PrismaticJoint.GetJointTranslation()
</p>
<pre><i>float</i> = b2PrismaticJoint.GetJointSpeed()
<i>float</i> = b2PrismaticJoint.GetMotorForce()
b2PrismaticJoint.SetMotorSpeed(float(speed))
b2PrismaticJoint.SetMotorForce(float(force))
</pre>
<a name="Using_Pulley_Joints"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-67" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Using Pulley Joints</span></h2>
<p>Pully joints provide the current lengths.
</p><p><i>float</i> = b2PulleyJoint.length1
</p>
<pre><i>float</i> = b2PulleyJoint.length2
</pre>
<a name="Using_Gear_Joints"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-68" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Using Gear Joints</span></h2>
<p>Gear joints don't provide any information beyond the functions defined in <i>b2Joint</i>.
</p>
<a name="Using_Mouse_Joints"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-69" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Using Mouse Joints</span></h2>
<p>The mouse joint is able to manipulate the attached body by updating the target point each time step.
</p>
<a name="Contacts"></a><h1><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-70" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Contacts</span></h1>
<a name="About_6"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-71" title="Template:Manual">edit</a>]</span> <span class="mw-headline">About</span></h2>
<p>Contacts are objects created by Box2D to manage collision between shapes. There are different kinds of contacts, derived from <i>b2Contact</i>,
for managing contact between different kinds of shapes. For example
there is a contact class for managing polygon-polygon collision and
another contact class for managing circle-circle collision. This is
normally not important to you, I just thought you might like to know.
</p><p>Here is some terminlogy associated with contacts. This
terminology is particular to Box2D, but you might find similar
terminology in other physics engines.
</p>
<dl><dt> contact point
</dt><dd> A contact point is a point where two shapes touch. In reality
objects may touch over regions when surfaces touch. Box2D approximates
contact with a small number of points.
</dd><dt> contact normal
</dt><dd> A contact normal is a unit vector that points from shape1 to shape2.
</dd><dt> contact separation
</dt><dd> Separation is the opposite of penetration. Separation is
negative when shapes overlap. It is possible that future versions of
Box2D will create contact points with positive separation, so you may
want to check the sign when contact points are reported.
</dd><dt> normal force
</dt><dd> Box2D use an iterative contact solver and stores the results
with the contact points. You can safely use the normal force to guage
the collision intensity. For example, you can use the force to trigger
breakables or to play collision sounds.
</dd><dt> tangent force
</dt><dd> The tangent force is the contact solver's estimate of the friction force.
</dd><dt> contact ids
</dt><dd> Box2D tries to re-use the contact force results from a time
step as the initial guess for the next time step. Box2D uses contact
ids to match contact points across time steps. The ids contain
geometric features indices that help to distinguish one contact point
from another.
</dd></dl>
<p>Contacts are created when two shape's AABBs overlap. Sometimes
collision filtering will prevent the creation of contacts. Box2D
sometimes needs to create a contact even though the collision is
filtered. In this case it uses a <i>b2NullContact</i> that prevents collision from occuring. Contacts are destroyed with the AABBs cease to overlap.
</p><p>So you might gather that there may be contacts created for
shapes that are not touching (just their AABBs). Well, this is correct.
It's a "chicken or egg" problem. We don't know if we need a contact
object until one is created to analyze the collision. We could delete
the contact right away if the shapes are not touching, or we can just
wait until the AABBS stop overlapping. Box2D takes the latter approach.
</p>
<a name="Contact_Listener"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-72" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Contact Listener</span></h2>
<p>You can receive contact data by implementing <i>b2ContactListener</i>.
This listener reports a contact point when it is created, when it
persists for more than one time step, and when it is destroyed. Keep in
mind that two shapes may have multiple contact points.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python"><span class="kw1">class</span> MyContactListener<span class="br0">(</span>b2ContactListener<span class="br0">)</span>:
<span class="kw1">def</span> <span class="kw4">__init__</span><span class="br0">(</span><span class="kw2">self</span><span class="br0">)</span>: <span class="kw2">super</span><span class="br0">(</span>myContactListener, <span class="kw2">self</span><span class="br0">)</span>.<span class="kw4">__init__</span><span class="br0">(</span><span class="br0">)</span>
<span class="kw1">def</span> Add<span class="br0">(</span><span class="kw2">self</span>, point<span class="br0">)</span>:
<span class="st0">""</span><span class="st0">"Handle add point"</span><span class="st0">""</span>
<span class="kw1">pass</span>
<span class="kw1">def</span> Persist<span class="br0">(</span><span class="kw2">self</span>, point<span class="br0">)</span>:
<span class="st0">""</span><span class="st0">"Handle persist point"</span><span class="st0">""</span>
<span class="kw1">pass</span>
<span class="kw1">def</span> Remove<span class="br0">(</span><span class="kw2">self</span>, point<span class="br0">)</span>:
<span class="st0">""</span><span class="st0">"Handle remove point"</span><span class="st0">""</span>
<span class="kw1">pass</span>
<span class="kw1">def</span> Result<span class="br0">(</span><span class="kw2">self</span>, point<span class="br0">)</span>:
<span class="st0">""</span><span class="st0">"Handle results"</span><span class="st0">""</span>
<span class="kw1">pass</span></pre></div>
<p><b>Caution</b>
</p><p>Do not keep a reference to the contact points returned to <i>b2ContactListener</i>. Instead make a deep copy of the contact point data into your own buffer. The example below shows one way of doing this.
</p><p>Continuous physics uses sub-stepping, so a contact point may be
added and removed within the same time step. This is normally not a
problem, but your code should handle this gracefully.
</p><p>Contact points are reported immediately when they are added,
persisted, or removed. This occurs before the solver is called, so the <i>b2ContactPoint</i>
object does not contain the computed impulse. However, the relative
velocity at the contact point is provided so that you can estimated the
contact impulse. If you implement the <i>Result</i> listener function, you will receive <i>b2ContactResult</i>
objects for solid contact points after the solver has been called.
These result structures contain the sub-step impulses. Again, due to
continuous physics you may receive multiple results per contact point
per <i>b2World.Step</i>.
</p><p>It is tempting to implement game logic that alters the physics
world inside a contact callback. For example, you may have a collision
that applies <b>damage</b> and try to destroy the associated actor and
its rigid body. However, Box2D does not allow you to alter the physics
world inside a callback because you might destroy objects that Box2D is
currently processing, leading to orphaned pointers.
</p><p>The recommended practice for processing contact points is to
buffer all contact points that you care about and process them after
the time step. You should always process the contact points immediately
after the time step, otherwise some other client code might alter the
physics world, invalidating the contact buffer. When you process the
contact point buffer you can alter the physics world, but you still
need to be careful that you don't orphan pointers stored in the contact
point buffer. The testbed has example contact point processing that is
safe from orphaned pointers.
</p><p>This code from the CollisionProcessing test (<a href="http://code.google.com/p/pybox2d/source/browse/trunk/Python/testbed/test_CollisionProcessing.py" class="external text" title="http://code.google.com/p/pybox2d/source/browse/trunk/Python/testbed/test_CollisionProcessing.py" rel="nofollow">test_CollisionProcessing.py</a>) shows how to handle orphaned bodies when processing the contact buffer. Here is an excerpt.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python"><span class="co1"># We are going to destroy some bodies according to contact</span>
<span class="co1"># points. We must buffer the bodies that should be destroyed</span>
<span class="co1"># because they may belong to multiple contact points.</span>
nuke = <span class="br0">[</span><span class="br0">]</span>
<span class="co1"># Traverse the contact results. Destroy bodies that</span>
<span class="co1"># are touching heavier bodies.</span>
body_pairs = <span class="br0">[</span><span class="br0">(</span>p.<span class="me1">shape1</span>.<span class="me1">GetBody</span><span class="br0">(</span><span class="br0">)</span>, p.<span class="me1">shape2</span>.<span class="me1">GetBody</span><span class="br0">(</span><span class="br0">)</span><span class="br0">)</span> <span class="kw1">for</span> p <span class="kw1">in</span> <span class="kw2">self</span>.<span class="me1">points</span><span class="br0">]</span>
<span class="kw1">for</span> body1, body2 <span class="kw1">in</span> body_pairs:
mass1, mass2 = body1.<span class="me1">GetMass</span><span class="br0">(</span><span class="br0">)</span>, body2.<span class="me1">GetMass</span><span class="br0">(</span><span class="br0">)</span>
<span class="kw1">if</span> mass1 > <span class="nu0">0.0</span> <span class="kw1">and</span> mass2 > <span class="nu0">0.0</span>:
<span class="kw1">if</span> mass2 > mass1:
nuke_body = body1
<span class="kw1">else</span>:
nuke_body = body2
<span class="kw1">if</span> nuke_body <span class="kw1">not</span> <span class="kw1">in</span> nuke:
nuke.<span class="me1">append</span><span class="br0">(</span>nuke_body<span class="br0">)</span>
<span class="co1"># Destroy the bodies, skipping duplicates.</span>
<span class="kw1">for</span> b <span class="kw1">in</span> nuke:
<span class="kw1">print</span> <span class="st0">"Nuking:"</span>, b
<span class="kw2">self</span>.<span class="me1">world</span>.<span class="me1">DestroyBody</span><span class="br0">(</span>b<span class="br0">)</span></pre></div>
<a name="Contact_Filtering"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-73" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Contact Filtering</span></h2>
<p>Often in a game you don't want all objects to collide. For example,
you may want to create a door that only certain characters can pass
through. This is called contact filtering, because some interactions
are <b>filtered out</b>.
</p><p>Box2D allows you to achieve custom contact filtering by implementing a <i>b2ContactFilter</i> class. This class requires you to implement a <i>ShouldCollide</i> function that receives two <i>b2Shape</i> pointers. Your function returns True if the shapes should collide.
</p><p>The default implementation of <i>ShouldCollide</i> uses the <i>b2FilterData</i> defined in the Filtering section of the Shapes chapter <a href="#Filtering" title="">Filtering</a>.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python"><span class="kw1">class</span> MyContactFilter<span class="br0">(</span>b2ContactFilter<span class="br0">)</span>:
<span class="kw1">def</span> <span class="kw4">__init__</span><span class="br0">(</span><span class="kw2">self</span><span class="br0">)</span>:
<span class="kw2">super</span><span class="br0">(</span>MyContactFilter, <span class="kw2">self</span><span class="br0">)</span>.<span class="kw4">__init__</span><span class="br0">(</span><span class="br0">)</span>
<span class="kw1">def</span> ShouldCollide<span class="br0">(</span><span class="kw2">self</span>, shape1, shape2<span class="br0">)</span>:
<span class="co1"># Implements the default behavior of b2ContactFilter in Python</span>
filter1 = shape1.<span class="me1">GetFilterData</span><span class="br0">(</span><span class="br0">)</span>
filter2 = shape2.<span class="me1">GetFilterData</span><span class="br0">(</span><span class="br0">)</span>
<span class="kw1">if</span> filter1.<span class="me1">groupIndex</span> == filter2.<span class="me1">groupIndex</span> <span class="kw1">and</span> filter1.<span class="me1">groupIndex</span> != <span class="nu0">0</span>:
<span class="kw1">return</span> filter1.<span class="me1">groupIndex</span> > <span class="nu0">0</span>
collide = <span class="br0">(</span>filter1.<span class="me1">maskBits</span> & filter2.<span class="me1">categoryBits</span><span class="br0">)</span> != <span class="nu0">0</span> <span class="kw1">and</span> <span class="br0">(</span>filter1.<span class="me1">categoryBits</span> & filter2.<span class="me1">maskBits</span><span class="br0">)</span> != <span class="nu0">0</span>
<span class="kw1">return</span> collide
<span class="co1"># Setting it:</span>
myCF = MyContactFilter<span class="br0">(</span><span class="br0">)</span>
world.<span class="me1">SetContactFilter</span><span class="br0">(</span> myCF <span class="br0">)</span></pre></div>
<a name="Loose_Ends"></a><h1><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-74" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Loose Ends</span></h1>
<a name="World_Boundary"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-75" title="Template:Manual">edit</a>]</span> <span class="mw-headline">World Boundary</span></h2>
<p>You can implement a <i>b2BoundaryListener</i> that allows <i>b2World</i>
to inform you when a body has gone outside the world AABB. When you get
the callback, you shouldn't try to delete the body, instead you should
mark the parent actor for deletion or error handling. After the physics
time step, you should handle the event.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python"><span class="kw1">class</span> MyBoundaryListener<span class="br0">(</span>b2BoundaryListener<span class="br0">)</span>:
<span class="kw1">def</span> <span class="kw4">__init__</span><span class="br0">(</span><span class="kw2">self</span><span class="br0">)</span>:
<span class="kw2">super</span><span class="br0">(</span>MyBoundaryListener, <span class="kw2">self</span><span class="br0">)</span>.<span class="kw4">__init__</span><span class="br0">(</span><span class="br0">)</span>
<span class="kw1">def</span> Violation<span class="br0">(</span><span class="kw2">self</span>, body<span class="br0">)</span>:
myActor = body.<span class="me1">userData</span><span class="br0">[</span><span class="st0">'actor'</span><span class="br0">]</span> <span class="co1"># if you stored it as a dict</span>
myActor.<span class="me1">MarkForErrorHandling</span><span class="br0">(</span><span class="br0">)</span></pre></div>
<p>You can then register an instance of your boundary listener with
your world object. You should do this during world initialization.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">myWorld.<span class="me1">SetBoundaryListener</span><span class="br0">(</span>myBoundaryListener<span class="br0">)</span></pre></div>
<a name="Implicit_Destruction"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-76" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Implicit Destruction</span></h2>
<p>Box2D doesn't use reference counting. So if you destroy a body it is
really gone. Accessing a pointer to a destroyed body has undefined
behavior. In other words, your program will likely crash and burn. To
help fix these problems, the debug build memory manager fills destroyed
entities with <i>FDFDFDFD</i>. This can help find problems more easily in some cases.
</p><p>If you destroy a Box2D entity, it is up to you to make sure you
remove all references to the destroyed object. This is easy if you only
have a single reference to the entity. If you have multiple references,
you might consider implementing a <b>handle</b> class to wrap the raw pointer.
</p><p>Often when using Box2D you will create and destroy many bodies,
shapes, and joints. Managing these entities is somewhat automated by
Box2D. If you destroy a body then all associated shapes and joints are
automatically destroyed. This is called <b>implicit destruction</b>.
</p><p>When you destroy a body, all its attached shapes, joints, and contacts are destroyed. This is called <b>implicit destruction</b>.
Any body connected to one of those joints and/or contacts is woken.
This process is usually convenient. However, you must be aware of one
crucial issue:
</p><p><b>Caution</b>
</p><p>When a body is destroyed, all shapes and joints attached to the
body are automatically destroyed. You must nullify any pointers you
have to those shapes and joints. Otherwise, your program will <b>die horribly</b> if you try to access or destroy those shapes or joints later.
</p><p>To help you nullify your joint pointers, Box2D provides a listener class named <i>b2WorldListener</i>
that you can implement and provide to your world object. Then the world
object will notify you when a joint is going to be implicity destroyed.
</p><p>Implicit destruction is a great convenience in many cases. It
can also make your program fall apart. You may store pointers to shapes
and joints somewhere in your code. These pointers become orphaned when
an associated body is destroyed. The situation becomes worse when you
consider that joints are often created by a part of the code unrelated
to management of the associated body. For example, the testbed creates
a <i>b2MouseJoint</i> for interactive manipulation of bodies on the screen.
</p><p>Box2D provides a callback mechanism to inform your application
when implicit destruction occurs. This gives your application a chance
to nullify the orphaned pointers. This callback mechanism is described
later in this manual.
</p><p>You can implement a <i>b2DestructionListener</i> that allows <i>b2World</i>
to inform you when a shape or joint is implicitly destroyed because an
associated body was destroyed. This will help prevent your code from
accessing orphaned pointers.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python"><span class="kw1">class</span> MyDestructionListener<span class="br0">(</span>b2DestructionListener<span class="br0">)</span>:
<span class="kw1">def</span> <span class="kw4">__init__</span><span class="br0">(</span><span class="kw2">self</span><span class="br0">)</span>:
<span class="kw2">super</span><span class="br0">(</span>MyDestructionListener, <span class="kw2">self</span><span class="br0">)</span>.<span class="kw4">__init__</span><span class="br0">(</span><span class="br0">)</span>
<span class="kw1">def</span> SayGoodbye<span class="br0">(</span><span class="kw2">self</span>, joint<span class="br0">)</span>:
<span class="co1"># remove all references to joint.</span>
<span class="kw1">pass</span></pre></div>
<p>You can then register an instance of your destruction listener with
your world object. You should do this during world initialization.
</p>
<div dir="ltr" style="text-align: left;"><pre class="source-python">myWorld.<span class="me1">SetDestructionListener</span><span class="br0">(</span>myDestructionListener<span class="br0">)</span></pre></div>
<a name="Settings"></a><h1><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-77" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Settings</span></h1>
<a name="About_7"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-78" title="Template:Manual">edit</a>]</span> <span class="mw-headline">About</span></h2>
<p>There are two source files included in Box2D that are supplied specifically for user customization. These are <i>b2Settings.h</i> and <i>b2Settings.cpp</i>.
</p><p>Box2D works with floating point numbers, so some tolerances have to be used to make Box2D perform well.
</p>
<a name="Tolerances"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-79" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Tolerances</span></h2>
<p>There are many tolerances settings that depend on using MKS units. See <a href="http://www.box2d.org/wiki/index.php?title=Python_Manual#Units" title="Python Manual">Units</a> for a deeper explanation of the unit system. See the doxygen docs for explanation of the individual tolerances.
</p>
<a name="Memory_Allocation"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-80" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Memory Allocation</span></h2>
<p>All of Box2D's memory allocations are funnelled through <i>b2Alloc</i> and <i>b2Free</i> except in the following cases.
</p>
<ul><li> <i>b2World</i> can be built on the stack or with whatever allocator you like.
</li><li> Any other Box2D class that you create without using a factory
method. This includes things like callbacks classes and contact point
buffers.
</li></ul>
<p>Feel free to redirect the allocation by modifying <i>b2Settings.cpp</i>.
</p>
<a name="Rendering"></a><h1><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-81" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Rendering</span></h1>
<a name="Debug_Drawing"></a><h2><span class="editsection">[<a href="http://www.box2d.org/wiki/index.php?title=Template:Manual&action=edit&section=T-82" title="Template:Manual">edit</a>]</span> <span class="mw-headline">Debug Drawing</span></h2>
<p><b>Note:</b> Debug Drawing should probably not be used for your final game. Its purpose is as the name implies, debugging.
</p><p>You can implement the <i>b2DebugDraw</i> class to get detailed drawing of the physics world. Here are the available entities:
</p>
<ul><li> shape outlines
</li><li> joint connectivity
</li><li> core shapes (for continuous collision)
</li><li> broad-phase axis-aligned bounding boxes (AABBs), including the world AABB
</li><li> polygon oriented bounding boxes (OBBs)
</li><li> broad-phase pairs (potential contacts)
</li><li> center of mass
</li></ul>
<p>This the preferred method of drawing these physics entities for
debugging, rather than accessing the data directly. The reason is that
much of the necessary data is internal and subject to change.
</p><p>The testbed draws physics entities using the debug draw
facility and the contact listener, so it serves as the primary example
of how to implement debug drawing as well as how to draw contact
points.
</p><p>See the pyBox2D <a href="http://www.box2d.org/wiki/index.php?title=Box2D_with_Python#b2DebugDraw_Callbacks" class="mw-redirect" title="Box2D with Python">b2DebugDraw Callbacks</a> section.
</p>
<!--
NewPP limit report
Preprocessor node count: 892/1000000
Post-expand include size: 76470/2097152 bytes
Template argument size: 522/2097152 bytes
#ifexist count: 0/100
-->
<!-- Saved in parser cache with key erincatto_wiki:pcache:idhash:85-0!1!0!!en!2 and timestamp 20090224230137 -->
<div class="printfooter">
Retrieved from "<a href="http://www.box2d.org/wiki/index.php?title=Python_Manual">http://www.box2d.org/wiki/index.php?title=Python_Manual</a>"</div>
<!-- end content -->
<div class="visualClear"></div>
</div>
</div>
</div>
<div id="column-one">
<div id="p-cactions" class="portlet">
<h5>Views</h5>
<div class="pBody">
<ul>
<li id="ca-nstab-main" class="selected"><a href="http://www.box2d.org/wiki/index.php?title=Python_Manual" title="View the content page [alt-c]" accesskey="c">Page</a></li>
<li id="ca-talk" class="new"><a href="http://www.box2d.org/wiki/index.php?title=Talk:Python_Manual&action=edit" title="Discussion about the content page [alt-t]" accesskey="t">Discussion</a></li>
<li id="ca-edit"><a href="http://www.box2d.org/wiki/index.php?title=Python_Manual&action=edit" title="You can edit this page. Please use the preview button before saving. [alt-e]" accesskey="e">Edit</a></li>
<li id="ca-history"><a href="http://www.box2d.org/wiki/index.php?title=Python_Manual&action=history" title="Past versions of this page. [alt-h]" accesskey="h">History</a></li>
<li id="ca-move"><a href="http://www.box2d.org/wiki/index.php?title=Special:Movepage/Python_Manual" title="Move this page [alt-m]" accesskey="m">Move</a></li>
<li id="ca-unwatch"><a href="http://www.box2d.org/wiki/index.php?title=Python_Manual&action=unwatch" title="Remove this page from your watchlist [alt-w]" accesskey="w">Unwatch</a></li>
</ul>
</div>
</div>
<div class="portlet" id="p-personal">
<h5>Personal tools</h5>
<div class="pBody">
<ul>
<li id="pt-userpage"><a href="http://www.box2d.org/wiki/index.php?title=User:Kne" title="My user page [alt-.]" accesskey="." class="new">Kne</a></li>
<li id="pt-mytalk"><a href="http://www.box2d.org/wiki/index.php?title=User_talk:Kne" title="My talk page [alt-n]" accesskey="n" class="new">My talk</a></li>
<li id="pt-preferences"><a href="http://www.box2d.org/wiki/index.php?title=Special:Preferences" title="My preferences">My preferences</a></li>
<li id="pt-watchlist"><a href="http://www.box2d.org/wiki/index.php?title=Special:Watchlist" title="The list of pages you're monitoring for changes [alt-l]" accesskey="l">My watchlist</a></li>
<li id="pt-mycontris"><a href="http://www.box2d.org/wiki/index.php?title=Special:Contributions/Kne" title="List of my contributions [alt-y]" accesskey="y">My contributions</a></li>
<li id="pt-logout"><a href="http://www.box2d.org/wiki/index.php?title=Special:Userlogout&returnto=Python_Manual" title="Log out">Log out</a></li>
</ul>
</div>
</div>
<div class="portlet" id="p-logo">
<a style="background-image: url(/images/icon.gif);" href="http://www.box2d.org/wiki/index.php?title=Main_Page" title="Visit the Main Page [alt-z]" accesskey="z"></a>
</div>
<script type="text/javascript"> if (window.isMSIE55) fixalpha(); </script>
<div class="portlet" id="p-navigation">
<h5>Navigation</h5>
<div class="pBody">
<ul>
<li id="n-mainpage"><a href="http://www.box2d.org/wiki/index.php?title=Main_Page" title="Visit the Main Page [alt-z]" accesskey="z">Main Page</a></li>
<li id="n-portal"><a href="http://www.box2d.org/wiki/index.php?title=Box2D_Wiki:Community_Portal" title="About the project, what you can do, where to find things">Community portal</a></li>
<li id="n-currentevents"><a href="http://www.box2d.org/wiki/index.php?title=Box2D_Wiki:Current_events" title="Find background information on current events">Current events</a></li>
<li id="n-recentchanges"><a href="http://www.box2d.org/wiki/index.php?title=Special:Recentchanges" title="The list of recent changes in the wiki. [alt-r]" accesskey="r">Recent changes</a></li>
<li id="n-randompage"><a href="http://www.box2d.org/wiki/index.php?title=Special:Random" title="Load a random page [alt-x]" accesskey="x">Random page</a></li>
<li id="n-help"><a href="http://www.box2d.org/wiki/index.php?title=Help:Contents" title="The place to find out.">Help</a></li>
<li id="n-sitesupport"><a href="http://www.box2d.org/wiki/index.php?title=Box2D_Wiki:Site_support" title="Support us">Donations</a></li>
</ul>
</div>
</div>
<div id="p-search" class="portlet">
<h5><label for="searchInput">Search</label></h5>
<div id="searchBody" class="pBody">
<form action="/wiki/index.php?title=Special:Search" id="searchform"><div>
<input id="searchInput" name="search" title="Search Box2D Wiki [alt-f]" accesskey="f" value="" type="text">
<input name="go" class="searchButton" id="searchGoButton" value="Go" title="Go to a page with this exact name if exists" type="submit">
<input name="fulltext" class="searchButton" id="mw-searchButton" value="Search" title="Search the pages for this text" type="submit">
</div></form>
</div>
</div>
<div class="portlet" id="p-tb">
<h5>Toolbox</h5>
<div class="pBody">
<ul>
<li id="t-whatlinkshere"><a href="http://www.box2d.org/wiki/index.php?title=Special:Whatlinkshere/Python_Manual" title="List of all wiki pages that link here [alt-j]" accesskey="j">What links here</a></li>
<li id="t-recentchangeslinked"><a href="http://www.box2d.org/wiki/index.php?title=Special:Recentchangeslinked/Python_Manual" title="Recent changes in pages linked from this page [alt-k]" accesskey="k">Related changes</a></li>
<li id="t-upload"><a href="http://www.box2d.org/wiki/index.php?title=Special:Upload" title="Upload files [alt-u]" accesskey="u">Upload file</a></li>
<li id="t-specialpages"><a href="http://www.box2d.org/wiki/index.php?title=Special:Specialpages" title="List of all special pages [alt-q]" accesskey="q">Special pages</a></li>
<li id="t-print"><a href="http://www.box2d.org/wiki/index.php?title=Python_Manual&printable=yes&printable=yes" title="Printable version of this page [alt-p]" accesskey="p">Printable version</a></li> <li id="t-permalink"><a href="http://www.box2d.org/wiki/index.php?title=Python_Manual&oldid=400" title="Permanent link to this version of the page">Permanent link</a></li> </ul>
</div>
</div>
</div><!-- end of the left (by default at least) column -->
<div class="visualClear"></div>
<div id="footer">
<div id="f-poweredbyico"><a href="http://www.mediawiki.org/"><img src="manual_files/poweredby_mediawiki_88x31.png" alt="Powered by MediaWiki"></a></div>
<ul id="f-list">
<li id="lastmod"> This page was last modified 05:14, 6 October 2008.</li>
<li id="viewcount">This page has been accessed 3,607 times.</li>
<li id="privacy"><a href="http://www.box2d.org/wiki/index.php?title=Box2D_Wiki:Privacy_policy" title="Box2D Wiki:Privacy policy">Privacy policy</a></li>
<li id="about"><a href="http://www.box2d.org/wiki/index.php?title=Box2D_Wiki:About" title="Box2D Wiki:About">About Box2D Wiki</a></li>
<li id="disclaimer"><a href="http://www.box2d.org/wiki/index.php?title=Box2D_Wiki:General_disclaimer" title="Box2D Wiki:General disclaimer">Disclaimers</a></li>
</ul>
</div>
<script type="text/javascript">if (window.runOnloadHook) runOnloadHook();</script>
</div>
<!-- Served in 0.527 secs. --></body></html>
|