jorbascrumps / phaser-plugin-water-body

A water body physics simulation plugin for Phaser v3
20 stars 2 forks source link

Phaser Water Body Plugin

View demo

Installation

npm i phaser-plugin-water-body -S

Then add to your game config:

import WaterBodyPlugin from 'phaser-plugin-water-body';

new Phaser.Game({
    plugins: [
        global: [
            {
                key: 'WaterBodyPlugin',
                plugin: WaterBodyPlugin,
                start: true,
            }
        ]
    ]
});

Basic Usage

The plugin registers a new custom Game Object that is available from within your scenes:

const waterBody = this.add.water(0, 0, 600, 600, 350, {
    texture: 'water', // Currently required..
});

This will render a body of water, but it will not allow it to interact with your world. There is no feasible way to create an out of the box solution for all games so it is up to you to configure this to your needs.

You will need to setup collisions for any possible object you'd like to interact with. You are also responsible for determining where an impact has occurred as well as how large of an impact it was. I recommend using the excellent phaser-matter-collision-plugin but ultimately it is up to you.

this.collision.addOnCollideStart({
    objectA: waterBody.sensor,
    callback: ({ gameObjectA: waterBody, gameObjectB, }) => {

        // Find the surface position directly under the colliding game object
        const impactPosition = waterBody.columns.findIndex((col, i) => col.x >= gameObjectB.x && i);

        // Calculate speed of game object on impact
        const speed = gameObjectB.body.speed * 3;

        // More speed means more droplets
        const numDroplets = Math.ceil(gameObjectB.body.speed) * 5;

        // Slow the colliding game object down
        gameObjectB.setFrictionAir(0.25);

        // Splash!
        waterBody.splash(impactPosition, speed, numDroplets);
    },
});

Check out the demo for a full example.

API

WaterBody(x, y, width, height, depth, options)

Create a new WaterBody object in the Scene.

Arguments

Returns a WaterBody object.

TODO