# 章節 18 - 物理模擬 - 讓物件自然的落下碰撞 (使用Matter.js) ## 第 1 單元 - 章節介紹與案例解析 物理模擬:落下碰撞 **matter.js** 憤怒鳥, 等現實世界物理法則 添加限制 偵測碰撞 案例 [波動弦](https://www.cuppetellimendoza.com/) 互動牆[google按鈕]( https://www.mentalfloss.com/article/81204/interactive-wall-google-made-thousands-arcade-buttons)[影片](https://www.youtube.com/watch?v=58pxJ8z1Vow) [黑色球球互動牆](https://www.youtube.com/watch?v=eazEgy_uA9E) IG[藝術家](https://www.instagram.com/jerson.latorre/) 吳哲宇[海膽作品](https://openprocessing.org/sketch/903498) ## 第 2 單元 - Matter.js 介紹與建立基礎物件 Matter.js is a JavaScript 2D rigid body physics engine for the web https://github.com/liabru/matter-js/ 引用 Matter.js 函式庫 ```javascript= var s = document.createElement("script"); s.type = "text/javascript"; s.src = "https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.14.2/matter.min.js" document.head.appendChild(s); ``` 建立 engine / bodies / world ```javascript= let Engine = Matter.Engine let Bodies = Matter.Bodies let World = Matter.World ``` 把物體畫出來後,需要加進 world 中 ![](https://i.imgur.com/PUCrA3O.png) 在下面畫一個地板阻擋其他物件超出範圍,並設定成靜態 (固定) ```javascript= isStatic: true ``` 為物件加上顏色 ```javascript= fill(box.color || 'white') ``` ## 單元 3 - 滑鼠與物件互動 可以跟建立地板一樣,建立左右的牆面來阻擋 ```javascript!= let wallLeft = Bodies.rectangle(0, height/2, 30, height, { isStatic = true }) ``` 設定字體粗度 `textStyle(BOLD)` ## 單元 4 - 自定義條件限制與事件偵測 matter.js 的 constraint 懸吊 ```javascript!= var constraint = Constraint.create({ pointA: { x: width/2, y:50}, bodyB: boxA, length: random(500) }) ``` 補充資料 [JavaScript Physics with Matter.js](https://codersblock.com/blog/javascript-physics-with-matter-js/) 設定位置、速度、靜態 setPosition() setVelocity() setStatic() ### Events ```javascript= Events.on(engine, 'collisionStart', function (event) { for(let pair of event.pairs){ console.log(pair) clickSound.play() // 加入音效,撞擊時觸發 } }) ```