|
| 1 | + |
| 2 | +var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update }); |
| 3 | + |
| 4 | +function preload() { |
| 5 | + |
| 6 | + game.load.image('ball', 'assets/sprites/shinyball.png'); |
| 7 | + |
| 8 | +} |
| 9 | + |
| 10 | +var bmd; |
| 11 | + |
| 12 | +var waveSize = 8; |
| 13 | +var wavePixelChunk = 2; |
| 14 | +var waveData; |
| 15 | +var waveDataCounter; |
| 16 | + |
| 17 | +function create() { |
| 18 | + |
| 19 | + // Create our BitmapData object at a size of 32x64 |
| 20 | + bmd = game.add.bitmapData('ball', 32, 64); |
| 21 | + |
| 22 | + // And apply it to 100 randomly positioned sprites |
| 23 | + for (var i = 0; i < 100; i++) |
| 24 | + { |
| 25 | + game.add.sprite(game.world.randomX, game.world.randomY, bmd); |
| 26 | + } |
| 27 | + |
| 28 | + // Populate the wave with some data |
| 29 | + waveData = game.math.sinCosGenerator(32, 8, 8, 2); |
| 30 | + |
| 31 | +} |
| 32 | + |
| 33 | +function update() { |
| 34 | + |
| 35 | + // Clear the BitmapData |
| 36 | + bmd.clear(); |
| 37 | + |
| 38 | + updateWobblyBall(); |
| 39 | + |
| 40 | +} |
| 41 | + |
| 42 | +// This creates a simple sine-wave effect running through our BitmapData. |
| 43 | +// This is then duplicated across all 100 sprites using it, meaning we only have to calculate it and upload it to the GPU once. |
| 44 | + |
| 45 | +function updateWobblyBall() |
| 46 | +{ |
| 47 | + var s = 0; |
| 48 | + var copyRect = { x: 0, y: 0, w: wavePixelChunk, h: 32 }; |
| 49 | + var copyPoint = { x: 0, y: 0 }; |
| 50 | + |
| 51 | + for (var x = 0; x < 32; x += wavePixelChunk) |
| 52 | + { |
| 53 | + copyPoint.x = x; |
| 54 | + copyPoint.y = waveSize + (waveSize / 2) + waveData.sin[s]; |
| 55 | + |
| 56 | + bmd.context.drawImage(game.cache.getImage('ball'), copyRect.x, copyRect.y, copyRect.w, copyRect.h, copyPoint.x, copyPoint.y, copyRect.w, copyRect.h); |
| 57 | + |
| 58 | + copyRect.x += wavePixelChunk; |
| 59 | + |
| 60 | + s++; |
| 61 | + } |
| 62 | + |
| 63 | + // Now all the pixel data has been redrawn we render it to the BitmapData object. |
| 64 | + // In CANVAS mode this doesn't do anything, but on WebGL it pushes the new texture to the GPU. |
| 65 | + // If your game is exclusively running under Canvas you ca safely ignore this step. |
| 66 | + bmd.render(); |
| 67 | + |
| 68 | + // Cycle through the wave data - this is what causes the image to "undulate" |
| 69 | + game.math.shift(waveData.sin); |
| 70 | + |
| 71 | + waveDataCounter++; |
| 72 | + |
| 73 | + if (waveDataCounter == waveData.length) |
| 74 | + { |
| 75 | + waveDataCounter = 0; |
| 76 | + } |
| 77 | +} |
0 commit comments