javascriptphaser-frameworkmatter.jsphaserjs

How to conditionally turn on/off collisions in Phaser 3?


I'm making a simple flick type basketball game. The game is 2D, but the ball scales smaller after you launch it to give the 3d effect.

Where the ball spawns, the rim of the hoop is directly above it on screen. However, I need to launch the ball above the rim without colliding with it, and then when the ball is on its way down, the rim becomes an object the ball can collide with. Otherwise, I am launching a ball and on its upwards trajectory, it's just hitting the rim from underneath it and bouncing down to the ground.

Here's the code I have:

export default class PlayScene extends Phaser.Scene {
    constructor({ sceneKey, nextSceneKey }) {
        super({ key: sceneKey, active: false });
        this.nextSceneKey = nextSceneKey;
        this.MIN_LAUNCH_VELOCITY = 10; // Minimum velocity required to count as a valid shot
        this.isBallFalling = false; // Track the ball's downward movement
        this.isGameRunning = true;
    }

    init({ score, sessionToken, config }) {
        this.config = config;
        this.sessionToken = sessionToken;
        this.score = score || 0;
        this.isDown = false;
    }

    preload() {}

    create() {
        const { height, width } = this.game.config;

        // Define collision categories
        const BALL_CATEGORY = 0x0001;
        const RIM_CATEGORY = 0x0002;

        this.matter.world.setBounds(
            0,
            0,
            width,
            height,
            32,
            true,
            true,
            false,
            true
        ); // Disabling the top boundary

        this.background = this.add
            .tileSprite(0, 0, width, height, 'global', 'background')
            .setOrigin(0, 0)
            .setAlpha(0.6);
        setHeightAndScale(this.background, height);

        this.hoop = this.add.sprite(width / 2, 400, 'global', 'hoop');
        setHeightAndScale(this.hoop, 250);

        // Create small circular collision bodies for the sides of the rim
        this.leftRim = this.matter.add.circle(width / 2 - 80, 485, 1, {
            isStatic: true,
            label: 'leftRim',
        });
        this.rightRim = this.matter.add.circle(width / 2 + 80, 485, 1, {
            isStatic: true,
            label: 'rightRim',
        });

        // Add debug graphics to see the collision bodies
        this.debugGraphics = this.add.graphics();
        this.debugGraphics.lineStyle(1, 0x00ff00);
        this.debugGraphics.fillStyle(0x00ff00, 0.5);

        this.drawDebug(this.leftRim);
        this.drawDebug(this.rightRim);

        this.ball = this.matter.add.image(
            width / 2,
            height - 50,
            'global',
            'basketball'
        );
        setHeightAndScale(this.ball, 150);
        this.ball.setCircle();
        this.ball.setBounce(0.5);
        this.ball.setInteractive({ useHandCursor: true });

        this.matter.add.mouseSpring({ length: 1, stiffness: 0.05 }); // Reduce stiffness for less sensitivity - experiment with

        this.matter.world.setGravity(0, 4);

        this.ball.on('pointerup', () => {
            const velocityX = this.ball.body.velocity.x * 0.5;
            const velocityY = this.ball.body.velocity.y * 0.5;

            // Check if the ball was actually launched
            if (
                Math.abs(velocityX) < this.MIN_LAUNCH_VELOCITY &&
                Math.abs(velocityY) < this.MIN_LAUNCH_VELOCITY
            ) {
                this.resetBall(this.ball);
                return;
            }

            this.ball.setVelocity(velocityX, velocityY);

            // Add scale tween to simulate "3D" effect
            this.tweens.add({
                targets: this.ball,
                scaleX: 0.5,
                scaleY: 0.5,
                duration: 150,
                ease: 'Power1',
                onComplete: () => {
                    if (
                        this.ball.body.velocity.x === 0 &&
                        this.ball.body.velocity.y === 0
                    ) {
                        this.ball.setScale(1, 1);
                    }
                },
            });

            // reset the ball if it goes out of bounds
            this.time.delayedCall(1000, () => {
                if (
                    this.ball.y > height ||
                    this.ball.y < 0 ||
                    this.ball.x > width ||
                    this.ball.x < 0
                ) {
                    this.resetBall(this.ball);
                }
            });
        });

        // Periodic check to reset the ball if it goes out of bounds
        this.time.addEvent({
            delay: 500,
            callback: () => {
                if (
                    this.ball.y > height ||
                    this.ball.y < 0 ||
                    this.ball.x > width ||
                    this.ball.x < 0
                ) {
                    this.resetBall(this.ball);
                }
            },
            loop: true,
        });

        // Pre-collision detection to manage ball and rim collision dynamically
        this.matter.world.on('collisionactive', (event) => {
            event.pairs.forEach((pair) => {
                const { bodyA, bodyB } = pair;

                // Handle rim collisions only when the ball is falling
                if (
                    (bodyA.label === 'basketball' &&
                        (bodyB.label === 'leftRim' ||
                            bodyB.label === 'rightRim')) ||
                    (bodyB.label === 'basketball' &&
                        (bodyA.label === 'leftRim' ||
                            bodyA.label === 'rightRim'))
                ) {
                    if (!this.isBallFalling) {
                        pair.isActive = false;
                    }
                }
            });
        });

        // Collision detection for scoring
        this.matter.world.on('collisionstart', (event) => {
            event.pairs.forEach((pair) => {
                const { bodyA, bodyB } = pair;

                // Handle rim collisions only when the ball is falling
                if (
                    (bodyA.label === 'basketball' &&
                        (bodyB.label === 'leftRim' ||
                            bodyB.label === 'rightRim')) ||
                    (bodyB.label === 'basketball' &&
                        (bodyA.label === 'leftRim' ||
                            bodyA.label === 'rightRim'))
                ) {
                    if (this.isBallFalling) {
                        this.handleRimCollision();
                    }
                }

                // Check if the ball hits the ground
                if (
                    (bodyA === this.ball.body && bodyB.label === 'ground') ||
                    (bodyB === this.ball.body && bodyA.label === 'ground')
                ) {
                    this.resetBall(this.ball);
                }
            });
        });

        // Create the ground as a static body
        this.ground = this.matter.add.rectangle(width / 2, height, width, 10, {
            isStatic: true,
            label: 'ground',
        });
    }

    drawDebug(body) {
        this.debugGraphics.fillCircle(body.position.x, body.position.y, 5);
        this.debugGraphics.strokeCircle(body.position.x, body.position.y, 5);
    }

    handleRimCollision() {
        this.score += 1;
        console.log('Score:', this.score);
    }

    resetBall(ball) {
        const { height, width } = this.game.config;

        ball.setPosition(width / 2, height - 50); // Reset to bottom center of the screen

        ball.setVelocity(0, 0);
        ball.setScale(1, 1);
        this.isBallFalling = false; // Reset the falling state
    }

    update() {
        if (!this.isGameRunning) {
            return;
        }

        // Check if the ball is falling
        this.isBallFalling = this.ball.body.velocity.y > 0;

        const { height, width } = this.game.config;
        if (
            this.ball.y > height ||
            this.ball.y < 0 ||
            this.ball.x > width ||
            this.ball.x < 0
        ) {
            this.resetBall(this.ball);
        }
    }
}

The main parts I thought were important are the pre collision check on collisionactive, and the actual collision logic on collisionstart. My thought was that I could only have the ball collide with the sides of the rim if it were on a downward trajectory (I.e. the y velocity is greater than 0). However, nothing I've done up to this point has gotten it to work.

Having a pre-collision check and a check in the collision start methods. Only handle the collision if the ball's trajectory is moving downwards.


Solution

  • A solution, could be to use / set the property isSensor, when the ball is falling.

    I created a short demo based on your code (I just keep, the relevant parts), if the velocity is greater than 0 (="falling"), the rim is only a sensor, the will be no collision. This might work for the most cases.

    Short Demo:
    to "throw" (drag & release) the "ball", but just small movements, if not you wont be able to see it.

    document.body.style = 'margin:0;';
    
    class PlayScene extends Phaser.Scene {
    
        create() {
            const { height, width } = this.game.config;
    
            this.add.text(15, 10, 'Demo for "isSensor"')
                .setColor('#ffffff');
    
            this.matter.world.setBounds(0, 0, width, height, 32, true, true, false, true);
            this.matter.add.mouseSpring({ length: 1, stiffness: 0.05 });
            this.matter.world.setGravity(0, 4);
    
            // Create small circular collision bodies for the sides of the rim
            this.leftRim = this.matter.add.circle(width / 2 - 80, 120, 8, { isStatic: true, label: 'leftRim', });
            this.rightRim = this.matter.add.circle(width / 2 + 80, 120, 8, { isStatic: true, label: 'rightRim', });
    
            this.ball = this.matter.add.image( width / 2 - 79, 30, 'global', 'basketball')
                .setCircle()
                .setInteractive({ useHandCursor: true });
    
            // Create the ground as a static body
            this.ground = this.matter.add.rectangle(width / 2, height, width, 10, {
                isStatic: true,
                label: 'ground',
            });
        }
    
        update() {
            // lower than zero, to prevent rounding errors
            this.rightRim.isSensor = this.leftRim.isSensor = (this.ball.body.velocity.y < -.05);
        }
    }
    
    var config = {
        width: 500,
        height: 180,
        physics: {
            default: 'matter',
            matter: {
                debug: {
                    staticFillColor: 0xff0000,
                    staticLineColor: 0xff0000,
                    renderFill: true,
                }
            }
        },
        scene: [PlayScene],
    };
    
    new Phaser.Game(config);
    console.clear();
    <script src="//cdn.jsdelivr.net/npm/phaser/dist/phaser.min.js"></script>

    Info: for testing it you can also simply drag the ball over the rim, and you will see how it changes to a sensor and back. (If "the rim" is blue it is a sensor, if it is red it is a collidable object).

    Tipp: You might also consider using the ball scale size to determine, if a collision should occur.