日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

cocos做飞机大战笔记【添加游戏音效】

發布時間:2023/12/29 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 cocos做飞机大战笔记【添加游戏音效】 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

  • 前言
  • 添加音頻腳本并綁定組件
    • 音頻腳本
  • 子彈發射播放音頻并將播放音頻方法在管理腳本中暴露
  • 點擊按鈕播放音頻
  • 敵機銷毀的時候播放音頻
  • 玩家飛機銷毀播放音頻
  • 完整代碼


前言

游戲音效會分為游戲開始音效,玩家飛機死亡音效,敵機死亡音效,以及子彈發射音效和按鈕點擊音效

添加音頻腳本并綁定組件

首先創建個空節點audio用于存放音頻,然后將背景音樂掛在其下

音頻腳本

創建腳本AudioManager.ts,將需要的音頻用一個數組接收,

將音頻腳本掛入引擎

子彈發射播放音頻并將播放音頻方法在管理腳本中暴露


將音頻節點掛入

點擊按鈕播放音頻

敵機銷毀的時候播放音頻

玩家飛機銷毀播放音頻


在引擎中添加音頻

完整代碼

  • AudioManager
import { _decorator, Component, Node, AudioClip, AudioSource } from 'cc'; const { ccclass, property } = _decorator;/*** Predefined variables* Name = AudioManager* DateTime = Fri Nov 26 2021 16:11:32 GMT+0800 (China Standard Time)* Author = mywayday* FileBasename = AudioManager.ts* FileBasenameNoExtension = AudioManager* URL = db://assets/script/framework/AudioManager.ts* ManualUrl = https://docs.cocos.com/creator/3.3/manual/en/**/interface IAudioMap {[name: string]: AudioClip; }@ccclass('AudioManager') export class AudioManager extends Component {//音頻列表@property([AudioClip])public audioList: AudioClip[] = [];private _dict: IAudioMap = {};//音頻集合private _audioSource: AudioSource = null;start() {//將音頻存入集合中for (let i = 0; i < this.audioList.length; i++) {const element = this.audioList[i];this._dict[element.name] = element;}this._audioSource = this.getComponent(AudioSource);//音頻組件初始化}//播放音頻public play(name: string) {const audioClip = this._dict[name];if (audioClip !== undefined) {this._audioSource.playOneShot(audioClip);}}// update (deltaTime: number) {// // [4]// } }/*** [1] Class member could be defined like this.* [2] Use `property` decorator if your want the member to be serializable.* [3] Your initialization goes here.* [4] Your update function goes here.** Learn more about scripting: https://docs.cocos.com/creator/3.3/manual/en/scripting/* Learn more about CCClass: https://docs.cocos.com/creator/3.3/manual/en/scripting/ccclass.html* Learn more about life-cycle callbacks: https://docs.cocos.com/creator/3.3/manual/en/scripting/life-cycle-callbacks.html*/
  • GameManager
import { _decorator, Component, Node, Prefab, instantiate, math, Vec3, BoxCollider, macro, Label } from 'cc'; import { Bullet } from '../bullet/Bullet'; import { BulletProp } from '../bullet/BulletProp'; import { EnemyPlane } from '../plane/EnemyPlane'; import { SelfPlane } from '../plane/SelfPlane'; import { AudioManager } from './AudioManager'; import { Constant } from './Constant'; const { ccclass, property } = _decorator;@ccclass('GameManager') export class GameManager extends Component {// 關聯玩家飛機@property(SelfPlane)public playerPlane: SelfPlane = null;// bullet 關聯所有子彈@property(Prefab)public bullet01: Prefab = null;@property(Prefab)public bullet02: Prefab = null;@property(Prefab)public bullet03: Prefab = null;@property(Prefab)public bullet04: Prefab = null;@property(Prefab)public bullet05: Prefab = null;// 射擊周期@propertypublic shootTime = 0.3;// 子彈移動速度@propertypublic bulletSpeed = 1;//子彈管理節點@property(Node)public bulletRoot: Node = null;// enemy/** 關聯敵機 */@property(Prefab)public enemy01: Prefab = null;@property(Prefab)public enemy02: Prefab = null;@propertypublic createEnemtTime = 1;//創建敵機時間@propertypublic enemy1Speed = 0.5;//敵機1速度@propertypublic enemy2Speed = 0.7;//敵機2速度// prop 定義道具屬性@property(Prefab)public bulletPropM: Prefab = null;@property(Prefab)public bulletPropH: Prefab = null;@property(Prefab)public bulletPropS: Prefab = null;@propertypublic bulletPropSpeed = 0.3;//道具速度// ui@property(Node)public gamePage: Node = null;//游戲界面@property(Node)public gameOverPage: Node = null;//游戲結束界面@property(Label)public gameOverScore: Label = null;//游戲結算分數@property(Label)public gameScore: Label = null;//游戲分數組件// audio@property(AudioManager)public audioEffect: AudioManager = null;//獲取音頻腳本public isGameStart = false;//游戲是否開始private _currShootTime = 0;// 是否觸摸屏幕private _isShooting = false;private _currCreateEnemyTime = 0//當前創建的敵機時間private _combinationInterval = Constant.Combination.PLAN1//組合間隔狀態private _bulletType = Constant.BulletPropType.BULLET_M;//子彈類型private _score = 0;//分數start() {this._init();}update(deltaTime: number) {//判斷游戲是否開始if (!this.isGameStart) {return;}//判斷玩家是否死亡if (this.playerPlane.isDie) {this.gameOver();return;}// 這步加時間是為了發射子彈this._currShootTime += deltaTime;// 判斷是觸摸狀態 并且射擊時間大于我們的周期 發射子彈if (this._isShooting && this._currShootTime > this.shootTime) {/*** 根據吃道具類型來產生子彈*/if (this._bulletType === Constant.BulletPropType.BULLET_H) {this.createPlayerBulletH();} else if (this._bulletType === Constant.BulletPropType.BULLET_S) {this.createPlayerBulletS();} else {this.createPlayerBulletM();}//發射子彈播放聲音由于音頻只有1,2子彈卻有3個,這里是處理邏輯const name = 'bullet' + (this._bulletType % 2 + 1);this.playAudioEffect(name);this._currShootTime = 0;}this._currCreateEnemyTime += deltaTime//判斷組合方式if (this._combinationInterval == Constant.Combination.PLAN1) {//只創建單一的飛機 0-10秒飛機創建if (this._currCreateEnemyTime > this.createEnemtTime) {//普通飛機創建this.createEnemyPlane()this._currCreateEnemyTime = 0}} else if (this._combinationInterval == Constant.Combination.PLAN2) {// 10-20秒飛機創建if (this._currCreateEnemyTime > this.createEnemtTime * 0.9) {//0.9飛機組合間隔const randomCombination = math.randomRangeInt(1, 3)//隨機1,2飛機if (randomCombination === Constant.Combination.PLAN2) {this.createCombination1()} else {this.createEnemyPlane()}this._currCreateEnemyTime = 0}} else {//20+ 飛機創建if (this._currCreateEnemyTime > this.createEnemtTime * 0.8) {//0.8飛機組合間隔const randomCombination = math.randomRangeInt(1, 4)//隨機1,2,3飛機if (randomCombination === Constant.Combination.PLAN2) {this.createCombination1()} else if (randomCombination === Constant.Combination.PLAN3) {this.createCombination2()} else {this.createEnemyPlane()}this._currCreateEnemyTime = 0}}}/*** 返回主界面邏輯,數據重置*/public returnMain() {this._currShootTime = 0;this._currCreateEnemyTime = 0;this._combinationInterval = Constant.Combination.PLAN1;this._bulletType = Constant.BulletPropType.BULLET_M;this.playerPlane.node.setPosition(0, 0, 15);this._score = 0;}/*** 游戲開始頁面數據重置*/public gameStart() {this.isGameStart = true;this._changePlanMode();//開啟定時器this._score = 0;this.gameScore.string = this._score.toString();}/*** 游戲再次開始*/public gameReStart() {this.isGameStart = true;this._currShootTime = 0;this._currCreateEnemyTime = 0;this._combinationInterval = Constant.Combination.PLAN1;this._bulletType = Constant.BulletPropType.BULLET_M;this.playerPlane.node.setPosition(0, 0, 15);this._score = 0;this._changePlanMode();//開啟定時器this.gameScore.string = this._score.toString();}/*** 游戲結束*/public gameOver() {this.isGameStart = false;this.gamePage.active = false;this.gameOverPage.active = true;this.gameOverScore.string = this._score.toString();this._isShooting = false;this.unschedule(this._modeChanged);//取消定時器this.playerPlane.init();//這里注意游戲結束要初始化this._destroyAll();}/*** 加分*/public addScore() {this._score++;this.gameScore.string = this._score.toString();}/*** 創建子彈*/public createPlayerBulletM() {// 子彈實例化const bullet = instantiate(this.bullet01);// 將子彈放在子彈管理節點下面bullet.setParent(this.bulletRoot);// 獲取飛機位置const pos = this.playerPlane.node.position;// 設置子彈位置bullet.setPosition(pos.x, pos.y, pos.z - 7);// 設置子彈速度const bulletComp = bullet.getComponent(Bullet);bulletComp.show(this.bulletSpeed, false)}/*** H形狀子彈創建*/public createPlayerBulletH() {const pos = this.playerPlane.node.position;// leftconst bullet1 = instantiate(this.bullet03);bullet1.setParent(this.bulletRoot);bullet1.setPosition(pos.x - 2.5, pos.y, pos.z - 7);const bulletComp1 = bullet1.getComponent(Bullet);bulletComp1.show(this.bulletSpeed, false);// rightconst bullet2 = instantiate(this.bullet03);bullet2.setParent(this.bulletRoot);bullet2.setPosition(pos.x + 2.5, pos.y, pos.z - 7);const bulletComp2 = bullet2.getComponent(Bullet);bulletComp2.show(this.bulletSpeed, false);}/*** S型子彈創建*/public createPlayerBulletS() {const pos = this.playerPlane.node.position;// middleconst bullet = instantiate(this.bullet05);bullet.setParent(this.bulletRoot);bullet.setPosition(pos.x, pos.y, pos.z - 7);const bulletComp = bullet.getComponent(Bullet);bulletComp.show(this.bulletSpeed, false);// leftconst bullet1 = instantiate(this.bullet05);bullet1.setParent(this.bulletRoot);bullet1.setPosition(pos.x - 4, pos.y, pos.z - 7);const bulletComp1 = bullet1.getComponent(Bullet);bulletComp1.show(this.bulletSpeed, false, Constant.Direction.LEFT);// rightconst bullet2 = instantiate(this.bullet05);bullet2.setParent(this.bulletRoot);bullet2.setPosition(pos.x + 4, pos.y, pos.z - 7);const bulletComp2 = bullet2.getComponent(Bullet);bulletComp2.show(this.bulletSpeed, false, Constant.Direction.RIGHT);}/*** 創建敵機子彈* @param targetPos 敵機子彈位置*/public createEnemyBullet(targetPos: Vec3) {// 子彈實例化const bullet = instantiate(this.bullet01);// 將子彈放在子彈管理節點下面bullet.setParent(this.bulletRoot);// 設置子彈位置bullet.setPosition(targetPos.x, targetPos.y, targetPos.z + 6);// 設置子彈速度const bulletComp = bullet.getComponent(Bullet);bulletComp.show(1, true)/*** 敵機子彈分組*/const colliderComp = bullet.getComponent(BoxCollider);colliderComp.setGroup(Constant.CollisionType.ENEMY_BULLET);colliderComp.setMask(Constant.CollisionType.SELF_PLANE);//設置掩碼}/*** 創建敵機**/public createEnemyPlane() {// 兩架飛機隨機選一(1,2)const whichEnemy = math.randomRangeInt(1, 3)let prefab: Prefab = nulllet speed = 0// 創建敵機1或2if (whichEnemy == Constant.EnemyType.TYPE1) {prefab = this.enemy01speed = this.enemy1Speed} else {prefab = this.enemy02speed = this.enemy2Speed}// 預制實例化const enemy = instantiate(prefab)console.log(enemy);enemy.setParent(this.node)const enemyComp = enemy.getComponent(EnemyPlane)enemyComp.show(this, speed, true)//單架敵機需要發射子彈// 設置飛機位置 const randomPos = math.randomRangeInt(-25, 26)enemy.setPosition(randomPos, 0, -50)}/*** 組合1創建 橫向排列 z軸50,x軸從-20開始**/public createCombination1() {const enemyArray = new Array<Node>(5)//飛機數組for (let i = 0; i < enemyArray.length; i++) {// 敵機資源實例化enemyArray[i] = instantiate(this.enemy01)const element = enemyArray[i]element.parent = this.nodeelement.setPosition(-20 + i * 10, 0, -50)//-20起始左位置,10飛機間隔,其實創建位置//設置飛機速度const enemyComp = element.getComponent(EnemyPlane)enemyComp.show(this, this.enemy1Speed, false)//組合飛機不需要發射子彈}}/*** 組合2創建 V字排列**/public createCombination2() {const enemyArray = new Array<Node>(7)//飛機數組// 位置數組const combinationPos = [-21, 0, -60,-14, 0, -55,-7, 0, -50,0, 0, -45,7, 0, -50,14, 0, -55,21, 0, -60]for (let i = 0; i < enemyArray.length; i++) {// 敵機資源實例化enemyArray[i] = instantiate(this.enemy02)const element = enemyArray[i]element.parent = this.nodeconst startIndex = i * 3//因為位置數組有7個 但是位置有3×7 21個 所以每架飛機位置偏移是3element.setPosition(combinationPos[startIndex], combinationPos[startIndex + 1], combinationPos[startIndex + 2])//設置飛機速度const enemyComp = element.getComponent(EnemyPlane)enemyComp.show(this, this.enemy2Speed, false)//組合飛機不需要發射子彈}}/*** 創建子彈道具* 隨機1~3是根據然后創建相對應的道具*/public createBulletProp() {const randomProp = math.randomRangeInt(1, 4);let prefab: Prefab = null;if (randomProp === Constant.BulletPropType.BULLET_H) {prefab = this.bulletPropH;} else if (randomProp === Constant.BulletPropType.BULLET_S) {prefab = this.bulletPropS;} else {prefab = this.bulletPropM;}//實例化道具const prop = instantiate(prefab);prop.setParent(this.node);prop.setPosition(15, 0, -50);const propComp = prop.getComponent(BulletProp);propComp.show(this, -this.bulletPropSpeed);}/*** 觸摸狀態設置* @param value true/false*/public isShooting(value: boolean) {this._isShooting = value;}/*** 改變子彈類型* @param type 類型*/public changeBulletType(type: number) {this._bulletType = type;}/*** 播放音頻* @param name 音頻名字*/public playAudioEffect(name: string) {this.audioEffect.play(name);}/*** 默認發射子彈*/private _init() {this._currShootTime = this.shootTime;this.playerPlane.init();// this._changePlanMode();}/*** 設計定時器 */private _changePlanMode() {/*** 每10秒改變一次狀態,,根據狀態就能決定采用什么組合*/this.schedule(this._modeChanged, 10, macro.REPEAT_FOREVER);//組件自帶定時器(回調函數,間隔時間,重復次數,延遲時間)}/*** 改變組合狀態*/private _modeChanged() {this._combinationInterval++this.createBulletProp();//創建子彈道具}/*** 銷毀所有的飛機與子彈*/private _destroyAll() {let children = this.node.children;let length = children.length;let i = 0;for (i = length - 1; i >= 0; i--) {const child = children[i];child.destroy();}children = this.bulletRoot.children;length = children.length;for (i = length - 1; i >= 0; i--) {const child = children[i];child.destroy();}} }
  • UIMain
import { _decorator, Component, Node, systemEvent, SystemEvent, Touch, EventTouch, Vec2 } from 'cc'; import { GameManager } from '../framework/GameManager'; const { ccclass, property } = _decorator;@ccclass('UIMain') export class UIMain extends Component {@propertypublic planeSpeed = 1;//飛機移動速度@property(Node)public playerPlane: Node = null;//gameManager的引用@property(GameManager)public gameManager: GameManager = null;@property(Node)public gameStart: Node = null;//游戲開始2D UI@property(Node)public game: Node = null;//游戲中2D UI@property(Node)public gameOver: Node = null;//游戲結束2D UIstart() {this.node.on(SystemEvent.EventType.TOUCH_START, this._touchStart, this);this.node.on(SystemEvent.EventType.TOUCH_MOVE, this._touchMove, this);this.node.on(SystemEvent.EventType.TOUCH_END, this._touchEnd, this);//初始化游戲開始頁面展示this.gameStart.active = true;}// update (deltaTime: number) {// // [4]// }/*** 再來一局的按鈕點擊事件*/public reStart() {this.gameOver.active = false;this.game.active = false;//點擊按鈕播放this.gameManager.playAudioEffect('button');this.gameManager.gameReStart();}/*** 回到主頁的按鈕點擊事件*/public returnMain() {this.gameOver.active = false;this.gameStart.active = true;//點擊按鈕播放this.gameManager.playAudioEffect('button');this.gameManager.returnMain();}/*** 觸摸開始 子彈發射* @param touch * @param event */_touchStart(touch: Touch, event: EventTouch) {//判斷第一次觸摸屏幕的時候游戲是否開始if (this.gameManager.isGameStart) {this.gameManager.isShooting(true);} else {//游戲開始切換游戲狀態this.gameStart.active = false;this.game.active = true;//點擊按鈕播放this.gameManager.playAudioEffect('button');this.gameManager.gameStart();}}/*** 觸摸中* @param touch * @param event */_touchMove(touch: Touch, event: EventTouch) {//判斷游戲狀態if (!this.gameManager.isGameStart) {return;}//獲取當前觸點值與上一次觸點值之間的差值 const delta = touch.getDelta();//獲取當前位置let pos = this.playerPlane.position;//移動位置z與x移動 y軸不變 /*** 乘0.01是因為每移動一段距離移動的都是單位,但是在操作屏幕觸點的時候操作的其實是像素,兩者之間不能轉換,所以只能預估一下大概的移動距離 */this.playerPlane.setPosition(pos.x + 0.01 * this.planeSpeed * delta.x, pos.y, pos.z - 0.01 * this.planeSpeed * delta.y);}/*** 觸摸結束 子彈取消發射* @param touch * @param event */_touchEnd(touch: Touch, event: EventTouch) {//判斷游戲狀態if (!this.gameManager.isGameStart) {return;}this.gameManager.isShooting(false);} }
  • EnemyPlane
import { _decorator, Component, Node, Collider, ITriggerEvent } from 'cc'; import { Constant } from '../framework/Constant'; import { GameManager } from '../framework/GameManager'; const { ccclass, property } = _decorator;// 敵機銷毀位置 const OUTOFBOUNCE = 50@ccclass('EnemyPlane') export class EnemyPlane extends Component {/** 子彈發射周期 */@propertypublic createBulletTime = 0.5// 敵機速度private _enemySpeed = 0;private _needBullet = false//當前是否發射子彈private _gameManager: GameManager = nullprivate _currCreateBulletTime = 0// // 敵機類型// public enemyType = Constant.EnemyType.TYPE1start() {// [3]}//監聽事件onEnable() {const collider = this.getComponent(Collider);//獲取碰撞組件collider.on('onTriggerEnter', this._onTriggerEnter, this);//碰撞到了立馬處理邏輯}//取消事件onDisable() {const collider = this.getComponent(Collider);//獲取碰撞組件collider.off('onTriggerEnter', this._onTriggerEnter, this);}update(deltaTime: number) {const pos = this.node.positionconst movePos = pos.z + this._enemySpeed// 因為敵機向西飛所以為正向this.node.setPosition(pos.x, pos.y, movePos)if (this._needBullet) {//發射子彈邏輯this._currCreateBulletTime += deltaTimeif (this._currCreateBulletTime > this.createBulletTime) {this._gameManager.createEnemyBullet(this.node.position)this._currCreateBulletTime = 0}}if (movePos > OUTOFBOUNCE) {//超出邊界銷毀this.node.destroy()}}/*** 設置飛機移動速度* @param speed 移動速度*/show(gameManager: GameManager, speed: number, needBullet: boolean) {this._gameManager = gameManagerthis._enemySpeed = speedthis._needBullet = needBullet}private _onTriggerEnter(event: ITriggerEvent) {const collisionGroup = event.otherCollider.getGroup();//獲取分組if (collisionGroup === Constant.CollisionType.SELF_PLANE || collisionGroup === Constant.CollisionType.SELF_BULLET) {//玩家飛機或者玩家子彈判斷掉血// console.log('trigger enemy destroy');//敵方飛機銷毀的時候播放音頻this._gameManager.playAudioEffect('enemy');this.node.destroy();this._gameManager.addScore();//獲得分數}} }
  • SelfPlane
import { _decorator, Component, Node, Collider, ITriggerEvent, AudioSource } from 'cc'; import { Constant } from '../framework/Constant'; const { ccclass, property } = _decorator;@ccclass('SelfPlane') export class SelfPlane extends Component {public lifeValue = 5;//玩家飛機血量上限public isDie = false;//是否死亡private _currLife = 0;//當前飛機血量private _audioEffect: AudioSource = null;start(){//獲取音頻組件this._audioEffect = this.getComponent(AudioSource);}//監聽事件onEnable() {const collider = this.getComponent(Collider);//獲取碰撞組件collider.on('onTriggerEnter', this._onTriggerEnter, this);//碰撞到了立馬處理邏輯}//取消事件onDisable() {const collider = this.getComponent(Collider);//獲取碰撞組件collider.off('onTriggerEnter', this._onTriggerEnter, this);}public init() {this._currLife = this.lifeValue;//重置飛機血量this.isDie = false;}// update (deltaTime: number) {// // [4]// }private _onTriggerEnter(event: ITriggerEvent) {const collisionGroup = event.otherCollider.getGroup();//獲取分組if (collisionGroup === Constant.CollisionType.ENEMY_PLANE || collisionGroup === Constant.CollisionType.ENEMY_BULLET) {//敵方飛機或者敵方子彈判斷掉血this._currLife--;//掉血if (this._currLife <= 0) {//判斷當前血量是不是小于0this.isDie = true;this._audioEffect.play();console.log('self plane is die');}}}}

總結

以上是生活随笔為你收集整理的cocos做飞机大战笔记【添加游戏音效】的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。