Jump to content

Bounce ,Collision and Destroy Object instance Based scene in Phaser3


Shivam Paliya
 Share

Recommended Posts

Hey community, this is my first post here, I am sharing my scene in which I have used bounce and collision effect of phaser 3 , I have marked comments in order for understanding and reference purposes. The code I have laid down is as follows:

window.onload = () => {//creating game window.
    class MainScene extends Phaser.Scene {
        preload() {// the following function preloads the image asset required in scene
            this.load.image("bird", "bird.png");
        }
        create() {
            this.player = this.add.group();//grouping the sprite in order to load them at different positions
            this.time.addEvent({ delay: 1000, loop: true, callback: () => this.addBall() })//calling back addBall function after
            this.physics.add.collider(this.player, this.player);//setting collider object between every object
        }

        update() {
            if (this.player.getChildren().length > 10) {// if qty of objects/player is >10
                const bird = this.player.getFirstAlive();//getting 1st instance of player
                this.tweens.add({targets: [bird], alpha: 0, duration: 500, onComplete: () => bird.destroy()});//deleting first instance of player
            }
            this.player.getChildren().forEach(bird => bird.setAngularVelocity(bird.body.velocity.x * 1));//to produce spiral motion
        }

        addBall() {
            const bird = this.physics.add.sprite(game.config.width / 3, 150, "bird");//assigning sprite to bird vairable
            this.player.add(bird);//assigning ball to
            bird.setBounce(0.7);//setting bounce value ,
            bird.setDrag(1);//setting drag value
            bird.setCollideWorldBounds(true);//to enable collision setting bounds
            bird.setVelocity(Phaser.Math.Between(-800, 800), 0);//setting velocity 
            bird.setScale(Math.random());//so that the objects are of random, not same size,
        }
    }

    const game = new Phaser.Game({
        type: Phaser.AUTO,
        width: 600,//frame width
        height: 600,//frame height 
        physics: {
            default: 'arcade',
            arcade: {
                gravity: {y: 1000},//setting up gravity value
            }
        },        
        scene: [MainScene]
    });
};

 

So thats how my scene looks and all the birds disappear after a certain time, as mentioned in the code, Feel free to suggest what more I shall improve upon in order to grow and develop, and how you feel of this scene.
Thank You :slight_smile:

 

Screenshot (198).png

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...