phaser.js,主要实现了移动底部篮子,接取下落物体

1.我将phaser分为3个文件,资源加载BootScene.js,逻辑处理PlayScene.js,整合game.js加粗样式

1.1资源加载BootScene.js

import { Scene } from 'phaser';

// 本地
import bgMusic from '@src/assets/music/bgMusic.mp3';
import bomb from "@src/assets/receiveEuropeanGas/bomb.png"
import european_gas from "@src/assets/receiveEuropeanGas/european_gas.png"
import purse from "@src/assets/receiveEuropeanGas/purse.png"
import blessing from "@src/assets/receiveEuropeanGas/blessing.png"
import gameBg from "@src/assets/receiveEuropeanGas/background.png"
import time01 from '@src/assets/receiveEuropeanGas/first.png';
import time02 from '@src/assets/receiveEuropeanGas/second.png';
import time03 from '@src/assets/receiveEuropeanGas/third.png';
import animation1 from '@src/assets/receiveEuropeanGas/award-animation.png';
import animation2 from '@src/assets/receiveEuropeanGas/bomb-animation.png';
import back from '@src/assets/receiveEuropeanGas/back.png';
import banner from '@src/assets/receiveEuropeanGas/banner.png';
import closeMusic from '@src/assets/receiveEuropeanGas/closeMusic.png';
import openMusic from '@src/assets/receiveEuropeanGas/openMusic.png';

export default class BootScene extends Scene {
    constructor() {
        super({
            key: 'BootScene'
        });
    }

    preload() {
        let wThat = window.$vueThat;
        this.load.on('progress', (value) => {
            wThat.progressNum = parseInt(value * 100);
            if (value >= 1) {
                wThat.progressNum = parseInt(value * 100);
            }
        });

         //本地
         this.load.audio('bgMusic', bgMusic);
         this.load.image('gameBg', gameBg);
         this.load.image('time01', time01);
         this.load.image('time02', time02);
         this.load.image('time03', time03);
         this.load.image('purse', purse);
         this.load.image('bomb', bomb);
         this.load.image('european_gas', european_gas);
         this.load.image('blessing', blessing);
         this.load.image('animation1', animation1);
         this.load.image('animation2', animation2);
         this.load.image('back', back);
         this.load.image('banner', banner);
         this.load.image('closeMusic', closeMusic);
         this.load.image('openMusic', openMusic);
    }

    create() {
        this.scene.start('PlayScene');
    }
}

1.2逻辑处理PlayScene.js

// import * as Types from '@src/store/types';
import {
    Scene
} from 'phaser';

const Store = window.$vueThat.$store;
const Router = window.$vueThat.$router;

const State = Store.state;
const Common = State.common;
const Commit = Store.commit;
const Fetch = Store.Fetch;

export default class PlayScene extends Scene {
    constructor() {
        super({
            key: 'PlayScene'
        });
        this.wWidth = window.innerWidth;
        this.wHeight = window.innerHeight;
        this.actualHeight = (this.wHeight * 1080) / this.wWidth;
        this.timedEvent = '';
        this.Store = window.$vueThat.$store;

        this.isCountDown = false; //倒计时动画开关
        this.isStartGame = false; //游戏开始开关
        this.isPause = false; //游戏暂停开关
        this.isGamePop = false; //游戏弹窗状态
        this.isDropGift = true; //掉礼包开关
        this.isClickBack = false; //返回开关
        this.isDisplayGift = false; //显示礼品
        this.isEnterGame = false;
        this.isMusic = false; //音乐开关
        this.count = 100000; //游戏时间,默认100000,一般无法超过
        this.bombs = null;
        this.silveGifts = null;
        this.generatorTimerLeft = null;
        this.generatorTimerMiddie = null
        this.generatorTimerRight = null;
        this.animation2 = null
        this.animation1 = null

        this.aniArr = [];
        this.mask = null
        this.isHaveAward = false
        this.closeMusic = null
        this.openMusic = null
        this.isClickMusic = false
        this.openMusicBag = null

    }

    between(min, max) {
        return Math.floor(Math.random() * (max + 1 - min) + min);
    }

    preload() {
    }

    create() {
        window.$phaserThis = this;
        console.log("重新开始游戏", )
        //图片层级按顺序变大
        this.gameBg = this.add
            .image(0, 0, 'gameBg')
            .setOrigin(0, 0)
            .setScale(1);
        this.back = this.physics.add.sprite(944, 580, 'back').setScale(1)//为了层级大于banner
        this.openMusicBag = this.add
            .image(63, 380, 'openMusic')
            .setOrigin(0, 0)
            .setScale(1);
        this.banner = this.add
            .image(95, 264, 'banner')
            .setOrigin(0, 0)
            .setScale(1);
        this.banner.setDepth(5)
        //顶部栏

        this.purse = this.physics.add.sprite(540, this.actualHeight - 401, 'purse').setScale(0.797)
        this.purse.setCollideWorldBounds(true);
        this.purse.setInteractive();
        this.input.setDraggable(this.purse);

        this.back.setCollideWorldBounds(true);
        this.back.setInteractive();
        this.input.setDraggable(this.back);


        //礼包
        this.bombs = this.physics.add.group({
            key: 'bomb',
        });
        this.silveGifts = this.physics.add.group({
            key: 'european_gas',
            key: 'blessing',
        });
        //将掉落礼包分为左中右三部分下落
        this.generatorTimerLeft = this.createCandies(100, 440)
        this.generatorTimerMiddie = this.createCandies(440, 640)
        this.generatorTimerRight = this.createCandies(640, 940)
    } // create

    update() {
        this.isClickBack = Common.isClickBack;
        this.isEnterGame = Common.isEnterGame
        //1. 触发了返回按钮, 暂停
        if (this.isClickBack && this.isEnterGame) {
            if (this.silveGifts) {
                this.silveGifts.children.entries.forEach((item) => {
                    item.destroy();
                });
            }
            if (this.bombs) {
                this.bombs.children.entries.forEach((item) => {
                    item.destroy();
                });
            }
            // console.log('1. 点击返回');
            this.aniArr = [];
            this.purse.removeListener('drag');
            this.isPause = true;
            this.sound.pauseAll()
            if (this.isClickMusic) {
                this.closeMusic.destroy()
            }

            this.isDropGift = false;
            this.isMusic = true
            this.isHaveAward = false
            this.physics.pause();
            this.generatorTimerLeft.paused = true;
            this.generatorTimerMiddie.paused = true;
            this.generatorTimerRight.paused = true;
            this.isGamePop = true;
            return;
        }
        //2. 弹窗关闭
        if (Common.gamePopType === 'close' && this.isGamePop) {
            console.log('2. 弹窗');
            this.isCountDown = false; //倒计时动画开关
            this.isStartGame = false; //游戏开始开关
            this.isPause = false; //游戏暂停开关
            this.isMusic = false //音乐开关
            this.isGamePop = false; //游戏弹窗状态
            //  this.isDropGift = true; //掉礼包开关打开
            this.physics.resume(); //游戏继续
            if (this.animation2) {
                this.animation2.destroy()
            }
            if (this.animation1) {
                this.animation1.destroy()
            }
            if (this.purse) {
                this.purse.destroy()
            }
            //重新使接去袋子居中
            this.purse = this.physics.add.sprite(540, this.actualHeight - 401, 'purse').setScale(0.797)
            this.purse.setCollideWorldBounds(true);
            this.purse.setInteractive();
            this.input.setDraggable(this.purse);
            this.generatorTimerLeft.paused = false;
            this.generatorTimerMiddie.paused = false;
            this.generatorTimerRight.paused = false;
            if (window.$phaserThis.count !== 100000) window.$phaserThis.count = 100000;
        }

        //3. 没有倒计时,开启倒计时
        if (!this.isCountDown && window.$vueThat.loaded) {
            console.log('3.倒计时');
            this.purse.removeListener('drag');
            this.aniArr = ['03', '02', '01'];
            this.isCountDown = true;
            this.countDown();
        }

        //4. 游戏为开始
        if (!this.isStartGame) {
            console.log('4游戏开始')
            return;
        }

        //5. 倒计时为0 且 未暂停
        if (+this.timedEvent.repeatCount === 0 && !this.isPause) {
            if (this.silveGifts) {
                this.silveGifts.children.entries.forEach((item) => {
                    item.destroy();
                });
            }
            if (this.bombs) {
                this.bombs.children.entries.forEach((item) => {
                    item.destroy();
                });
            }
            console.log('5. 暂停');
            //时间不足,游戏暂停
            this.isPause = true;
            this.physics.pause();
            //根据不同的状况不同的弹窗:
            this.isGamePop = true;
            this.generatorTimerLeft.paused = true;
            this.generatorTimerMiddie.paused = true;
            this.generatorTimerRight.paused = true;
            this.isStartGame = true;
            return;
        }

        //6.游戏开始
        if (this.isStartGame) {
            this.dropGift();
        }
    }
    checkOverlap(spriteA, spriteB) {
        var boundsA = spriteA.getBounds();
        var boundsB = spriteB.getBounds();
        return this.IsRectCross(boundsA, boundsB);
    }
    IsRectCross(rect1, rect2) {
        if (rect1.right - 45 <= rect2.left) return false;
        if (rect1.left + 45 >= rect2.right) return false;
        if (rect1.bottom - 196 <= rect2.top) return false;
        if (rect1.top >= rect2.bottom) return false;
        return true;
    }
    createCandies(left, right) {
        return this.time.addEvent({
            loop: true,
            delay: 1000,
            paused: true,
            callback: () => {
                if (!window.$phaserThis.isStartGame) {
                    return;
                }
                let i = Math.ceil(Math.random() * 12);
                let gift;
                if (i <= 4) {
                    gift = window.$phaserThis.bombs.create(0, 0, 'bomb').setScale(0.8);
                    gift.setTexture('bomb');
                    gift.setScale(0.8);
                    gift.setGravityY(500);
                } else if (i >= 5 && i <= 7) {
                    gift = window.$phaserThis.silveGifts.create(0, 0, 'bomb').setScale(0.8);
                    gift.setTexture('european_gas');
                    gift.setScale(0.8);
                    gift.setGravityY(500);
                } else {
                    gift = window.$phaserThis.silveGifts.create(0, 0, 'bomb').setScale(0.8);
                    gift.setTexture('blessing');
                    gift.setScale(0.8);
                    gift.setGravityY(500);
                }
                gift.setX(window.$phaserThis.between(left, right));
                gift.setY(window.$phaserThis.between(400, 580));
                gift.angle = window.$phaserThis.between(0, 0);
            }
        });
    }
    countDown() {
        //mask
        this.mask = this.add.renderTexture(0, 0, this.wWidth, this.actualHeight).setScale(4, 1);
        this.mask.fill('#b2463b', 0.5);
        this.mask.setDepth(6)

        console.log("重新开始游戏")
        //runing
        this.time.addEvent({
            repeat: 180,
            loop: false,
            delay: 10,
            callback: () => {
                if (this.silveGifts) {
                    this.silveGifts.children.entries.forEach((item) => {
                        item.destroy();
                    });
                }
                if (this.bombs) {
                    this.bombs.children.entries.forEach((item) => {
                        item.destroy();
                    });
                }
            }
        });
        //倒计时动效
        this.isDisplayGift = true;
        let indexIn = 0;
        let indexOut = 0;
        const scaleBigTime = 200; //放大时间
        const scaleSmallTime =200; //缩小时间
        const scaleBigDelay = 100; //停顿时间
        const intervalTime = (scaleBigTime + scaleSmallTime + scaleBigDelay) * 2; //倒计时动效定时时间
        let that = this;
        if (indexIn >= 2 || indexOut >= 2) {
            return;
        }

        this.time.addEvent({
            repeat: 2,
            loop: false,
            delay: intervalTime,
            callback: () => {
                let tweenObj = this.add.image(540, this.actualHeight - 1200, `time${this.aniArr[indexOut]}`);
                tweenObj.setDepth(7)

                this.add.tween({
                    targets: tweenObj.setScale(1),
                    scaleX: 0.9, // 恢复缩放原来的尺寸
                    scaleY: 0.9, // as the same
                    duration: scaleSmallTime, // 动画时间
                    // alpha: 0,                   // 透明度
                    ease: 'Power2',
                    repeat: 0,
                    completeDelay: scaleBigDelay, // 动画完成前的停顿时间
                    onComplete: function () {
                        // 动画完成后的回调
                        that.add.tween({
                            targets: tweenObj.setScale(1),
                            scaleX: 1.1,
                            scaleY: 1.1,
                            duration: scaleBigTime, // 动画时间
                            alpha: 0, // 透明度
                            ease: 'Power2',
                            repeat: 0
                        });
                        indexIn++;
                    }
                });
                indexOut++;
                if (indexIn > 2 || indexOut > 2) {
                    let that = this;
                    this.purse.on('drag', function (pointer, x, y) {
                        let minX = 150
                        let maxX = 930
                        if(x <= minX){
                            x = minX
                        }
                        if(x >= maxX) {
                            x = maxX
                        }
                        // console.log(x,'xxxxxxxxxxxx')
                        that.purse.x = x;
                    });
                    this.back.on('pointerdown', function (pointer, x, y) {
                        Router.back();
                    });

                    this.isDisplayGift = false;
                    this.isStartGame = true;
                    this.timedEvent = this.time.addEvent({
                        delay: 1000,
                        repeat: this.count
                    }); //开始倒计时动画结束,初始化游戏倒计时
                    try {
                        if (!this.isMusic) {
                            //防止网络慢的情况下加载失败
                            let that = this;
                            //初始化开启背景音乐
                            this.sound.play('bgMusic', {
                                valume: 0.75,
                            });
                            //背景音乐关闭打开
                            //生成打开音乐物理引擎
                            this.openMusic = this.physics.add.sprite(134, 575, 'openMusic').setScale(1)
                            this.openMusic.setCollideWorldBounds(true);
                            this.openMusic.setInteractive();
                            this.input.setDraggable(this.openMusic);
                            //对openMusic进行按下事件监听
                            this.openMusic.on('pointerdown', function (pointer, x, y) {
                                //生成关闭音乐物理引擎
                                that.closeMusic = that.physics.add.sprite(134, 575, 'closeMusic').setScale(1)
                                that.closeMusic.setCollideWorldBounds(true);
                                that.closeMusic.setInteractive();
                                that.input.setDraggable(that.closeMusic);
                                that.isClickMusic = true
                                that.closeMusic.setDepth(4)
                                that.sound.pauseAll()
                                let thats = that
                                //对closeMusic进行按下事件监听
                                that.closeMusic.on('pointerdown', function (pointer, x, y) {
                                    thats.closeMusic.destroy()
                                    thats.sound.play('bgMusic', {
                                        valume: 0.75,
                                    });
                                });
                            });

                        }
                        this.generatorTimerLeft.paused = false;
                        this.generatorTimerMiddie.paused = false;
                        this.generatorTimerRight.paused = false;
                    } catch (e) {}
                    this.mask.destroy();
                }
            }
        });
    }
    //掉礼包
    dropGift() {
        window.$phaserThis.bombs.children.entries.forEach((item) => {
            if (item.y * -1 > 3500 || item.y > 3500) {
                item.destroy();
            }
            if (window.$phaserThis.checkOverlap(window.$phaserThis.purse, item)) {
                if (this.animation1) {
                    this.animation1.destroy()
                }
                if (this.animation2) {
                    this.animation2.destroy()
                }
                this.animation2 = this.physics.add.sprite(window.$phaserThis.purse.x, this.actualHeight - 481, 'animation2').setScale(0.86);

                item.destroy();
                this.Store.commit('setCommonInfo', {
                    isClickBack: true,
                    isSignOut: false,
                    haveAward: this.isHaveAward ? true : false,
                    gamePopType: 'get-award'
                });
            }
        });
        window.$phaserThis.silveGifts.children.entries.forEach((item) => {
            if (item.y * -1 > 3500 || item.y > 3500) {
                item.destroy();
            }
            if (window.$phaserThis.checkOverlap(window.$phaserThis.purse, item)) {
                if (this.animation1) {
                    this.animation1.destroy()
                }
                if (this.animation2) {
                    this.animation2.destroy()
                }
                this.isHaveAward = true
                // console.log(window.$phaserThis.purse.x)
                this.animation1 = this.physics.add.sprite(window.$phaserThis.purse.x, this.actualHeight - 486, 'animation1').setScale(0.797);

                setTimeout(() => {
                    this.animation1.destroy()
                }, 50);
                item.destroy();
            }
        });
        window.$phaserThis.count = window.$phaserThis.timedEvent.repeatCount;
        if (window.$phaserThis.count === 0) window.$phaserThis.count = 100000;
    } // dropGift
}

countDown()实现了游戏3秒倒计时的功能
在这里插入图片描述

//生成底部袋子引擎
this.purse = this.physics.add.sprite(540, this.actualHeight - 401, 'purse').setScale(0.797)
//监听袋子的拖拽事件
this.purse.on('drag', function (pointer, x, y) {
                 let minX = 150
                 let maxX = 930
                 if(x <= minX){
                     x = minX
                 }
                 if(x >= maxX) {
                     x = maxX
                 }
                 that.purse.x = x;
  });

上面的代码实现了底部袋子的左右拖拽功能
在这里插入图片描述

//初始化开启背景音乐
this.sound.play('bgMusic', {
    valume: 0.75,
});
//背景音乐关闭打开
//生成打开音乐物理引擎
this.openMusic = this.physics.add.sprite(134, 575, 'openMusic').setScale(1)
this.openMusic.setCollideWorldBounds(true);
this.openMusic.setInteractive();
this.input.setDraggable(this.openMusic);
//对openMusic进行按下事件监听
this.openMusic.on('pointerdown', function (pointer, x, y) {
    //生成关闭音乐物理引擎
    that.closeMusic = that.physics.add.sprite(134, 575, 'closeMusic').setScale(1)
    that.closeMusic.setCollideWorldBounds(true);
    that.closeMusic.setInteractive();
    that.input.setDraggable(that.closeMusic);
    that.isClickMusic = true
    that.closeMusic.setDepth(4)
    that.sound.pauseAll()
    let thats = that
    //对closeMusic进行按下事件监听
    that.closeMusic.on('pointerdown', function (pointer, x, y) {
        thats.closeMusic.destroy()
        thats.sound.play('bgMusic', {
            valume: 0.75,
        });
    });

这段代码实现了点击音乐可以进行背景音乐的开启和关闭的切换功能
在这里插入图片描述

1.3整合game.js

import Phaser from 'phaser';
import BootScene from './BootScene';
import PlayScene from './PlayScene';

function launch(containerId, self) {
    return new Phaser.Game({
        parentPoint: self,
        type: Phaser.CANVAS,
        parent: containerId,
        scale: {
            mode: Phaser.Scale.WIDTH_CONTROLS_HEIGHT,
            width: 1080,
            height: window.innerHeight * 1080 / window.innerWidth
        },
        backgroundColor: '#b2463b',
        physics: {
            default: 'arcade',
            arcade: {
                gravity: { y: 0 },
                debug: false
            }

        },
        scene: [BootScene, PlayScene]
    });
}

export default launch
export { launch }

1.4js使用,在vue中的mounted生命周期中,引入game.js

    const game = await import('@src/game/game');
    this.$nextTick(() => {
        this.gameInstance = game.launch(this.containerId, this);
    });

1.5.主要实现截取下落物体的小游戏

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Phaser.js是一个用于创建HTML5游戏的开源框架,其中包含了许多功能强大的工具和库。要创建一个赛车游戏,你可以使用Phaser.js的物理引擎和精灵功能来实现。以下是一个简单的示例代码,展示了如何使用Phaser.js创建一个基本的赛车游戏: ```javascript // 创建一个Phaser游戏实例 var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update }); // 预加载资源 function preload() { game.load.image('car', 'assets/car.png'); } // 创建游戏场景 function create() { // 添加赛车精灵 var car = game.add.sprite(400, 300, 'car'); // 启用物理引擎 game.physics.startSystem(Phaser.Physics.ARCADE); game.physics.arcade.enable(car); // 设置赛车的重力和碰撞边界 car.body.collideWorldBounds = true; car.body.gravity.y = 0; // 设置赛车的控制 var cursors = game.input.keyboard.createCursorKeys(); cursors.up.onDown.add(function() { car.body.velocity.y = -200; }); cursors.down.onDown.add(function() { car.body.velocity.y = 200; }); cursors.left.onDown.add(function() { car.body.velocity.x = -200; }); cursors.right.onDown.add(function() { car.body.velocity.x = 200; }); } // 游戏更新 function update() { // 游戏逻辑更新 } ``` 请注意,这只是一个简单的示例,你可以根据自己的需求进行修改和扩展。你还可以通过添加更多的精灵、道具、关卡和游戏机制来进一步完善赛车游戏。希望对你有所帮助!
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值