Коллайдер в Phaser 3 случайно не работает

#javascript #game-development #collider #phaser

#javascript #разработка игры #phaser-framework #коллайдер

Вопрос:

Я только начал кодировать в Phaser 3 после разработки некоторых игр с p5.js и хотел сделать 2d бесконечный раннер. Итак, вот код для моей игры:

 var game;
var gameOptions = {
    monkeyGravity: 1200,
    monkeyPower: 1000
}

window.onload = function() {
    let gameConfig = {
        type: Phaser.AUTO,
        backgroundColor:0x87ceeb,
        scale: {
            mode: Phaser.Scale.FIT,
            autoCenter: Phaser.Scale.CENTER_BOTH,
            parent: 'thegame',
            width: 1920,
            height: 1080
        },
        physics: {
            default: 'arcade',
            arcade: {debug: true}
        },
        scene: [
            startGame,
            playGame
        ]
    }
    game = new Phaser.Game(gameConfig);
    window.focus();
}

class startGame extends Phaser.Scene{
    constructor(){
        super('StartGame');
    }
    preload(){
        this.load.image('menu-bg', '/jeffrey2nd/menu-bg.png');
        this.load.image('play-button', '/jeffrey2nd/play-button.png');
    }
    create() {
        this.menuBg = this.add.sprite(game.config.width / 2, 0, 'menu-bg').setScale(2);
        const screenCenterX = this.cameras.main.worldView.x   this.cameras.main.width / 2;
        const screenCenterY = this.cameras.main.worldView.y   this.cameras.main.height / 2;
        const startButton = this.add.sprite(screenCenterX, screenCenterY, 'play-button');
        startButton.setInteractive();
        startButton.on('pointerdown', () => this.scene.start('PlayGame'));
      }
}


class playGame extends Phaser.Scene{
    constructor(){
        super('PlayGame');
    }
    preload(){
        this.load.image('background', '/jeffrey2nd/background.png');
        this.load.image('backgroundL1', '/jeffrey2nd/backgroundL1.png');
        this.load.image('backgroundL2', '/jeffrey2nd/backgroundL2.png');
        this.load.image('backgroundL3', '/jeffrey2nd/backgroundL3.png');
        this.load.image('backgroundL4', '/jeffrey2nd/backgroundL4.png');
        this.load.image('ground', '/jeffrey2nd/ground.png');
        
        //ANIMATIONS
    
        this.load.image('run0',  '/jeffrey2nd/animations/monkey/Running_000.png');
        this.load.image('run1',  '/jeffrey2nd/animations/monkey/Running_001.png');
        this.load.image('run2',  '/jeffrey2nd/animations/monkey/Running_002.png');
        this.load.image('run3',  '/jeffrey2nd/animations/monkey/Running_003.png');
        this.load.image('run4',  '/jeffrey2nd/animations/monkey/Running_004.png');
        this.load.image('run5',  '/jeffrey2nd/animations/monkey/Running_005.png');
        this.load.image('run6',  '/jeffrey2nd/animations/monkey/Running_006.png');
        this.load.image('run7',  '/jeffrey2nd/animations/monkey/Running_007.png');
        this.load.image('run8',  '/jeffrey2nd/animations/monkey/Running_008.png');
        this.load.image('run9',  '/jeffrey2nd/animations/monkey/Running_009.png');
        this.load.image('run10', '/jeffrey2nd/animations/monkey/Running_010.png');
        this.load.image('run11', '/jeffrey2nd/animations/monkey/Running_011.png');
        this.load.image('run12', '/jeffrey2nd/animations/monkey/Running_012.png');
        this.load.image('run13', '/jeffrey2nd/animations/monkey/Running_013.png');

        this.load.image('jump0',  '/jeffrey2nd/animations/monkey/Jumping_000.png');
        this.load.image('jump1',  '/jeffrey2nd/animations/monkey/Jumping_001.png');
        this.load.image('jump2',  '/jeffrey2nd/animations/monkey/Jumping_002.png');
        this.load.image('jump3',  '/jeffrey2nd/animations/monkey/Jumping_003.png');
        this.load.image('jump4',  '/jeffrey2nd/animations/monkey/Jumping_004.png');

    }
    create(){
        
        //BACKGROUND AND LAYERS
        this.bgLs = this.add.group();
        this.background = this.bgLs.create(0, game.config.height / 2, 'background');
        this.backgroundL1 = this.bgLs.create(0, game.config.height / 2, 'backgroundL1');
        this.backgroundL12 = this.bgLs.create(game.config.width, game.config.height / 2, 'backgroundL1');
        this.backgroundL2 = this.bgLs.create(0, game.config.height / 2, 'backgroundL2');
        this.backgroundL22 = this.bgLs.create(game.config.width, game.config.height / 2, 'backgroundL2');
        this.backgroundL3 = this.bgLs.create(0, game.config.height / 2, 'backgroundL3');
        this.backgroundL32 = this.bgLs.create(game.config.width, game.config.height / 2, 'backgroundL3');
        this.backgroundL4 = this.bgLs.create(0, game.config.height / 2, 'backgroundL4');
        this.backgroundL42 = this.bgLs.create(game.config.width, game.config.height / 2, 'backgroundL4');
        
        for (let b of this.bgLs.children.entries) {
            b.setOrigin(0, 0.5);
        }
        
        //GROUND PLATFORMS      
        this.groundGroup = this.physics.add.group();
        this.ground1 = this.groundGroup.create(0, game.config.height - 50, 'ground');
        this.ground2 = this.groundGroup.create(game.config.width, game.config.height - 50, 'ground');
        this.ground3 = this.groundGroup.create(game.config.width   game.config.width / 2, game.config.height - 275, 'ground');
        this.ground4 = this.groundGroup.create(game.config.width   game.config.width / 1.5, game.config.height - 500, 'ground');
        this.ground4.setScale(0.5, 1);
        for (let g of this.groundGroup.children.entries) {
            g.setOrigin(0, 0.5);
            g.setImmovable(true);
            g.setScale(1,0.3);
            g.body.checkCollision.down = false;
        }
        
        //MONKEY
        this.monkey = this.physics.add.sprite(game.config.width / 10 * 2, 500, 'run0');
        this.monkey.setScale(0.3);
        this.anims.create({
            key: "player-run",
            frames: [
                { key: 'run0' },
                { key: 'run1' },
                { key: 'run2' },
                { key: 'run3' },
                { key: 'run4' },
                { key: 'run5' },
                { key: 'run6' },
                { key: 'run7' },
                { key: 'run8' },
                { key: 'run9' },
                { key: 'run10' },
                { key: 'run11' },
                { key: 'run12' },
                { key: 'run13' }
            ],
            frameRate: 20,
            repeat: -1
        })
        this.anims.create({
            key: "player-jump",
            frames: [
                { key: 'jump0' },
                { key: 'jump1' },
                { key: 'jump2' },
                { key: 'jump3' },
                { key: 'jump4' }
            ],
            frameRate: 20,
            repeat: -1
        })
        
        this.monkey.body.setSize(this.monkey.width/2, this.monkey.height/2);    
        this.input.on('pointerdown', this.jump, this);
        this.input.on('pointerup', this.fall, this);
    }
    update(){
        this.backgroundL1.x -= 0.2;
        this.backgroundL12.x -= 0.2;
        this.backgroundL2.x -= 0.4;
        this.backgroundL22.x -= 0.4;
        this.backgroundL3.x -= 0.6;
        this.backgroundL32.x -= 0.6;
        this.backgroundL4.x -= 0.8;
        this.backgroundL42.x -= 0.8;
        
        for (let b of this.bgLs.children.entries) {
            if (b.x <= -game.config.width) b.setX(game.config.width);
        }
        
        var speed = 5;
        
        for (let g of this.groundGroup.children.entries) {
            g.setX(g.x-speed);
            //if (g.x <= -game.config.width) g.setX(game.config.width);
        }
        
        if (this.ground1.x <= -game.config.width) this.ground1.setX(game.config.width);
        if (this.ground2.x <= -game.config.width) this.ground2.setX(game.config.width);

        
        if (this.ground3.x <= -game.config.width) {
            this.rnd1 = (Phaser.Math.Between(0, 500))/100;
            this.ground3.setX(game.config.width   game.config.width / this.rnd1);
        }
        if (this.ground4.x <= -game.config.width) {
            this.rnd2 = (Phaser.Math.Between(0, 500))/100;
            this.ground4.setX(game.config.width   game.config.width / this.rnd2);
        }
        
        this.physics.world.collide(this.groundGroup, this.monkey, ()=> {console.log('touche'   game.loop.time )}, null, this);
        
        this.monkey.body.gravity.y = gameOptions.monkeyGravity;

        if(this.monkey.body.touching.down) this.monkey.anims.play("player-run", true);
        else this.monkey.anims.play("player-jump", true);

    }
    jump(){
        if(this.monkey.body.touching.down) {
            this.monkey.body.setVelocity(0, -gameOptions.monkeyPower);
            this.monkey.anims.stop();
            this.monkey.anims.play("player-jump");
        }
    }
    fall(){
        if (this.monkey.body.velocity.y < 0) this.monkey.body.setVelocity(0, -100);
    }
}
 

В сцене запуска игры есть кнопка «Пуск», игра начинается, обезьяна бегает по платформам, и вы можете прыгать на верхние платформы.

Кажется, все работает нормально, но иногда случайно обезьяна падает с экрана. Вы можете увидеть воспроизводимую версию ошибки на https://420videogames.com/jeffrey2nd

Здесь я добавил консольный журнал в функцию обратного вызова ‘monkey vs ground goup collide’, регистрируя game.loop.time , чтобы попытаться понять. Моя идея заключалась в том, что, возможно, некоторые кадры были пропущены во время обновления, и объекты столкнулись не идеально, но когда обезьяна падает, функция обратного вызова выполняется 2 раза, а затем обезьяна продолжает падать, и игра прерывается.

Еще одна странная вещь в этой проблеме заключается в том, что на моем мобильном телефоне REDMI8 игра работает без проблем, как и на iPhone8 моего GF. На Firefox mobile другого друга, кстати, у игры такая же проблема с ПК.

Заранее благодарю вас за внимание, надеюсь, кто-нибудь поможет мне решить эту проблему, Ab

Комментарии:

1. Я добавил this.monkey.setCollideWorldBounds(true); , и обезьяна все еще падает с платформ, но не выходит с экрана дисплея. Может ли это быть реальной физической проблемой? Я имею в виду, если обезьяна была слишком тяжелой, и платформы не могли ее остановить?

Ответ №1:

Проблема была решена, переместив коллайдеры из функции обновления в функцию создания.