前言
接下來我們要來製作怪物的部分,目前史萊姆只有一隻,所以要讓他變多且自動移動。
史萊姆
1 2 3 4 5 6
| blob = gameSprite('blob.png', resource); blob.x = 350; blob.y = frames.meta.size.h / 2; blob.vx = 0; blob.vy = 0; gameStart.addChild(blob);
|
我們要改成用迴圈來大量生成史萊姆
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| const blobs = []; const blobOptions = { number: 8, speeds: 5, };
for(let i = 0; i < blobOptions.number; i += 1) { blob = gameSprite('blob.png', resource); blob.x = 120 + (blobOptions.number + 32) * i; blob.y = frames.meta.size.h / 2; blob.vx = 0; blob.vy = blobOptions.speeds; blobs.push(blob); gameStart.addChild(blob); }
|
但是這邊要注意一件事情,我們要將 blob 儲存在特定陣列中,到時候我們會需要使用
修改 Gameloop
接下來我們要修改原有的程式碼也就是 contain(blob, {x: 28, y: 10, width: 488, height: 480})
要改成使用迴圈的方式處理,並賦予速率,但是這邊要注意碰撞函數的部分也要丟入該迴圈中
1 2 3 4 5 6 7 8 9 10 11 12 13
| blobs.forEach((item) => { item.y += item.vy; const blobsHit = contain(item, {x: 28, y: 10, width: 488, height: 480}) if(blobsHit === 'top' || blobsHit === 'bottom') { item.vy *= -1; } if(boxesIntersect(explorer, item)) { gameHP -= 20; explorer.x -= 10; } })
|
接下來你應該會看到史萊姆同時移動,感覺超弱的,所以這邊要改一下速率將它變成隨機速率
1 2 3
| function randomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }
|
然後稍微調整一下初始化的史萊姆速率
1
| blob.vy = blobOptions.speeds + randomInt(0, 3);
|
最後基本上每一隻的速率就會不太一樣
![GIF 轉錄會比較 LAG]()
參考文獻