1. 程式人生 > >phaser3入門教程-從零開始開發一個打磚塊遊戲

phaser3入門教程-從零開始開發一個打磚塊遊戲

### 專案程式碼 [專案程式碼](https://gitee.com/kamiba/phaser3-brick-game) ### 體驗一下 空格開始,左右箭頭控制移動 [體驗一下](https://kamiba.gitee.io/phaser3-brick-game/) ### Phaser簡介 [Phaser](https://phaser.io/)是一個HTML5遊戲框架。它使用了許多HTML5 API,例如Canvas,WebGL,Audio,Gamepad等,並添加了一些有用的邏輯,例如管理遊戲迴圈併為我們提供了物理引擎。 使用Phaser,我們可以只用HTML,CSS和JavaScript來構建2D遊戲。 ### 專案需求 在使用Phaser構建Breakout克隆之前,讓我們首先定義遊戲的範圍: 這款單人遊戲具有30個積木,一個球拍和一個球的一個關卡 目標是讓球摧毀所有積木,同時確保其不離開遊戲畫面的底部。 玩家將控制一個可左右移動的槳 該遊戲是為桌面版網路使用者打造的,因此將使用鍵盤進行輸入 ### 設定Phaser Phaser是一個JavaScript庫,要開發和玩我們的遊戲,我們需要一些基本的HTML來載入JS。在一個工作區中建立一個名為breakout的目錄。 在目錄中建立以下檔案和資料夾: 一個index.html檔案 一個breakout.js檔案 名為的資料夾 assets 在您的assets資料夾中,建立一個images資料夾 遊戲資產是遊戲使用的藝術品,聲音,視訊和其他資料。對於這個簡單的Breakout克隆,沒有多少資產需要使用資料夾進行組織。但是,優良作法是將資產與程式碼分開,並按型別將資產分開。 將以下程式碼新增到您的index.html檔案中: ``` ``` 此基本HTML程式碼執行以下操作: * 刪除HTML和body標籤中的瀏覽器邊距和填充 * 新增一個`game`div元素,其中將包含我們的Breakout克隆 * 通過其CDN載入Phaser v3.17 * 載入`breakout.js`當前不執行任何操作但包含遊戲邏輯的檔案 為了使用Phaser有效開發遊戲,我們需要將這些檔案放到web伺服器中執行。如果web伺服器,出於安全原因,我們的瀏覽器將不允許我們的遊戲指令碼載入資產。 幸運的是,無需設定[Apache](https://www.apache.org/)或[Nginx](https://www.nginx.com/)即可獲得執行中的Web伺服器。如果使用[VisualStudio](https://visualstudio.microsoft.com/) Code,則可以安裝[Live Server](https://ritwickdey.github.io/vscode-live-server/)擴充套件。大多數IDE和文字編輯器都具有功能類似的外掛。 如果您安裝了Python版本3,則可以通過終端進入工作區並輸入`python3 -m http.server`。還有其他CLI工具可提供簡單的Web伺服器,請選擇一種可以為您提供最快時間開發遊戲的工具。 最後,下載我們為此遊戲建立的影象資產。將PNG檔案複製並貼上到images資料夾中。 ### 創造我們的遊戲世界 通過設定HTML和CSS,讓我們編輯`breakout.js`檔案以設定遊戲世界。 #### 開始Phaser 首先,我們需要配置Phaser並建立我們的`Game`例項。該[遊戲](https://photonstorm.github.io/phaser3-docs/Phaser.Game.html)的例項是Phaser遊戲的中央控制器,它進行所有的設定和開始遊戲迴圈。 讓我們配置和建立`Game`例項: ``` // This object contains all the Phaser configurations to load our game const config = { type: Phaser.AUTO, parent: 'game', width: 800, heigth: 640, scale: { mode: Phaser.Scale.RESIZE, autoCenter: Phaser.Scale.CENTER_BOTH }, scene: { preload, create, update, }, physics: { default: 'arcade', arcade: { gravity: false }, } }; // Create the game instance const game = new Phaser.Game(config); ``` 該`type`屬性告訴Phaser使用什麼渲染器。Phaser可以使用HTML5的[WebGL](https://get.webgl.org/)或[Canvas](https://www.w3schools.com/html/html5_canvas.asp)元素來渲染我們的遊戲。通過將型別設定為`Phaser.AUTO`,我們告訴Phaser首先嚐試使用WebGL進行渲染,如果失敗,則使用Canvas進行渲染。 該`parent`屬性表示將要玩我們的遊戲的HTML元素的ID。我們使用`width`和定義遊戲尺寸(以畫素為單位)`height`。該`scale`物件為我們做兩件事: * `mode` 告訴Phaser如何使用父元素的空間,在這種情況下,我們確保遊戲適合父元素的大小 `div` * `autoCenter`告訴Phaser`div`如果需要的話,如何在我們的父級中居中游戲。在這種情況下,我們將遊戲在父div內垂直和水平居中。當遊戲不佔據父物件的整個空間時,此屬性會更有用。 在Phaser中,我們的遊戲邏輯在中定義`Scenes`。將場景視為遊戲中的各種狀態:標題螢幕是一個場景,遊戲的每個級別將是它們自己的場景,剪下場景將是它自己的場景,等等。Phaser提供了[Scene](https://photonstorm.github.io/phaser3-docs/Phaser.Scene.html)物件,但它也可以與含有常規的JavaScript物件`preload()`,`create()`和`update()`定義的函式。 最後一個配置告訴Phaser要使用哪個物理引擎。Phaser可以使用3種不同的物理引擎:[Arcade](https://photonstorm.github.io/phaser3-docs/Phaser.Physics.Arcade.html),[Impact](https://photonstorm.github.io/phaser3-docs/Phaser.Physics.Impact.html)和[Matter](https://photonstorm.github.io/phaser3-docs/Phaser.Physics.Matter.html)。Arcade是最簡單的入門遊戲,足以滿足我們的遊戲需求。 Breakout 不需要重力即可工作,因此我們在物理引擎中禁用了該屬性。如果我們要構建Platform遊戲,則可能會啟用重力,這樣當我們的玩家跳躍時,他們會自然地掉回地面。 為了確保我們的遊戲設定工作,我們需要新增`preload()`,`create()`和`update()`功能。建立遊戲例項後,向其中新增以下空白函式: ``` function preload() { } function create() { } function update() { } ``` 在Web伺服器執行的情況下,導航到運行遊戲的頁面。您應該看到一個空白螢幕,如下所示: ![遊戲設定](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/7d23f6062e7e48e8a0eb24bf6c7dc2a9~tplv-k3u1fbpfcp-zoom-1.image) #### 載入資產 該遊戲中的資產包括5張圖片。在您可能建立的其他遊戲中,您的資產可能非常龐大。高清晰影象,音訊和視訊檔案可能會佔用兆位元組的空間。資產越大,負擔越長。因此,Phaser具有一項`preload()`功能,我們可以在開始運行遊戲之前載入所有資產。 將`preload()`函式更改為以下內容,以便我們可以在遊戲迴圈開始之前載入影象: ``` function preload() { this.load.image('ball', 'assets/images/ball_32_32.png'); this.load.image('paddle', 'assets/images/paddle_128_32.png'); this.load.image('brick1', 'assets/images/brick1_64_32.png'); this.load.image('brick2', 'assets/images/brick2_64_32.png'); this.load.image('brick3', 'assets/images/brick3_64_32.png'); } ``` 第一個引數是稍後將用來引用影象的鍵,第二個引數是影象的位置。 **注:** -當我們用`this`我們的`preload()`,`create()`和`update()`功能,我們指的是由之前建立的遊戲例項game。 載入影象後,我們想在螢幕上放置精靈。在的頂部`breakout.js`,新增以下將包含我們的精靈資料的變數: ``` let player, ball, violetBricks, yellowBricks, redBricks, cursors; ``` 一旦全域性定義它們,我們所有的函式都可以使用它們。 #### 新增精靈 sprite 是遊戲場景中任何2D影象。在Phaser中,sprite 會封裝影象以及其位置,速度,物理屬性和其他屬性。首先,通過`create()`函式建立player精靈: ``` player = this.physics.add.sprite( 400, // x position 600, // y position 'paddle', // key of image for the sprite ); ``` 您現在應該可以在螢幕上看到一個槳: ![螢幕播放器](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/ff48bc65675c485ca0227a176ca26dc3~tplv-k3u1fbpfcp-zoom-1.image) 該`sprite()`方法的第一個引數是`X`放置精靈的座標。第二個引數是`Y`座標,最後一個引數是`preload()`函式中新增的影象資產的鍵。 瞭解phaser和大多數2D遊戲框架如何使用座標很重要。我們在學校學到的圖形通常將原點即點(0,0)置於中心。在Phaser中,原點位於螢幕的左上方。隨著`x`增長,我們實際上正在向右移動。隨著`y`增加,我們正在向下移動。 我們的遊戲的寬度為800畫素,高度為640畫素,因此我們的遊戲座標如下所示: ![遊戲座標](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/98af739877dc476c85c2a9c2ec0aeeee~tplv-k3u1fbpfcp-zoom-1.image) 讓我們將球新增到Player上方。將以下程式碼新增到該`create()`函式: ``` ball = this.physics.add.sprite( 400, // x position 565, // y position 'ball' // key of image for the sprite ); ``` 由於球**上面**我們的Player,在座標y的值是**低**比玩家的Y座標。 #### 新增精靈組 雖然Phaser可以輕鬆新增sprite,但如果必須分別定義每個sprite,將很快變得乏味。Breakout中的磚塊幾乎相同。位置不同,但是它們的屬性(例如顏色以及它們與球的互動方式)是相同的。我們可以建立精靈組來更好地管理它們,而不是建立30個磚精靈物件。 讓我們通過`create()`函式新增第一排紫色磚: ``` // Add violet bricks violetBricks = this.physics.add.group({ key: 'brick1', repeat: 9, setXY: { x: 80, y: 140, stepX: 70 } }); ``` 代替`this.physics.add.sprite()`我們使用`this.physics.add.group()`並傳遞一個JavaScript物件。key屬性引用sprite組中所有sprite將使用的影象鍵。該`repeat`屬性告訴Phaser再建立多少個精靈。每個精靈組都建立一個精靈。隨著`repeat`設定為9,Phaser將建立一個精靈組10個精靈。該`setXY`物件具有三個有趣的屬性: * `x` 是第一個精靈的X座標 * `y` 是第二個精靈的Y座標 * `stepX` 是x軸上重複的精靈之間的畫素長度。 也有一個`stepY`屬性,但是我們不需要在遊戲中使用它。讓我們為磚新增另外兩個剩餘的精靈組: ``` // Add yellow bricks yellowBricks = this.physics.add.group({ key: 'brick2', repeat: 9, setXY: { x: 80, y: 90, stepX: 70 } }); // Add red bricks redBricks = this.physics.add.group({ key: 'brick3', repeat: 9, setXY: { x: 80, y: 40, stepX: 70 } }); ``` 我們的遊戲已經整合在一起,您的螢幕應如下所示: ![新增所有精靈](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/635aeb5953e94267a44c0a79f8839c89~tplv-k3u1fbpfcp-zoom-1.image) ### 遊戲勝利與結束 如果我們的球落到螢幕底部,我們可能會輸掉一場比賽。在“phaser”中,要使球位於螢幕下方,則球的Y座標大於遊戲世界的高度。讓我們建立一個檢查此功能的函式,在底部`breakout.js`新增以下內容: ``` function isGameOver(world) { return ball.body.y > world.bounds.height; } ``` 我們的功能從場景的物理屬性中獲取世界物件,該物件將在`update()`功能中可用。它檢查球精靈的Y座標是否大於遊戲世界邊界的高度。 為了贏得比賽,我們需要打掉所有磚塊。Phaser中的精靈都具有活動屬性。我們可以使用該屬性來確定我們是否獲勝。精靈組可以計算其中包含的活動精靈的數量。如果每個積木精靈組中都沒有活動的積木,即活動積木有0個,則玩家贏得了遊戲。 讓我們`breakout.js`通過在底部新增一個檢查來更新檔案: ``` function isWon() { return violetBricks.countActive() + yellowBricks.countActive() + redBricks.countActive() === 0; } ``` 我們接受每個精靈組作為引數,在其中新增活動精靈的數量,並檢查其是否等於0。 既然我們已經定義了輸贏條件,我們希望Phaser在遊戲迴圈開始時檢查它們。一旦玩家獲勝或失敗,遊戲便應停止。 讓我們更新`update()`函式: ``` function update() { // Check if the ball left the scene i.e. game over if (isGameOver(this.physics.world)) { // TODO: Show "Game over" message to the player } else if (isWon()) { // TODO: Show "You won!" message to the player } else { // TODO: Logic for regular game time } } ``` ### 使用鍵盤輸入移動播放器 演奏者的動作取決於鍵盤輸入。為了能夠跟蹤鍵盤輸入。現在該使用cursors變量了。 並且在我們create()功能的底部: cursors = this.input.keyboard.createCursorKeys(); Phaser中的游標鍵可跟蹤6個鍵盤鍵的用法:上,右,下,左,Shift和空格鍵。 現在我們需要對cursors物件的狀態做出反應以更新播放器的位置。在函式的else子句中update()新增以下內容: ``` // Put this in so that the player stays still if no key is being pressed player.body.setVelocityX(0); if (cursors.left.isDown) { player.body.setVelocityX(-350); } else if (cursors.right.isDown) { player.body.setVelocityX(350); } ``` 現在我們可以將播放器從左向右移動! ![](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/cd0efb12cb914f51af3562d7a859625f~tplv-k3u1fbpfcp-zoom-1.image) 您會注意到,玩家精靈可以離開遊戲螢幕,理想情況下,它不能離開遊戲螢幕。我們稍後將在處理衝突時解決該問題。 ### 等待開始 在我們新增邏輯來移動球之前,如果遊戲在移動之前等待使用者輸入,這將有所幫助。載入遊戲並立即被強制啟動並不是一種好的體驗。玩家沒有時間做出反應! 玩家按下空格鍵後,讓我們向上移動球。如果使用者向左或向右移動球拍,則球也將被移動,因此它始終位於球拍的中心。 首先,我們需要自己的變數來跟蹤遊戲是否啟動。在breakout.js宣告遊戲變數之後,在的頂部,新增: ``` let gameStarted = false; ``` 現在,在else我們的更新函式的子句中: ``` if (!gameStarted) { ball.setX(player.x); if (cursors.space.isDown) { gameStarted = true; ball.setVelocityY(-200); } } ``` 如果遊戲尚未開始,請將我們球的X座標設定為玩家的中心。遊戲物件的座標基於其中心,因此sprite的x和y屬性將點指向我們sprite的中心。 請注意,雖然可以x通過在設定屬性時直接引用屬性值來獲取屬性值,但我們總是嘗試使用適當的setter函式。設定器功能可以包括驗證我們的輸入,更新另一個屬性或觸發事件的邏輯。它使我們的程式碼更具可預測性。 就像之前移動player一樣,我們檢查是否按下了空格鍵。如果按下該按鈕,我們會將gameStarted標誌切換到,true以便球不再跟隨玩家的水平位置,並將球的Y速度設定為-200。負y速度將物體向上傳送。對於正速度,較大的值可以更快地向下移動物件。對於負速度,較小的值可以更快地向上移動物件。 現在,當我們移動玩家時,球跟隨著,如果我們按下空格鍵,球就會向上射擊: ![](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/b1a71a3dcdad48bcaa6d20f9539780eb~tplv-k3u1fbpfcp-zoom-1.image) 到目前為止,您將觀察到我們遊戲的一些行為: - 球在磚塊後面渲染 - 玩家可以離開螢幕的邊界 - 球可以離開螢幕的邊界 球是在積木後面渲染的,因為它是在積木精靈組之前的建立函式中新增到遊戲中的。在Phaser中,通常使用HTML5 canvas元素,最近新增的影象繪製在先前影象的頂部。 通過新增一些世界碰撞可以解決最後兩個問題。 ###處理碰撞 ####世界碰撞 我們所有的精靈互動都在create函式中定義。使用Phaser輕鬆與世界場景碰撞,在create函式末尾新增以下內容: ``` player.setCollideWorldBounds(true); ball.setCollideWorldBounds(true); ``` 它應該給我們這樣的輸出: ![](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/cbf99cb33af84cc5a5a485fdd71dd696~tplv-k3u1fbpfcp-zoom-1.image) 當球員運動正常時,球似乎卡在頂部。為了解決這個問題,我們需要設定bounce球形精靈的屬性。該bounce屬性將告訴Phaser與物件碰撞後要維持多少速度。 將此新增到create()函式的末尾: ``` ball.setBounce(1, 1); ``` 這告訴Phaser,球應保持其所有X和Y速度。如果我們用空格鍵釋放球,則球應該在遊戲世界中上下彈跳。我們需要從遊戲世界的底部禁用碰撞檢測。 如果我們不這樣做,我們將永遠不知道比賽何時結束。通過在create函式末尾新增以下行來禁用與遊戲世界底部的碰撞: ``` this.physics.world.checkCollision.down = false; ``` 我們現在應該有一個像這樣的遊戲: ![](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/6d643859e2af484dba01c63b03eb47ec~tplv-k3u1fbpfcp-zoom-1.image) ### 撞磚 現在我們的運動精靈已正確地與我們的遊戲世界碰撞,讓我們開始研究球與磚塊之間以及球與球員之間的碰撞。 在我們的create()函式中,將以下程式碼行新增到末尾: ``` this.physics.add.collider(ball, violetBricks, hitBrick, null, this); this.physics.add.collider(ball, yellowBricks, hitBrick, null, this); this.physics.add.collider(ball, redBricks, hitBrick, null, this); ``` hitBrick()當ball與各種磚精靈組發生碰撞時,碰撞器方法會告訴Phaser的物理系統執行該功能。 每次按下空格鍵,球就會向上射擊。沒有X速度,所以球會直接回到槳上。那將是一個無聊的遊戲。因此,當我們第一次碰到一塊磚時,我們將設定一個隨機的X速度。 在以下breakout.js定義的底部hitBrick: ``` function hitBrick(ball, brick) { brick.disableBody(true, true); if (ball.body.velocity.x === 0) { randNum = Math.random(); if (randNum >= 0.5) { ball.body.setVelocityX(150); } else { ball.body.setVelocityX(-150); } } } ``` 該hitBrick()函式接受collider()方法中使用的前兩個引數,例如ball和violetBricks。該disableBody(true, true)磚上呼叫告訴Phaser,以使之失去活性,並從螢幕隱藏它。如果球的X速度為0,則根據隨機數的值為球賦予速度。 如果一個小球以緩慢的速度向您的腳滾動,則在碰撞時它將停止。預設情況下,Arcade Physics引擎會模擬碰撞對速度的影響。對於我們的遊戲,我們不希望球撞到磚頭時失去速度。我們需要將immovable屬性設定為sprite組true。 更新的定義violetBricks,yellowBricks並redBricks於以下內容: ``` // Add violet bricks violetBricks = this.physics.add.group({ key: 'brick1', repeat: 9, immovable: true, setXY: { x: 80, y: 140, stepX: 70 } }); // Add yellow bricks yellowBricks = this.physics.add.group({ key: 'brick2', repeat: 9, immovable: true, setXY: { x: 80, y: 90, stepX: 70 } }); // Add red bricks redBricks = this.physics.add.group({ key: 'brick3', repeat: 9, immovable: true, setXY: { x: 80, y: 40, stepX: 70 } }); ``` 我們的磚塊碰撞現在已經完成,我們的遊戲應該像這樣工作: ![](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/292589e9276f4ab5bae22c426c1f0243~tplv-k3u1fbpfcp-zoom-1.image) 開發技巧-開發遊戲的物理原理時,您可能需要啟用除錯模式,以檢視精靈的邊界框以及它們如何相互碰撞。在您的遊戲config物件中,在arcade我們定義的屬性中gravity,您可以通過將其新增到物件中來啟用除錯功能: ``` debug: true ``` ### 玩家衝突 處理球與player之間的碰撞是類似的。首先,確保播放器為immovable。在create()函式的末尾新增以下內容: ``` player.setImmovable(true); ``` 然後我們在球和player之間新增一個對撞機: ``` this.physics.add.collider(ball, player, hitPlayer, null, this); ``` 當球擊中球員時,我們希望發生兩件事: - 球應該移動得更快一些,以逐漸增加比賽難度 - 球的水平方向取決於擊中球員的哪一側-如果球擊中球員的左側,那麼它應該向左走,如果球擊中球員的右側,那麼它應該向右走。 為了適應這些情況,讓我們更新breakout.js以下hitPlayer()功能: ``` function hitPlayer(ball, player) { // Increase the velocity of the ball after it bounces ball.setVelocityY(ball.body.velocity.y - 5); let newXVelocity = Math.abs(ball.body.velocity.x) + 5; // If the ball is to the left of the player, ensure the X-velocity is negative if (ball.x < player.x) { ball.setVelocityX(-newXVelocity); } else { ball.setVelocityX(newXVelocity); } } ``` 注意:一個精靈可以與另一個精靈碰撞,一個精靈可以與精靈組碰撞,並且精靈組可以相互碰撞。phaser足夠聰明,可以使用我們在上下文中定義的碰撞函式。 現在我們的遊戲既有玩家衝突又有磚塊衝突: ![](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/0b4abb5d700b489f8f6de14a2b687e4d~tplv-k3u1fbpfcp-zoom-1.image) ### 新增文字 儘管我們的遊​​戲可以完全正常執行,但是玩此遊戲的人卻不知道如何開始或不知道遊戲何時結束。 讓我們在gameStarted宣告的頂部新增三個新的全域性變數,這些變數將儲存我們的文字資料breakout.js: ``` let openingText, gameOverText, playerWonText; ``` ### 開始介面 讓我們在載入遊戲時新增一些文字,告訴玩家按下空格。在create()函式中新增以下程式碼: ``` openingText = this.add.text( this.physics.world.bounds.width / 2, this.physics.world.bounds.height / 2, 'Press SPACE to Start', { fontFamily: 'Monaco, Courier, monospace', fontSize: '50px', fill: '#fff' } ); openingText.setOrigin(0.5); ``` 該text方法的前兩個引數是文字框的X和Y座標。我們使用遊戲場景的寬度和高度來確定其放置位置-居中。第三個引數是要顯示的文字。第四個引數是包含字型相關資料的JS物件。 與精靈不同,文字物件的X和Y座標是指物件最左上角的點,而不是其中心。這就是為什麼我們使用該setOrigin()方法使座標系像sprites一樣工作,在這種情況下,它使定位在中心更加容易。 在玩遊戲時,我們不再希望看到開頭文字。在update()函式中,將if檢查是否按下空格鍵的語句更改為以下內容: ``` if (cursors.space.isDown) { gameStarted = true; ball.setVelocityY(-200); openingText.setVisible(false); } ``` 文字物件不是精靈,我們不能禁用它們的主體。當我們不需要看到它們時,可以使它們不可見。我們的遊戲現在開始如下: ![](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/b853e69a793749c287014daa57343016~tplv-k3u1fbpfcp-zoom-1.image) #### 遊戲結束和贏得比賽 像之前一樣,我們需要在`create()`函式中新增文字物件,並使它們不可見,以便在遊戲開始時不會看到它們: ``` // Create game over text gameOverText = this.add.text( this.physics.world.bounds.width / 2, this.physics.world.bounds.height / 2, 'Game Over', { fontFamily: 'Monaco, Courier, monospace', fontSize: '50px', fill: '#fff' } ); gameOverText.setOrigin(0.5); // Make it invisible until the player loses gameOverText.setVisible(false); // Create the game won text playerWonText = this.add.text( this.physics.world.bounds.width / 2, this.physics.world.bounds.height / 2, 'You won!', { fontFamily: 'Monaco, Courier, monospace', fontSize: '50px', fill: '#fff' } ); playerWonText.setOrigin(0.5); // Make it invisible until the player wins playerWonText.setVisible(false); ``` 現在已定義它們,我們必須在`update()`函式中更改其可見性: ``` // Check if the ball left the scene i.e. game over if (isGameOver(this.physics.world)) { gameOverText.setVisible(true); ball.disableBody(true, true); } else if (isWon()) { playerWonText.setVisible(true); ball.disableBody(true, true); } else { ... } ``` 我們禁用了球體,因此不再需要更新並顯示該球。 如果我們輸了比賽,我們將看到: ![遊戲結束](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/10f9be4342914276abd2abeedbfcfa88~tplv-k3u1fbpfcp-zoom-1.image) 如果我們贏了比賽,我們將看到以下內容: ![遊戲勝利](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/dcede42fc51e4e4cbb8a84fba9e7df5b~tplv-k3u1fbpfcp-zoom-1.image) 我們的打磚塊遊戲已完成! ### 結論 Phaser是一個HTML5遊戲開發框架,可讓我們在網路上快速構建視訊遊戲。除了通過HTML5 API進行抽象之外,它還為我們提供了有用的實用程式,例如物理引擎,並管理了遊戲迴圈-所有遊戲的執行生命週期。 ### 完整程式碼 ``` // Game objects are global variables so that many functions can access them let player, ball, violetBricks, yellowBricks, redBricks, cursors; // Variable to determine if we started playing let gameStarted = false; // Add global text objects let openingText, gameOverText, playerWonText; // This object contains all the Phaser configurations to load our game const config = { /** * The type can be Phaser.CANVAS, Phaser.WEBGL or Phaser.AUTO. AUTO means that * Phaser will try to render with WebGL, and fall back to Canvas if it fails */ type: Phaser.AUTO, // Parent element to inject the Canvas/WebGL element with the game parent: 'game', width: 800, heigth: 640, scale: { // Ensure the canvas is resized to fit the parent div's dimensions mode: Phaser.Scale.RESIZE, // Center the game canvas both horizontally and vertically within the parent autoCenter: Phaser.Scale.CENTER_BOTH }, /** * A scene is "self-contained" game world - all the logic and state of a game * component. For e.g. it's common to a game menu to be one scene, whereas the * first level is another scene. Phaser has a Scene object, but we can provide * a regular JS object with these function names: */ scene: { preload, create, update, }, /** * The physics engine determines how objects interact with the world. Phaser * supports three physics engines out of the box: arcade, impact and matter. * Arcade is understood to be the simplest one to implement */ physics: { default: 'arcade', arcade: { gravity: false }, } }; // Create the game instance const game = new Phaser.Game(config); /** * The function loads assets as Phaser begins to run the scene. The images are * loaded as key value pairs, we reference the assets by their keys of course */ function preload() { this.load.image('ball', 'assets/images/ball_32_32.png'); this.load.image('paddle', 'assets/images/paddle_128_32.png'); this.load.image('brick1', 'assets/images/brick1_64_32.png'); this.load.image('brick2', 'assets/images/brick2_64_32.png'); this.load.image('brick3', 'assets/images/brick3_64_32.png'); } /** * We create our game world in this function. The initial state of our game is * defined here. We also set up our physics rules here */ function create() { /** * Coordinates start at 0,0 from the top left * As we move rightward, the x value increases * As we move downward, the y value increases. */ player = this.physics.add.sprite( 400, // x position 600, // y position 'paddle', // key of image for the sprite ); // Let's add the ball ball = this.physics.add.sprite( 400, // x position 565, // y position 'ball' // key of image for the sprite ); // Add violet bricks violetBricks = this.physics.add.group({ key: 'brick1', repeat: 9, immovable: true, setXY: { x: 80, y: 140, stepX: 70 } }); // Add yellow bricks yellowBricks = this.physics.add.group({ key: 'brick2', repeat: 9, immovable: true, setXY: { x: 80, y: 90, stepX: 70 } }); // Add red bricks redBricks = this.physics.add.group({ key: 'brick3', repeat: 9, immovable: true, setXY: { x: 80, y: 40, stepX: 70 } }); // Manage key presses cursors = this.input.keyboard.createCursorKeys(); // Ensure that the player and ball can't leave the screen player.setCollideWorldBounds(true); ball.setCollideWorldBounds(true); /** * The bounce ensures that the ball retains its velocity after colliding with * an object. */ ball.setBounce(1, 1); /** * Disable collision with the bottom of the game world. This needs to be added * so the ball falls to the bottom, which means that the game is over */ this.physics.world.checkCollision.down = false; // Add collision for the bricks this.physics.add.collider(ball, violetBricks, hitBrick, null, this); this.physics.add.collider(ball, yellowBricks, hitBrick, null, this); this.physics.add.collider(ball, redBricks, hitBrick, null, this); // Make the player immovable player.setImmovable(true); // Add collision for the player this.physics.add.collider(ball, player, hitPlayer, null, this); // Create opening text openingText = this.add.text( this.physics.world.bounds.width / 2, this.physics.world.bounds.height / 2, 'Press SPACE to Start', { fontFamily: 'Monaco, Courier, monospace', fontSize: '50px', fill: '#fff' }, ); /** * The origin of the text object is at the top left, change the origin to the * center so it can be properly aligned */ openingText.setOrigin(0.5); // Create game over text gameOverText = this.add.text( this.physics.world.bounds.width / 2, this.physics.world.bounds.height / 2, 'Game Over', { fontFamily: 'Monaco, Courier, monospace', fontSize: '50px', fill: '#fff' }, ); gameOverText.setOrigin(0.5); // Make it invisible until the player loses gameOverText.setVisible(false); // Create the game won text playerWonText = this.add.text( this.physics.world.bounds.width / 2, this.physics.world.bounds.height / 2, 'You won!', { fontFamily: 'Monaco, Courier, monospace', fontSize: '50px', fill: '#fff' }, ); playerWonText.setOrigin(0.5); // Make it invisible until the player wins playerWonText.setVisible(false); } /** * Our game state is updated in this function. This corresponds exactly to the * update process of the game loop */ function update() { // Check if the ball left the scene i.e. game over if (isGameOver(this.physics.world)) { gameOverText.setVisible(true); ball.disableBody(true, true); } else if (isWon()) { playerWonText.setVisible(true); ball.disableBody(true, true); } else { // Put this in so that the player doesn't move if no key is being pressed player.body.setVelocityX(0); /** * Check the cursor and move the velocity accordingly. With Arcade Physics we * adjust velocity for movement as opposed to manipulating xy values directly */ if (cursors.left.isDown) { player.body.setVelocityX(-350); } else if (cursors.right.isDown) { player.body.setVelocityX(350); } // The game only begins when the user presses Spacebar to release the paddle if (!gameStarted) { // The ball should follow the paddle while the user selects where to start ball.setX(player.x); if (cursors.space.isDown) { gameStarted = true; ball.setVelocityY(-200); openingText.setVisible(false); } } } } /** * Checks if the user lost the game * @param world - the physics world * @return {boolean} */ function isGameOver(world) { return ball.body.y > world.bounds.height; } /** * Checks if the user won the game * @return {boolean} */ function isWon() { return violetBricks.countActive() + yellowBricks.countActive() + redBricks.countActive() == 0; } /** * This function handles the collision between a ball and a brick sprite * In the create function, ball is a sprite and violetBricks, yellowBricks and * redBricks are sprite groups. Phaser is smart enough to handle the collisions * for each individual sprite. * @param ball - the ball sprite * @param brick - the brick sprite */ function hitBrick(ball, brick) { brick.disableBody(true, true); if (ball.body.velocity.x == 0) { randNum = Math.random(); if (randNum >= 0.5) { ball.body.setVelocityX(150); } else { ball.body.setVelocityX(-150); } } } /** * The function handles the collision between the ball and the player. We want * to ensure that the ball's direction after bouncing off the player is based * on which side of the player was hit. Also, to make things more difficult, we * want to increase the ball's velocity when it's hit. * @param ball - the ball sprite * @param player - the player/paddle sprite */ function hitPlayer(ball, player) { // Increase the velocity of the ball after it bounces ball.setVelocityY(ball.body.velocity.y - 5); let newXVelocity = Math.abs(ball.body.velocity.x) + 5; // If the ball is to the left of the player, ensure the x velocity is negative if (ball.x < player.x) { ball.setVelocityX(-newXVelocity); } else { ball.setVelocityX(newXVelocity);