|
| 1 | +import { Application, Assets, Graphics, MeshRope, Point } from 'pixi.js'; |
| 2 | + |
| 3 | +(async () => { |
| 4 | + // Create a new application |
| 5 | + const app = new Application(); |
| 6 | + |
| 7 | + // Initialize the application |
| 8 | + await app.init({ resizeTo: window }); |
| 9 | + |
| 10 | + // Append the application canvas to the document body |
| 11 | + document.body.appendChild(app.canvas); |
| 12 | + |
| 13 | + // Load the snake texture |
| 14 | + const texture = await Assets.load('https://pixijs.com/assets/snake.png'); |
| 15 | + |
| 16 | + let count = 0; |
| 17 | + |
| 18 | + // Build a rope from points! |
| 19 | + const ropeLength = 45; |
| 20 | + |
| 21 | + const points = []; |
| 22 | + |
| 23 | + for (let i = 0; i < 25; i++) { |
| 24 | + points.push(new Point(i * ropeLength, 0)); |
| 25 | + } |
| 26 | + |
| 27 | + // Create the snake MeshRope |
| 28 | + const strip = new MeshRope({ texture, points }); |
| 29 | + |
| 30 | + strip.x = -40; |
| 31 | + strip.y = 300; |
| 32 | + |
| 33 | + app.stage.addChild(strip); |
| 34 | + |
| 35 | + const g = new Graphics(); |
| 36 | + |
| 37 | + g.x = strip.x; |
| 38 | + g.y = strip.y; |
| 39 | + app.stage.addChild(g); |
| 40 | + |
| 41 | + // Start animating |
| 42 | + app.ticker.add(() => { |
| 43 | + count += 0.1; |
| 44 | + |
| 45 | + // Make the snake |
| 46 | + for (let i = 0; i < points.length; i++) { |
| 47 | + points[i].y = Math.sin(i * 0.5 + count) * 30; |
| 48 | + points[i].x = i * ropeLength + Math.cos(i * 0.3 + count) * 20; |
| 49 | + } |
| 50 | + renderPoints(); |
| 51 | + }); |
| 52 | + |
| 53 | + function renderPoints() { |
| 54 | + g.clear(); |
| 55 | + g.moveTo(points[0].x, points[0].y); |
| 56 | + |
| 57 | + for (let i = 1; i < points.length; i++) { |
| 58 | + g.lineTo(points[i].x, points[i].y); |
| 59 | + g.stroke({ width: 2, color: 0xffc2c2 }); |
| 60 | + } |
| 61 | + |
| 62 | + for (let i = 1; i < points.length; i++) { |
| 63 | + g.drawCircle(points[i].x, points[i].y, 10); |
| 64 | + g.fill({ color: 0xff0022 }); |
| 65 | + g.stroke({ width: 2, color: 0xffc2c2 }); |
| 66 | + } |
| 67 | + } |
| 68 | +})(); |
0 commit comments