Spaces:
Running
Running
File size: 61,004 Bytes
db9635c |
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 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 |
# VibeGame Engine A 3D game engine with declarative XML syntax and ECS architecture. Start playing immediately with automatic player, camera, and lighting - just add a ground to prevent falling. ## Core Architecture ### ECS (Entity Component System) - **Entities**: Just numbers (IDs), no data or behavior - **Components**: Pure data containers (position, health, color) - **Systems**: Functions that process entities with specific components - **Queries**: Find entities with specific component combinations ### Plugin System Bevy-inspired modular architecture: - **Components**: Data definitions using bitECS - **Systems**: Logic organized by update phases (setup, fixed, simulation, draw) - **Recipes**: XML entity templates with preset components - **Config**: Defaults, shorthands, enums, validations, parsers ### Update Phases 1. **SetupBatch**: Input gathering and frame setup 2. **FixedBatch**: Physics simulation at fixed timestep (50Hz) 3. **SimulationBatch**: Game logic and state updates 4. **DrawBatch**: Rendering and interpolation ## Critical Rules β οΈ **Physics Position Override**: Physics bodies override transform positions. Always use `pos` attribute on physics entities, not transform position. β οΈ **Ground Required**: Always include ground/platforms or the player falls infinitely. β οΈ **Component Declaration**: Bare attributes mean "include with defaults", not "empty". ## Essential Knowledge ## Instant Playable Game ```html <script src="https://cdn.jsdelivr.net/npm/vibegame@latest/dist/cdn/vibegame.standalone.iife.js"></script> <world canvas="#game-canvas" sky="#87ceeb"> <!-- Ground (REQUIRED to prevent player falling) --> <static-part pos="0 -0.5 0" shape="box" size="20 1 20" color="#90ee90"></static-part> </world> <canvas id="game-canvas"></canvas> <script> GAME.run(); </script> ``` This creates a complete game with: - β Player character (auto-created) - β Orbital camera (auto-created) - β Directional + ambient lighting (auto-created) - β Ground platform (you provide this) - β WASD movement, mouse camera, space to jump ## Development Setup After installation with `npm create vibegame@latest my-game`: ```bash cd my-game bun dev # Start dev server with hot reload ``` ### Project Structure - **TypeScript** - Full TypeScript support with strict type checking - **src/main.ts** - Entry point for your game - **index.html** - HTML template with canvas element - **vite.config.ts** - Build configuration ### Commands - `bun dev` - Development server with hot reload - `bun run build` - Production build - `bun run preview` - Preview production build - `bun run check` - TypeScript type checking - `bun run lint` - Lint code with ESLint - `bun run format` - Format code with Prettier ## Physics Objects ```xml <world canvas="#game-canvas"> <!-- 1. Static: Never moves (grounds, walls, platforms) --> <static-part pos="0 -0.5 0" shape="box" size="20 1 20" color="#808080"></static-part> <!-- 2. Dynamic: Falls with gravity (balls, crates, debris) --> <dynamic-part pos="0 5 0" shape="sphere" size="1" color="#ff0000"></dynamic-part> <!-- 3. Kinematic: Script-controlled movement (moving platforms, doors) --> <kinematic-part pos="5 2 0" shape="box" size="3 0.5 3" color="#0000ff"> <!-- Animate the platform up and down --> <tween target="body.pos-y" from="2" to="5" duration="3" loop="ping-pong"></tween> </kinematic-part> </world> ``` ## CRITICAL: Physics Position vs Transform Position <warning> β οΈ **Physics bodies override transform positions!** Always set position on the body, not the transform, for physics entities. </warning> ```xml <!-- β BEST: Use recipe with pos shorthand --> <dynamic-part pos="0 5 0" shape="sphere" size="1"></dynamic-part> <!-- β WRONG: Transform position ignored if body exists --> <entity transform="pos: 0 5 0" body collider></entity> <!-- Falls to 0,0,0! --> <!-- β CORRECT: Set body position explicitly (if using raw entity) --> <entity transform body="pos: 0 5 0" collider></entity> ``` ## ECS Architecture Explained Unlike traditional game engines with GameObjects, VibeGame uses Entity-Component-System: - **Entities**: Just numbers (IDs), no data or behavior - **Components**: Pure data containers (position, health, color) - **Systems**: Functions that process entities with specific components ```typescript // Component = Data only const Health = GAME.defineComponent({ current: GAME.Types.f32, max: GAME.Types.f32 }); // System = Logic only const healthQuery = GAME.defineQuery([Health]); const DamageSystem: GAME.System = { update: (state) => { const entities = healthQuery(state.world); for (const entity of entities) { Health.current[entity] -= 1 * state.time.deltaTime; if (Health.current[entity] <= 0) { state.destroyEntity(entity); } } } }; ``` ## What's Auto-Created (Game Engine Defaults) The engine automatically creates these if missing: 1. **Player** - Character with physics, controls, and respawn (at 0, 1, 0) 2. **Camera** - Orbital camera following the player 3. **Lighting** - Ambient + directional light with shadows You only need to provide: - **Ground/platforms** - Or the player falls forever - **Game objects** - Whatever makes your game unique ### Override Auto-Creation (When Needed) While auto-creation is recommended, you can manually create these for customization: ```xml <world canvas="#game-canvas"> <static-part pos="0 -0.5 0" shape="box" size="20 1 20" color="#90ee90"></static-part> <!-- Custom player spawn position and properties --> <player pos="0 10 0" speed="8" jump-height="3"></player> <!-- Custom camera settings --> <camera orbit-camera="distance: 10; target-pitch: 0.5"></camera> <!-- Custom lighting (or use <light> for both ambient + directional) --> <ambient-light sky-color="#ff6b6b" ground-color="#4ecdc4" intensity="0.8"></ambient-light> <directional-light color="#ffffff" intensity="0.5" direction="-1 -2 -1"></directional-light> </world> ``` **Best Practice**: Use auto-creation unless you specifically need custom positions, properties, or multiple instances. The defaults are well-tuned for most games. ## Post-Processing Effects ```xml <!-- Bloom effect for glow --> <camera bloom="intensity: 2; luminance-threshold: 0.8"></camera> <!-- Retro dithering (reduces color palette) --> <camera dithering="color-bits: 3; scale: 2; noise: 1"></camera> <!-- Tonemapping for HDR-like visuals --> <camera tonemapping="mode: aces-filmic"></camera> <!-- Combined cinematic style --> <camera bloom="intensity: 1.5" tonemapping="mode: aces-filmic"></camera> ``` ## Common Game Patterns ### Basic Platformer ```xml <world canvas="#game-canvas"> <!-- Ground --> <static-part pos="0 -0.5 0" shape="box" size="50 1 50" color="#90ee90"></static-part> <!-- Platforms at different heights --> <static-part pos="-5 2 0" shape="box" size="3 0.5 3" color="#808080"></static-part> <static-part pos="0 4 0" shape="box" size="3 0.5 3" color="#808080"></static-part> <static-part pos="5 6 0" shape="box" size="3 0.5 3" color="#808080"></static-part> <!-- Moving platform --> <kinematic-part pos="0 3 5" shape="box" size="4 0.5 4" color="#4169e1"> <tween target="body.pos-x" from="-10" to="10" duration="5" loop="ping-pong"></tween> </kinematic-part> <!-- Goal area --> <static-part pos="10 8 0" shape="box" size="5 0.5 5" color="#ffd700"></static-part> </world> ``` ### Collectible Coins (Collision-based) ```xml <world canvas="#game-canvas"> <static-part pos="0 -0.5 0" shape="box" size="20 1 20" color="#90ee90"></static-part> <!-- Spinning coins --> <kinematic-part pos="2 1 0" shape="cylinder" size="0.5 0.1 0.5" color="#ffd700"> <tween target="body.euler-y" from="0" to="360" duration="2" loop="loop"></tween> </kinematic-part> <kinematic-part pos="-2 1 0" shape="cylinder" size="0.5 0.1 0.5" color="#ffd700"> <tween target="body.euler-y" from="0" to="360" duration="2" loop="loop"></tween> </kinematic-part> </world> ``` ### Physics Playground ```xml <world canvas="#game-canvas"> <!-- Ground --> <static-part pos="0 -0.5 0" shape="box" size="30 1 30" color="#90ee90"></static-part> <!-- Walls --> <static-part pos="15 5 0" shape="box" size="1 10 30" color="#808080"></static-part> <static-part pos="-15 5 0" shape="box" size="1 10 30" color="#808080"></static-part> <static-part pos="0 5 15" shape="box" size="30 10 1" color="#808080"></static-part> <static-part pos="0 5 -15" shape="box" size="30 10 1" color="#808080"></static-part> <!-- Spawn balls at different positions --> <dynamic-part pos="-5 10 0" shape="sphere" size="1" color="#ff0000"></dynamic-part> <dynamic-part pos="0 12 0" shape="sphere" size="1.5" color="#00ff00"></dynamic-part> <dynamic-part pos="5 8 0" shape="sphere" size="0.8" color="#0000ff"></dynamic-part> <!-- Bouncy ball (high restitution) --> <dynamic-part pos="0 15 5" shape="sphere" size="1" color="#ff00ff" collider="restitution: 0.9"></dynamic-part> </world> ``` ## Recipe Reference | Recipe | Purpose | Key Attributes | Common Use | |--------|---------|---------------|------------| | `<static-part>` | Immovable objects | `pos`, `shape`, `size`, `color` | Grounds, walls, platforms | | `<dynamic-part>` | Gravity-affected objects | `pos`, `shape`, `size`, `color`, `mass` | Balls, crates, falling objects | | `<kinematic-part>` | Script-controlled physics | `pos`, `shape`, `size`, `color` | Moving platforms, doors | | `<player>` | Player character | `pos`, `speed`, `jump-height` | Main character (auto-created) | | `<entity>` | Base entity | Any components via attributes | Custom entities | ### Shape Options - `box` - Rectangular solid (default) - `sphere` - Ball shape - `cylinder` - Cylindrical shape - `capsule` - Pill shape (good for characters) ### Size Attribute - Box: `size="width height depth"` or `size="2 1 2"` - Sphere: `size="diameter"` or `size="1"` - Cylinder: `size="diameter height"` or `size="1 2"` - Broadcast: `size="2"` becomes `size="2 2 2"` ## How Recipes and Shorthands Work ### Everything is an Entity Every XML tag creates an entity. Recipes like `<static-part>` are just shortcuts for `<entity>` with preset components. ```xml <!-- These are equivalent: --> <static-part pos="0 0 0" color="#ff0000"></static-part> <entity transform body="type: fixed" collider renderer="color: 0xff0000" pos="0 0 0"></entity> ``` ### Component Attributes Components are declared using bare attributes (no value means "use defaults"): ```xml <!-- Bare attributes declare components with default values --> <entity transform body collider renderer></entity> <!-- Add properties to override defaults --> <entity transform="pos-x: 5; pos-y: 2; pos-z: -3; scale: 2"></entity> <!-- Mix bare and valued attributes --> <entity transform="pos: 0 5 0" body="type: dynamic; mass: 10" collider renderer></entity> <!-- Property groups --> <entity transform="pos: 5 2 -3; scale: 2 2 2"></entity> ``` **Important**: Bare attributes like `transform` mean "include this component with default values", NOT "empty" or "disabled". ### Automatic Shorthand Expansion Shorthands expand to ANY component with matching properties: ```xml <!-- "pos" shorthand applies to components with posX, posY, posZ --> <entity transform body pos="0 5 0"></entity> <!-- Both transform AND body get pos values --> <!-- "color" shorthand applies to renderer.color --> <entity renderer color="#ff0000"></entity> <!-- "size" shorthand (broadcasts single value) --> <entity collider size="2"></entity> <!-- Expands to: sizeX: 2, sizeY: 2, sizeZ: 2 --> <!-- Multiple shorthands together --> <entity transform body collider renderer pos="0 5 0" size="1" color="#ff0000"></entity> ``` ### Recipe Internals Recipes are registered component bundles with defaults: ```xml <!-- What <dynamic-part> actually is: --> <entity transform body="type: dynamic" <!-- Override --> collider renderer respawn ></entity> <!-- So this: --> <dynamic-part pos="0 5 0" color="#ff0000"></dynamic-part> <!-- Is really: --> <entity transform="pos: 0 5 0" body="type: dynamic; pos: 0 5 0" <!-- pos applies to body too! --> collider renderer="color: 0xff0000" respawn ></entity> ``` ### Common Pitfall: Component Requirements ```xml <!-- β BAD: Missing required components --> <entity pos="0 5 0"></entity> <!-- No transform component! --> <!-- β GOOD: Explicit components --> <entity transform="pos: 0 5 0"></entity> <!-- β BEST: Use recipe with built-in components --> <static-part pos="0 5 0"></static-part> ``` ### Best Practices Summary 1. **Use recipes** (`<static-part>`, `<dynamic-part>`, etc.) instead of raw `<entity>` tags 2. **Use shorthands** (`pos`, `size`, `color`) for cleaner code 3. **Override only what you need** - recipes have good defaults 4. **Mix recipes with custom components** - e.g., `<dynamic-part health="max: 100">` ## Currently Supported Features ### β What Works Well - **Basic platforming** - Jump puzzles, obstacle courses - **Physics interactions** - Balls, dominoes, stacking - **Moving platforms** - Via kinematic bodies + tweening - **Collectibles** - Using collision detection in systems - **Third-person character control** - WASD + mouse camera - **Gamepad support** - Xbox/PlayStation controllers - **Visual effects** - Tweening colors, positions, rotations - **Post-processing** - Bloom, dithering, and tonemapping effects for visual styling - **Game UI/HUD** - HTML/CSS overlays with GSAP animations, ECS state integration ### Example Prompts That Work - "Create a platformer with moving platforms and collectible coins" - "Make bouncing balls that collide with walls" - "Build an obstacle course with rotating platforms" - "Add falling crates that stack up" - "Create a simple parkour level" - "Add a score display and upgrade menu with animations" - "Create a game with currency system and floating text effects" ### Troubleshooting - **Physics not working?** β Check if ground exists, verify `<world>` tag - **Entity not appearing?** β Verify transform component, check position values - **Movement feels wrong?** β Physics body position overrides transform position - **Player falling forever?** β Add a ground/platform with `<static-part>` ## Plugin Development Pattern ```typescript // Component Definition export const MyComponent = GAME.defineComponent({ value: GAME.Types.f32, enabled: GAME.Types.ui8 }); // System Definition const myQuery = GAME.defineQuery([MyComponent]); export const MySystem: GAME.System = { group: 'simulation', // or 'setup', 'fixed', 'draw' update: (state) => { const entities = myQuery(state.world); for (const entity of entities) { // System logic MyComponent.value[entity] += state.time.deltaTime; } } }; // Plugin Bundle export const MyPlugin: GAME.Plugin = { components: { MyComponent }, systems: [MySystem], config: { defaults: { "my-component": { value: 1, enabled: 1 } }, shorthands: { "my-val": "my-component.value" } } }; // Registration GAME.withPlugin(MyPlugin).run(); ``` ## State Management Patterns ### Singleton Entities (Game State) ```typescript function getOrCreateGameState(state: GAME.State): number { const query = GAME.defineQuery([GameState]); const entities = query(state.world); if (entities.length > 0) return entities[0]; const entity = state.createEntity(); state.addComponent(entity, GameState, { score: 0, level: 1 }); return entity; } ``` ### Component Access (bitECS style) ```typescript // Direct property access GAME.Transform.posX[entity] = 10; GAME.Transform.posY[entity] = 5; // Read values const x = GAME.Transform.posX[entity]; const health = GAME.Health.current[entity]; ``` ## Features Not Yet Built-In ### β Engine Features Not Available - **Multiplayer/Networking** - No server sync - **Sound/Audio** - No audio system yet - **Save/Load** - No persistence system - **Inventory** - No item management system built-in (but easily implementable with UI) - **Dialog/NPCs** - No conversation system built-in (but easily implementable with UI) - **AI/Pathfinding** - No enemy AI - **Particles** - No particle effects (though UI can create particle-like effects) - **Custom shaders** - Fixed rendering pipeline - **Terrain** - Use box platforms instead ### Recommended Approaches - **Complex UI** β HTML/CSS overlays (this is actually superior to most game engines) - **Animations** β GSAP for smooth transitions and effects - **Level progression** β Reload with different XML or hide/show worlds - **Enemy behavior** β Tweened movement patterns - **Interactions** β Collision detection in custom systems ## Common Mistakes to Avoid ### β Forgetting the Ground ```xml <!-- BAD: No ground, player falls forever --> <world canvas="#game-canvas"> <dynamic-part pos="0 5 0" shape="sphere"></dynamic-part> </world> ``` ### β Setting Transform Position on Physics Objects ```xml <!-- BAD: Transform position ignored --> <entity transform="pos: 0 5 0" body collider></entity> <!-- GOOD: Set body position (raw entity) --> <entity transform body="pos: 0 5 0" collider></entity> <!-- BEST: Use recipes with pos shorthand --> <dynamic-part pos="0 5 0" shape="sphere"></dynamic-part> ``` ### β Missing World Tag ```xml <!-- BAD: Entities outside world tag --> <static-part pos="0 0 0" shape="box"></static-part> <!-- GOOD: Everything inside world --> <world canvas="#game-canvas"> <static-part pos="0 0 0" shape="box"></static-part> </world> ``` ### β Wrong Physics Type ```xml <!-- BAD: Dynamic platform (falls with gravity) --> <dynamic-part pos="0 3 0" shape="box"> <tween target="body.pos-x" from="-5" to="5"></tween> </dynamic-part> <!-- GOOD: Kinematic for controlled movement --> <kinematic-part pos="0 3 0" shape="box"> <tween target="body.pos-x" from="-5" to="5"></tween> </kinematic-part> ``` ## Custom Components and Systems ### Creating a Health System ```typescript import * as GAME from 'vibegame'; // Define the component const Health = GAME.defineComponent({ current: GAME.Types.f32, max: GAME.Types.f32 }); // Create the system const HealthSystem: GAME.System = { update: (state) => { const entities = GAME.defineQuery([Health])(state.world); for (const entity of entities) { // Regenerate health over time if (Health.current[entity] < Health.max[entity]) { Health.current[entity] += 5 * state.time.deltaTime; } } } }; // Bundle as plugin const HealthPlugin: GAME.Plugin = { components: { Health }, systems: [HealthSystem], config: { defaults: { "health": { current: 100, max: 100 } } } }; // Use in game GAME.withPlugin(HealthPlugin).run(); ``` ### Using in XML ```xml <world canvas="#game-canvas"> <!-- Add health to a dynamic entity (best practice: use recipes) --> <dynamic-part pos="0 2 0" shape="sphere" color="#ff0000" health="current: 50; max: 100"></dynamic-part> </world> ``` ## State API Reference Available in all systems via the `state` parameter: ### Entity Management - `createEntity(): number` - Create new entity - `destroyEntity(entity: number)` - Remove entity - `query(...Components): number[]` - Find entities with components ### Component Operations - `addComponent(entity, Component, data?)` - Add component - `removeComponent(entity, Component)` - Remove component - `hasComponent(entity, Component): boolean` - Check component - `getComponent(name: string): Component | null` - Get by name ### Time - `time.delta: number` - Frame time in seconds - `time.elapsed: number` - Total time in seconds - `time.fixed: number` - Fixed timestep (1/50) ### Physics Helpers - `addComponent(entity, ApplyImpulse, {x, y, z})` - One-time push - `addComponent(entity, ApplyForce, {x, y, z})` - Continuous force - `addComponent(entity, KinematicMove, {x, y, z})` - Move kinematic ## Plugin System ### Using Specific Plugins ```typescript import * as GAME from 'vibegame'; // Start with no plugins GAME .withoutDefaultPlugins() .withPlugin(TransformsPlugin) // Just transforms .withPlugin(RenderingPlugin) // Add rendering .withPlugin(PhysicsPlugin) // Add physics .run(); ``` ### Default Plugin Bundle - **RecipesPlugin** - XML parsing and entity creation - **TransformsPlugin** - Position, rotation, scale, hierarchy - **RenderingPlugin** - Three.js meshes, lights, camera - **PhysicsPlugin** - Rapier physics simulation - **InputPlugin** - Keyboard, mouse, gamepad input - **OrbitCameraPlugin** - Third-person camera - **PlayerPlugin** - Character controller - **TweenPlugin** - Animation system - **RespawnPlugin** - Fall detection and reset - **StartupPlugin** - Auto-create player/camera/lights ## Plugin Reference ### Core Math utilities for interpolation and 3D transformations. ### Functions #### lerp(a, b, t): number Linear interpolation #### slerp(fromX, fromY, fromZ, fromW, toX, toY, toZ, toW, t): Quaternion Quaternion spherical interpolation #### Examples ## Usage Note Math utilities are used internally by systems like tweening and transforms. For animating properties, use the Tween system instead of directly calling interpolation functions. For transformations, use the Transform component's euler angles which are automatically converted to quaternions by the system. ### Animation Procedural character animation with body parts that respond to movement states. ### Components #### AnimatedCharacter - headEntity: eid - torsoEntity: eid - leftArmEntity: eid - rightArmEntity: eid - leftLegEntity: eid - rightLegEntity: eid - phase: f32 - Walk cycle phase (0-1) - jumpTime: f32 - fallTime: f32 - animationState: ui8 - 0=IDLE, 1=WALKING, 2=JUMPING, 3=FALLING, 4=LANDING - stateTransition: f32 #### HasAnimator Tag component (no properties) ### Systems #### AnimatedCharacterInitializationSystem - Group: setup - Creates body part entities for AnimatedCharacter components #### AnimatedCharacterUpdateSystem - Group: simulation - Updates character animation based on movement and physics state #### Examples ## Examples ### Basic Usage ```typescript import * as GAME from 'vibegame'; // Add animated character to a player entity const player = state.createEntity(); state.addComponent(player, GAME.AnimatedCharacter); state.addComponent(player, GAME.CharacterController); state.addComponent(player, GAME.Transform); // The AnimatedCharacterInitializationSystem will automatically // create body parts in the next setup phase ``` ### Accessing Animation State ```typescript import * as GAME from 'vibegame'; const characterQuery = GAME.defineQuery([GAME.AnimatedCharacter]); const MySystem: GAME.System = { update: (state) => { const characters = characterQuery(state.world); for (const entity of characters) { const animState = GAME.AnimatedCharacter.animationState[entity]; if (animState === 2) { // JUMPING console.log('Character is jumping!'); } } } }; ``` ### XML Declaration ```xml <!-- Player entity with animated character --> <entity animated-character character-controller transform="pos: 0 2 0" /> ``` ### Input Focus-aware input handling for mouse, keyboard, and gamepad with buffered actions. Keyboard input only responds when canvas has focus. ### Components #### InputState - moveX: f32 - Horizontal axis (-1 left, 1 right) - moveY: f32 - Forward/backward (-1 back, 1 forward) - moveZ: f32 - Vertical axis (-1 down, 1 up) - lookX: f32 - Mouse delta X - lookY: f32 - Mouse delta Y - scrollDelta: f32 - Mouse wheel delta - jump: ui8 - Jump available (0/1) - primaryAction: ui8 - Primary action (0/1) - secondaryAction: ui8 - Secondary action (0/1) - leftMouse: ui8 - Left button (0/1) - rightMouse: ui8 - Right button (0/1) - middleMouse: ui8 - Middle button (0/1) - jumpBufferTime: f32 - primaryBufferTime: f32 - secondaryBufferTime: f32 ### Systems #### InputSystem - Group: simulation - Updates InputState components with current input data ### Functions #### setTargetCanvas(canvas: HTMLCanvasElement | null): void Registers canvas for focus-based keyboard input #### consumeJump(): boolean Consumes buffered jump input #### consumePrimary(): boolean Consumes buffered primary action #### consumeSecondary(): boolean Consumes buffered secondary action #### handleMouseMove(event: MouseEvent): void Processes mouse movement #### handleMouseDown(event: MouseEvent): void Processes mouse button press #### handleMouseUp(event: MouseEvent): void Processes mouse button release #### handleWheel(event: WheelEvent): void Processes mouse wheel ### Constants #### INPUT_CONFIG Default input mappings and sensitivity settings #### Examples ## Examples ### Basic Plugin Registration ```typescript import * as GAME from 'vibegame'; GAME .withPlugin(GAME.InputPlugin) .run(); ``` ### Reading Input in a Custom System ```typescript import * as GAME from 'vibegame'; const playerQuery = GAME.defineQuery([GAME.Player, GAME.InputState]); const PlayerControlSystem: GAME.System = { update: (state) => { const players = playerQuery(state.world); for (const player of players) { // Read movement axes const moveX = GAME.InputState.moveX[player]; const moveY = GAME.InputState.moveY[player]; // Check for jump if (GAME.InputState.jump[player]) { // Jump is available this frame } // Check mouse buttons if (GAME.InputState.leftMouse[player]) { // Left mouse is held } } } }; ``` ### Consuming Buffered Actions ```typescript import * as GAME from 'vibegame'; const CombatSystem: GAME.System = { update: (state) => { // Consume jump if available (prevents double consumption) if (GAME.consumeJump()) { // Perform jump velocity.y = JUMP_FORCE; } // Consume primary action if (GAME.consumePrimary()) { // Fire weapon spawnProjectile(); } } }; ``` ### Custom Input Mappings ```typescript import * as GAME from 'vibegame'; // Modify before starting the game GAME.INPUT_CONFIG.mappings.jump = ['Space', 'KeyX']; GAME.INPUT_CONFIG.mappings.moveForward = ['KeyW', 'KeyZ', 'ArrowUp']; GAME.INPUT_CONFIG.mouseSensitivity.look = 0.3; GAME.run(); ``` ### Manual Event Handling ```typescript import * as GAME from 'vibegame'; // Use the exported handlers directly if needed canvas.addEventListener('mousedown', GAME.handleMouseDown); canvas.addEventListener('mouseup', GAME.handleMouseUp); ``` ### Orbit Camera Orbital camera controller for third-person views and smooth target following. ### Components #### OrbitCamera - target: eid (0) - Target entity ID - current-yaw: f32 (Ο) - Current horizontal angle - current-pitch: f32 (Ο/6) - Current vertical angle - current-distance: f32 (4) - Current distance - target-yaw: f32 (Ο) - Target horizontal angle - target-pitch: f32 (Ο/6) - Target vertical angle - target-distance: f32 (4) - Target distance - min-distance: f32 (1) - max-distance: f32 (25) - min-pitch: f32 (0) - max-pitch: f32 (Ο/2) - smoothness: f32 (0.5) - Interpolation speed - offset-x: f32 (0) - offset-y: f32 (1.25) - offset-z: f32 (0) ### Systems #### OrbitCameraSystem - Group: draw - Updates camera position and rotation around target ### Recipes #### camera - Creates orbital camera with default settings - Components: orbit-camera, transform, world-transform, main-camera #### Examples ## Examples ### Basic Camera ```xml <!-- Create default orbital camera --> <camera /> ``` ### Camera Following Player ```xml <world> <!-- Player entity --> <player id="player" pos="0 0 0" /> <!-- Camera following player --> <camera target="#player" target-distance="10" min-distance="5" max-distance="20" offset-y="2" /> </world> ``` ### Custom Orbit Settings ```xml <entity orbit-camera=" target: #boss; target-distance: 15; target-yaw: 0; target-pitch: 0.5; smoothness: 0.2; offset-y: 3 " transform main-camera /> ``` ### Programmatic Usage ```typescript import * as GAME from 'vibegame'; const cameraQuery = GAME.defineQuery([GAME.OrbitCamera]); const CameraControlSystem = { update: (state) => { const cameras = cameraQuery(state.world); for (const camera of cameras) { // Rotate camera on input if (state.input.mouse.deltaX) { GAME.OrbitCamera.targetYaw[camera] += state.input.mouse.deltaX * 0.01; } // Zoom on scroll if (state.input.mouse.wheel) { GAME.OrbitCamera.targetDistance[camera] = Math.max( GAME.OrbitCamera.minDistance[camera], Math.min( GAME.OrbitCamera.maxDistance[camera], GAME.OrbitCamera.targetDistance[camera] - state.input.mouse.wheel * 0.5 ) ); } } } }; ``` ### Dynamic Target Switching ```typescript import * as GAME from 'vibegame'; // Switch camera target const switchTarget = (state, cameraEntity, newTargetEntity) => { GAME.OrbitCamera.target[cameraEntity] = newTargetEntity; }; ``` ### Physics 3D physics simulation with Rapier including rigid bodies, collisions, and character controllers. ### Constants - DEFAULT_GRAVITY: -60 ### Enums #### BodyType - Dynamic = 0 - Affected by forces - Fixed = 1 - Immovable static - KinematicPositionBased = 2 - Script position - KinematicVelocityBased = 3 - Script velocity #### ColliderShape - Box = 0 - Sphere = 1 - Capsule = 2 ### Components #### PhysicsWorld - gravityX: f32 (0) - gravityY: f32 (-60) - gravityZ: f32 (0) #### Body - type: ui8 - BodyType enum (Fixed) - mass: f32 (1) - linearDamping: f32 (0) - angularDamping: f32 (0) - gravityScale: f32 (1) - ccd: ui8 (0) - lockRotX: ui8 (0) - lockRotY: ui8 (0) - lockRotZ: ui8 (0) - posX, posY, posZ: f32 - rotX, rotY, rotZ, rotW: f32 (rotW=1) - eulerX, eulerY, eulerZ: f32 - velX, velY, velZ: f32 - rotVelX, rotVelY, rotVelZ: f32 - lastPosX, lastPosY, lastPosZ: f32 #### Collider - shape: ui8 - ColliderShape enum (Box) - sizeX, sizeY, sizeZ: f32 (1) - radius: f32 (0.5) - height: f32 (1) - friction: f32 (0.5) - restitution: f32 (0) - density: f32 (1) - isSensor: ui8 (0) - membershipGroups: ui16 (0xffff) - filterGroups: ui16 (0xffff) - posOffsetX, posOffsetY, posOffsetZ: f32 - rotOffsetX, rotOffsetY, rotOffsetZ, rotOffsetW: f32 (rotOffsetW=1) #### CharacterController - offset: f32 (0.08) - maxSlope: f32 (45Β°) - maxSlide: f32 (30Β°) - snapDist: f32 (0.5) - autoStep: ui8 (1) - maxStepHeight: f32 (0.3) - minStepWidth: f32 (0.05) - upX, upY, upZ: f32 (upY=1) - moveX, moveY, moveZ: f32 - grounded: ui8 - platform: eid - Entity the character is standing on - platformVelX, platformVelY, platformVelZ: f32 - platformDeltaX, platformDeltaY, platformDeltaZ: f32 #### CharacterMovement - desiredVelX, desiredVelY, desiredVelZ: f32 - velocityY: f32 - actualMoveX, actualMoveY, actualMoveZ: f32 #### InterpolatedTransform - prevPosX, prevPosY, prevPosZ: f32 - prevRotX, prevRotY, prevRotZ, prevRotW: f32 - posX, posY, posZ: f32 - rotX, rotY, rotZ, rotW: f32 #### Force/Impulse Components - ApplyForce: x, y, z (f32) - ApplyTorque: x, y, z (f32) - ApplyImpulse: x, y, z (f32) - ApplyAngularImpulse: x, y, z (f32) - SetLinearVelocity: x, y, z (f32) - SetAngularVelocity: x, y, z (f32) - KinematicMove: x, y, z (f32) - KinematicRotate: x, y, z, w (f32) #### Collision Events - CollisionEvents: activeEvents (ui8) - TouchedEvent: other, handle1, handle2 (ui32) - TouchEndedEvent: other, handle1, handle2 (ui32) ### Systems - PhysicsWorldSystem - Initializes physics world - PhysicsInitializationSystem - Creates bodies and colliders - PhysicsCleanupSystem - Removes physics on entity destroy - PlatformDeltaSystem - Tracks platform position changes - CharacterMovementSystem - Character controller movement with platform sticking - CollisionEventCleanupSystem - Clears collision events - ApplyForcesSystem - Applies forces - ApplyTorquesSystem - Applies torques - ApplyImpulsesSystem - Applies impulses - ApplyAngularImpulsesSystem - Applies angular impulses - SetVelocitySystem - Sets velocities - TeleportationSystem - Instant position changes - KinematicMovementSystem - Kinematic movement - PhysicsStepSystem - Steps simulation - PhysicsRapierSyncSystem - Syncs Rapier to ECS - PhysicsInterpolationSystem - Interpolates for rendering ### Functions #### initializePhysics(): Promise<void> Initializes Rapier WASM physics engine ### Recipes - static-part - Immovable physics objects - dynamic-part - Gravity-affected objects - kinematic-part - Script-controlled objects #### Examples ## Examples ### Basic Usage #### XML Recipes ##### Static Floor ```xml <static-part pos="0 -0.5 0" shape="box" size="20 1 20" color="#90ee90" /> ``` ##### Dynamic Ball ```xml <dynamic-part pos="0 5 0" shape="sphere" radius="0.5" color="#ff0000" mass="2" restitution="0.8" /> ``` ##### Moving Platform ```xml <kinematic-part pos="0 2 0" shape="box" size="3 0.2 3" color="#4169e1" > <!-- Add movement with tweening --> <tween target="body.pos-y" from="2" to="5" duration="3" ease="sine-in-out" loop="ping-pong" /> </kinematic-part> ``` ##### Character with Controller ```xml <entity pos="0 1 0" body="type: kinematic-position" collider="shape: capsule; height: 1.8; radius: 0.4" character-controller character-movement transform renderer /> ``` #### JavaScript API ##### Create Physics Entity ```typescript import * as GAME from 'vibegame'; // Create a dynamic physics box const entity = state.createEntity(); state.addComponent(entity, GAME.Body, { type: GAME.BodyType.Dynamic, mass: 5, posX: 0, posY: 10, posZ: 0 }); state.addComponent(entity, GAME.Collider, { shape: GAME.ColliderShape.Box, sizeX: 1, sizeY: 1, sizeZ: 1, friction: 0.7, restitution: 0.3 }); // Note: Physics body won't exist until next fixed update // Transform will be overwritten by Body position after initialization ``` ##### Moving Physics Bodies ```typescript import * as GAME from 'vibegame'; // Dynamic bodies - Use forces/impulses for movement if (GAME.Body.type[entity] === GAME.BodyType.Dynamic) { // Apply force for gradual acceleration state.addComponent(entity, GAME.ApplyForce, { x: 10, y: 0, z: 0 }); // Apply impulse for instant velocity change state.addComponent(entity, GAME.ApplyImpulse, { x: 0, y: 50, z: 0 }); // Direct position setting only for teleportation GAME.Body.posX[entity] = 10; // Teleport - use sparingly } // Kinematic bodies - Direct control via movement components if (GAME.Body.type[entity] === GAME.BodyType.KinematicPositionBased) { state.addComponent(entity, GAME.KinematicMove, { x: 5, y: 2, z: 0 }); } if (GAME.Body.type[entity] === GAME.BodyType.KinematicVelocityBased) { state.addComponent(entity, GAME.SetLinearVelocity, { x: 3, y: 0, z: 0 }); } // Never modify Transform directly for physics entities // GAME.Transform.posX[entity] = 10; // β Will be overwritten by Body ``` ##### Apply Forces ```typescript import * as GAME from 'vibegame'; // Apply upward impulse (jump) state.addComponent(entity, GAME.ApplyImpulse, { x: 0, y: 50, z: 0 }); // Apply continuous force state.addComponent(entity, GAME.ApplyForce, { x: 10, y: 0, z: 0 }); // Set velocity directly state.addComponent(entity, GAME.SetLinearVelocity, { x: 0, y: 5, z: 0 }); ``` ##### Handle Collisions ```typescript import * as GAME from 'vibegame'; const touchedQuery = GAME.defineQuery([GAME.TouchedEvent]); const CollisionSystem: GAME.System = { update: (state) => { // Query entities with collision events for (const entity of touchedQuery(state.world)) { const otherEntity = GAME.TouchedEvent.other[entity]; console.log(`Entity ${entity} collided with ${otherEntity}`); // React to collision state.addComponent(entity, GAME.ApplyImpulse, { x: 0, y: 10, z: 0 }); } } }; ``` ##### Character Movement ```typescript import * as GAME from 'vibegame'; const PlayerMovementSystem: GAME.System = { update: (state) => { const movementQuery = GAME.defineQuery([GAME.CharacterMovement, GAME.CharacterController]); for (const entity of movementQuery(state.world)) { // Set desired movement based on input GAME.CharacterMovement.desiredVelX[entity] = input.x * 5; GAME.CharacterMovement.desiredVelZ[entity] = input.z * 5; // Jump if grounded if (GAME.CharacterController.grounded[entity] && input.jump) { GAME.CharacterMovement.velocityY[entity] = 10; } } } }; ``` ##### Custom Plugin Integration ```typescript import * as GAME from 'vibegame'; // Initialize physics before running await GAME.initializePhysics(); // Use with builder GAME .withPlugin(GAME.PhysicsPlugin) .run(); ``` ### Player Complete player character controller with physics movement, jumping, and platform momentum preservation. ### Components #### Player - speed: f32 (5.3) - jumpHeight: f32 (2.3) - rotationSpeed: f32 (10) - canJump: ui8 (1) - isJumping: ui8 (0) - jumpCooldown: f32 (0) - lastGroundedTime: f32 (0) - jumpBufferTime: f32 (-10000) - cameraSensitivity: f32 (0.007) - cameraZoomSensitivity: f32 (1.5) - cameraEntity: eid (0) - inheritedVelX: f32 (0) - Horizontal momentum inherited from platform - inheritedVelZ: f32 (0) - Horizontal momentum inherited from platform ### Systems #### PlayerMovementSystem - Group: fixed - Handles movement, rotation, jumping with platform momentum preservation #### PlayerGroundedSystem - Group: fixed - Tracks grounded state, jump availability, and clears inherited momentum on landing #### PlayerCameraLinkingSystem - Group: simulation - Links player to orbit camera #### PlayerCameraControlSystem - Group: simulation - Camera control via mouse input ### Recipes #### player - Complete player setup with physics - Components: player, character-movement, transform, world-transform, body, collider, character-controller, input-state, respawn ### Functions #### processInput(moveForward, moveRight, cameraYaw): Vector3 Converts input to world-space movement #### handleJump(entity, jumpPressed, currentTime): number Processes jump with buffering #### updateRotation(entity, inputVector, deltaTime, rotationData): Quaternion Smooth rotation towards movement #### Examples ## Examples ### Basic Player Usage (XML) ```xml <world> <!-- Player auto-created if not specified --> <player pos="0 2 0" speed="6" jump-height="3" /> </world> ``` ### Custom Player Configuration (XML) ```xml <world> <player pos="5 1 -10" speed="8" jump-height="4" rotation-speed="15" camera-sensitivity="0.005" /> </world> ``` ### Accessing Player Component (JavaScript) ```typescript import * as GAME from 'vibegame'; const playerQuery = GAME.defineQuery([GAME.Player]); const MySystem: GAME.System = { update: (state) => { const players = playerQuery(state.world); for (const entity of players) { // Check if player is jumping if (GAME.Player.isJumping[entity]) { console.log('Player is airborne!'); } // Modify player speed GAME.Player.speed[entity] = 10; } } }; ``` ### Creating Player Programmatically ```typescript import * as GAME from 'vibegame'; const PlayerSpawnSystem: GAME.System = { setup: (state) => { // Create player entity const player = state.createEntity(); // Add player recipe components state.addComponent(player, GAME.Player, { speed: 7, jumpHeight: 3.5, cameraSensitivity: 0.01 }); // Add required components state.addComponent(player, GAME.Transform, { posY: 5 }); state.addComponent(player, GAME.Body, { type: GAME.BodyType.KinematicPositionBased }); state.addComponent(player, GAME.CharacterController); state.addComponent(player, GAME.InputState); } }; ``` ### Movement Controls **Keyboard:** - W/S or Arrow Up/Down - Move forward/backward - A/D or Arrow Left/Right - Move left/right - Space - Jump **Mouse:** - Right-click + drag - Rotate camera - Scroll wheel - Zoom in/out ### Plugin Registration ```typescript import * as GAME from 'vibegame'; GAME .withPlugin(GAME.PlayerPlugin) // Included in defaults .run(); ``` ### Rendering Three.js rendering pipeline with meshes, lights, cameras, and post-processing effects. ### Components #### Renderer - shape: ui8 - 0=box, 1=sphere, 2=cylinder, 3=plane - sizeX, sizeY, sizeZ: f32 (1) - color: ui32 (0xffffff) - visible: ui8 (1) #### RenderContext - clearColor: ui32 (0x000000) - hasCanvas: ui8 #### MainCamera Tag component (no properties) #### Ambient - skyColor: ui32 (0x87ceeb) - groundColor: ui32 (0x4a4a4a) - intensity: f32 (0.6) #### Directional - color: ui32 (0xffffff) - intensity: f32 (1) - castShadow: ui8 (1) - shadowMapSize: ui32 (4096) - directionX: f32 (-1) - directionY: f32 (2) - directionZ: f32 (-1) - distance: f32 (30) #### Bloom - intensity: f32 (1.0) - Bloom intensity - luminanceThreshold: f32 (1.0) - Luminance threshold for bloom - luminanceSmoothing: f32 (0.03) - Smoothness of luminance threshold - mipmapBlur: ui8 (1) - Enable mipmap blur - radius: f32 (0.85) - Blur radius for mipmap blur - levels: ui8 (8) - Number of MIP levels for mipmap blur #### Dithering - colorBits: ui8 (4) - Bits per color channel (1-8) - intensity: f32 (1.0) - Effect intensity (0-1) - grayscale: ui8 (0) - Enable grayscale mode (0/1) - scale: f32 (1.0) - Pattern scale (higher = coarser dithering) - noise: f32 (1.0) - Noise threshold intensity ### Systems #### MeshInstanceSystem - Group: draw - Synchronizes transforms with Three.js meshes #### LightSyncSystem - Group: draw - Updates Three.js lights #### CameraSyncSystem - Group: draw - Updates Three.js camera and manages post-processing effects #### WebGLRenderSystem - Group: draw (last) - Renders scene through EffectComposer ### Functions #### setCanvasElement(entity, canvas): void Associates canvas with RenderContext ### Recipes - ambient-light - Ambient hemisphere lighting - directional-light - Directional light with shadows - light - Both ambient and directional #### Examples ## Examples ### Basic Rendering Setup ```xml <!-- Declarative scene with lighting and rendered objects --> <world canvas="#game-canvas" sky="#87ceeb"> <!-- Default lighting --> <light></light> <!-- Rendered box --> <entity transform renderer="shape: box; color: 0xff0000; size-x: 2" pos="0 1 0" /> <!-- Rendered sphere --> <entity transform renderer="shape: sphere; color: 0x00ff00" pos="3 1 0" /> </world> ``` ### Custom Lighting ```xml <!-- Separate ambient and directional lights --> <ambient-light sky-color="#ffd4a3" ground-color="#808080" intensity="0.4" /> <directional-light color="#ffffff" intensity="1.5" direction-x="-1" direction-y="3" direction-z="-0.5" cast-shadow="1" shadow-map-size="2048" /> ``` ### Imperative Usage ```typescript import * as GAME from 'vibegame'; // Create rendered entity programmatically const entity = state.createEntity(); // Add transform for positioning state.addComponent(entity, GAME.Transform, { posX: 0, posY: 5, posZ: 0 }); // Add renderer component state.addComponent(entity, GAME.Renderer, { shape: 1, // sphere sizeX: 2, sizeY: 2, sizeZ: 2, color: 0xff00ff, visible: 1 }); // Set canvas for rendering context const contextQuery = GAME.defineQuery([GAME.RenderContext]); const contextEntity = contextQuery(state.world)[0]; const canvas = document.getElementById('game-canvas'); GAME.setCanvasElement(contextEntity, canvas); ``` ### Shape Types ```typescript import * as GAME from 'vibegame'; // Available shape enums const shapes = { box: 0, sphere: 1, cylinder: 2, plane: 3 }; // Use in XML <entity renderer="shape: sphere"></entity> // Or with enum names <entity renderer="shape: 1"></entity> ``` ### Visibility Control ```typescript import * as GAME from 'vibegame'; // Hide/show entities GAME.Renderer.visible[entity] = 0; // Hide GAME.Renderer.visible[entity] = 1; // Show // In XML <entity renderer="visible: 0"></entity> <!-- Initially hidden --> ``` ### Post-Processing Effects ```xml <!-- Camera with bloom effect (using defaults) --> <camera bloom></camera> <!-- Camera with custom bloom settings --> <camera bloom="intensity: 2; luminance-threshold: 0.8; luminance-smoothing: 0.05"></camera> <!-- Camera with mipmap blur settings --> <camera bloom="mipmap-blur: 1; radius: 0.9; levels: 10"></camera> <!-- Camera without effects (still uses composer internally) --> <camera></camera> <!-- Camera with retro dithering effect --> <camera dithering="color-bits: 3; intensity: 0.8; scale: 2"></camera> <!-- Combined bloom and dithering for retro aesthetic --> <camera bloom="intensity: 1.5" dithering="color-bits: 2; grayscale: 1; scale: 3"></camera> <!-- Subtle dithering for vintage look --> <camera dithering="color-bits: 5; intensity: 0.5; scale: 1"></camera> <!-- Coarse pixel-art style dithering --> <camera dithering="color-bits: 2; scale: 4; intensity: 1"></camera> ``` ### Respawn Automatic respawn system that resets entities when falling below Y=-100. ### Components #### Respawn - posX, posY, posZ: f32 - Spawn position - eulerX, eulerY, eulerZ: f32 - Spawn rotation (degrees) ### Systems #### RespawnSystem - Group: simulation - Resets entities when Y < -100 #### Examples ## Examples ### Player with Respawn (Automatic) The `<player>` recipe automatically includes respawn: ```xml <world> <!-- Player spawns at 0,5,0 and respawns there if falling --> <player pos="0 5 0"></player> </world> ``` ### Manual Respawn Component ```xml <entity transform body collider respawn="pos: 0 10 -5"> <!-- Entity respawns at 0,10,-5 when falling below Y=-100 --> </entity> ``` ### Imperative Usage ```typescript import * as GAME from 'vibegame'; // Add respawn to an entity const entity = state.createEntity(); // Set spawn point from current transform state.addComponent(entity, GAME.Transform, { posX: 0, posY: 10, posZ: 0, eulerX: 0, eulerY: 0, eulerZ: 0 }); state.addComponent(entity, GAME.Respawn, { posX: 0, posY: 10, posZ: 0, eulerX: 0, eulerY: 0, eulerZ: 0 }); // Entity will respawn at (0,10,0) when falling ``` ### Update Spawn Point ```typescript import * as GAME from 'vibegame'; // Change respawn position dynamically GAME.Respawn.posX[entity] = 20; GAME.Respawn.posY[entity] = 5; GAME.Respawn.posZ[entity] = -10; ``` ### XML with Transform Sync Position attributes automatically populate the respawn component: ```xml <!-- Position sets both transform and respawn --> <player pos="5 3 -2" euler="0 90 0"></player> ``` ### Startup Auto-creates player, camera, and lighting entities at startup if missing. ### Systems #### LightingStartupSystem - Group: setup - Creates default lighting if none exists #### CameraStartupSystem - Group: setup - Creates main camera if none exists #### PlayerStartupSystem - Group: setup - Creates player entity if none exists #### PlayerCharacterSystem - Group: setup - Adds animated character to players #### Examples ## Examples ### Basic Usage (Auto-Creation) ```typescript // The plugin automatically creates defaults when included import * as GAME from 'vibegame'; // This will create player, camera, and lighting automatically GAME.run(); // Uses DefaultPlugins which includes StartupPlugin ``` ### Preventing Auto-Creation with XML ```xml <world> <!-- Creating your own player prevents auto-creation --> <player pos="10 2 -5" speed="12" /> <!-- Creating custom lighting prevents default lights --> <entity ambient="sky-color: 0xff0000" directional /> </world> ``` ### Manual Plugin Registration ```typescript import * as GAME from 'vibegame'; // Use startup plugin without other defaults GAME.withoutDefaultPlugins() .withPlugin(GAME.TransformsPlugin) .withPlugin(GAME.RenderingPlugin) .withPlugin(GAME.StartupPlugin) .run(); ``` ### System Behavior The startup systems are idempotent - they check for existing entities before creating: ```typescript import * as GAME from 'vibegame'; // First run: Creates player, camera, lights const playerQuery = GAME.defineQuery([GAME.Player]); playerQuery(state.world).length // 0 -> creates player // Subsequent runs: Skips creation playerQuery(state.world).length // 1 -> skips creation ``` ### Transforms 3D transforms with position, rotation, scale, and parent-child hierarchies. ### Components #### Transform - posX, posY, posZ: f32 (0) - rotX, rotY, rotZ, rotW: f32 (rotW=1) - Quaternion - eulerX, eulerY, eulerZ: f32 (0) - Degrees - scaleX, scaleY, scaleZ: f32 (1) #### WorldTransform - Same properties as Transform - Auto-computed from hierarchy (read-only) ### Systems #### TransformHierarchySystem - Group: simulation (last) - Syncs euler/quaternion and computes world transforms #### Examples ## Examples ### Basic Usage #### XML Position and Rotation ```xml <!-- Position only --> <entity transform="pos: 0 5 -3"></entity> <!-- Euler rotation (degrees) --> <entity transform="euler: 0 45 0"></entity> <!-- Scale (single value applies to all axes) --> <entity transform="scale: 2"></entity> <!-- Combined transform --> <entity transform="pos: 0 5 0; euler: 0 45 0; scale: 1.5"></entity> ``` #### JavaScript API ```typescript import * as GAME from 'vibegame'; // In a system const MySystem = { update: (state) => { const entity = state.createEntity(); // Add transform component with initial values state.addComponent(entity, GAME.Transform, { posX: 10, posY: 5, posZ: -3, eulerX: 0, eulerY: 45, eulerZ: 0, scaleX: 2, scaleY: 2, scaleZ: 2 }); // Transform system automatically syncs euler to quaternion } }; ``` ### Transform Hierarchy #### Parent-Child Relationships ```xml <!-- Parent at origin --> <entity transform="pos: 0 0 0"> <!-- Children positioned relative to parent --> <entity transform="pos: 2 0 0"></entity> <entity transform="pos: -2 0 0"></entity> </entity> <!-- Rotating parent affects all children --> <entity transform="euler: 0 45 0"> <entity id="arm" transform="pos: 0 2 0"> <entity id="hand" transform="pos: 0 2 0"></entity> </entity> </entity> ``` #### Accessing World Transform ```typescript import * as GAME from 'vibegame'; const transformQuery = GAME.defineQuery([GAME.Transform, GAME.WorldTransform]); const WorldTransformSystem = { update: (state) => { // Query entities with both transforms const entities = transformQuery(state.world); for (const entity of entities) { // Local position const localX = GAME.Transform.posX[entity]; // World position (after parent transforms) const worldX = GAME.WorldTransform.posX[entity]; console.log(`Local: ${localX}, World: ${worldX}`); } } }; ``` ### Common Patterns #### Setting Transform Values ```typescript import * as GAME from 'vibegame'; // Direct property access (bitECS style) GAME.Transform.posX[entity] = 10; GAME.Transform.posY[entity] = 5; GAME.Transform.posZ[entity] = -3; // Using euler angles for rotation GAME.Transform.eulerX[entity] = 0; GAME.Transform.eulerY[entity] = 45; GAME.Transform.eulerZ[entity] = 0; // Quaternion will be auto-synced by TransformHierarchySystem // Uniform scale GAME.Transform.scaleX[entity] = 2; GAME.Transform.scaleY[entity] = 2; GAME.Transform.scaleZ[entity] = 2; ``` #### Transform Interpolation ```typescript import * as GAME from 'vibegame'; // Interpolate between two positions const t = 0.5; // 50% between start and end GAME.Transform.posX[entity] = startX + (endX - startX) * t; GAME.Transform.posY[entity] = startY + (endY - startY) * t; GAME.Transform.posZ[entity] = startZ + (endZ - startZ) * t; ``` ### Tweening Animates component properties with easing functions and loop modes. Kinematic velocity bodies use velocity-based tweening for smooth physics-correct movement. ### Components #### Tween - duration: f32 (1) - Seconds - elapsed: f32 - easingIndex: ui8 - loopMode: ui8 - 0=Once, 1=Loop, 2=PingPong #### TweenValue - source: ui32 - Tween entity - target: ui32 - Target entity - componentId: ui32 - fieldIndex: ui32 - from: f32 - to: f32 - value: f32 - Current value #### KinematicTween - tweenEntity: ui32 - Associated tween entity - targetEntity: ui32 - Kinematic body entity - axis: ui8 - 0=X, 1=Y, 2=Z - from: f32 - Start position - to: f32 - End position - lastPosition: f32 - targetPosition: f32 ### Systems #### KinematicTweenSystem - Group: fixed - Converts position tweens to velocity for kinematic bodies #### TweenSystem - Group: simulation - Interpolates values with easing and auto-cleanup ### Functions #### createTween(state, entity, target, options): number | null Animates component property ### Easing Functions - linear - sine-in, sine-out, sine-in-out - quad-in, quad-out, quad-in-out - cubic-in, cubic-out, cubic-in-out - quart-in, quart-out, quart-in-out - expo-in, expo-out, expo-in-out - circ-in, circ-out, circ-in-out - back-in, back-out, back-in-out - elastic-in, elastic-out, elastic-in-out - bounce-in, bounce-out, bounce-in-out ### Loop Modes - once - Play once and destroy - loop - Repeat indefinitely - ping-pong - Alternate directions ### Shorthand Targets - rotation - body.eulerX/Y/Z - at - body.posX/Y/Z - scale - transform.scaleX/Y/Z #### Examples ## Examples ### Basic XML Tween ```xml <!-- Animate Y position from 5 to 10 over 2 seconds --> <kinematic-part pos="0 5 -5"> <tween target="body.pos-y" from="5" to="10" duration="2" ease="sine-in-out" loop="ping-pong" /> </kinematic-part> ``` ### Multiple Properties ```xml <!-- Animate rotation on all axes --> <entity transform renderer> <tween target="rotation" to="0 360 0" duration="4" loop="loop" /> </entity> ``` ### Body Physics Properties ```xml <!-- Animate physics body velocity --> <dynamic-part pos="0 10 0"> <tween target="body.velocity-x" from="0" to="10" duration="1" ease="quad-out" /> </tween> ``` ### Programmatic Usage ```typescript import * as GAME from 'vibegame'; // In a system const MySystem = { setup: (state) => { const entity = state.createEntity(); state.addComponent(entity, GAME.Transform); // Create tween programmatically GAME.createTween(state, entity, 'body.pos-y', { from: 0, to: 10, duration: 2, easing: 'bounce-out', loop: 'once' }); } }; ``` ### Complex Animation Sequence ```xml <!-- Platform with multiple animated properties --> <kinematic-part pos="0 0 0" color="#ff0000"> <!-- Position animation --> <tween target="body.pos-x" from="-5" to="5" duration="3" loop="ping-pong"></tween> <!-- Rotation animation --> <tween target="body.euler-y" to="360" duration="10" loop="loop"></tween> <!-- Scale pulse --> <tween target="transform.scale-x" from="1" to="1.5" duration="1" ease="sine-in-out" loop="ping-pong"></tween> <tween target="transform.scale-z" from="1" to="1.5" duration="1" ease="sine-in-out" loop="ping-pong"></tween> </kinematic-part> ``` ### Ui Web-native UI system using HTML/CSS overlays positioned over the 3D canvas. Includes GSAP for animations, ECS state synchronization, and external library support. This provides capabilities superior to most game engines' built-in UI systems. ### Components #### UIManager - element: HTMLElement - Root UI container - state: State - ECS state reference for updates - visible: ui8 (1) - UI visibility toggle ### Systems #### UIUpdateSystem - Group: simulation - Updates UI elements from ECS component state #### UIEventSystem - Group: setup - Handles UI event binding and canvas focus management ### Functions #### createUIOverlay(canvas: HTMLCanvasElement): HTMLElement Creates positioned UI overlay container #### bindUIToState(uiManager: UIManager, state: State): void Connects UI updates to ECS state changes #### showFloatingText(x: number, y: number, text: string): void Creates animated floating text at screen coordinates ### Patterns #### Basic UI Setup ```html <div id="game-ui"> <div class="hud"> <span id="score">0</span> <span id="health">100</span> </div> </div> ``` #### ECS Integration ```typescript const UISystem = { update: (state) => { // Update UI from game state components const scoreEl = document.getElementById('score'); if (scoreEl) scoreEl.textContent = getScore(state); } }; ``` #### GSAP Animations ```typescript gsap.to("#currency", { scale: 1.2, duration: 0.2, yoyo: true, repeat: 1 }); ``` #### Examples ## Examples ### Basic Game HUD ```html <!doctype html> <html> <head> <style> body { margin: 0; font-family: Arial; } #game-ui { position: fixed; top: 0; left: 0; right: 0; bottom: 0; pointer-events: none; z-index: 1000; } .hud { position: absolute; top: 20px; left: 20px; background: rgba(0,0,0,0.7); padding: 15px; border-radius: 8px; color: white; pointer-events: auto; } </style> </head> <body> <world canvas="#game-canvas"> <static-part pos="0 -0.5 0" shape="box" size="20 1 20" color="#90ee90"></static-part> </world> <canvas id="game-canvas"></canvas> <div id="game-ui"> <div class="hud"> <div>Score: <span id="score">0</span></div> <div>Coins: <span id="coins">0</span></div> </div> </div> <script type="module"> import * as GAME from 'vibegame'; const GameState = GAME.defineComponent({ score: GAME.Types.ui32, coins: GAME.Types.ui32 }); const UISystem = { update: (state) => { const query = GAME.defineQuery([GameState]); const entities = query(state.world); if (entities.length > 0) { const entity = entities[0]; document.getElementById('score').textContent = GameState.score[entity]; document.getElementById('coins').textContent = GameState.coins[entity]; } } }; GAME.withPlugin({ components: { GameState }, systems: [UISystem] }).run(); </script> </body> </html> ``` ### Animated Currency with GSAP ```javascript import gsap from 'gsap'; class AnimatedCounter { constructor(elementId) { this.element = document.getElementById(elementId); this.currentValue = 0; this.displayValue = 0; } setValue(newValue) { this.currentValue = newValue; gsap.to(this, { displayValue: newValue, duration: 0.8, ease: "power2.out", onUpdate: () => { this.element.textContent = Math.floor(this.displayValue); } }); } } // Usage in ECS system const coinCounter = new AnimatedCounter('coins'); const UISystem = { update: (state) => { const coins = getCoinsFromState(state); coinCounter.setValue(coins); } }; ``` ### Floating Damage Text ```javascript function showDamageText(worldX, worldY, worldZ, damage) { // Convert 3D world position to screen coordinates const camera = getMainCamera(state); const screenPos = worldToScreen(worldX, worldY, worldZ, camera); const element = document.createElement('div'); element.textContent = `-${damage}`; element.style.cssText = ` position: fixed; left: ${screenPos.x}px; top: ${screenPos.y}px; color: #ff4444; font-weight: bold; font-size: 24px; pointer-events: none; z-index: 10000; `; document.body.appendChild(element); gsap.timeline() .to(element, { y: screenPos.y - 100, opacity: 0, duration: 1.5, ease: "power2.out" }) .call(() => element.remove()); } // Usage in collision system const DamageSystem = { update: (state) => { // When player takes damage const playerPos = getPlayerPosition(state); showDamageText(playerPos.x, playerPos.y + 2, playerPos.z, 25); } }; ``` ### Menu System with State ```javascript class GameMenu { constructor() { this.isOpen = false; this.element = document.getElementById('main-menu'); } toggle() { this.isOpen = !this.isOpen; if (this.isOpen) { this.show(); } else { this.hide(); } } show() { this.element.style.display = 'block'; gsap.fromTo(this.element, { opacity: 0, scale: 0.8 }, { opacity: 1, scale: 1, duration: 0.3, ease: "back.out(1.7)" } ); } hide() { gsap.to(this.element, { opacity: 0, scale: 0.8, duration: 0.2, onComplete: () => { this.element.style.display = 'none'; } }); } } // Integration with input system const menu = new GameMenu(); const MenuSystem = { update: (state) => { // Check for escape key press if (GAME.consumeInput(state, 'escape')) { menu.toggle(); } } }; ``` |