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.

New contributor

Jimmy Blundell is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật