Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                
              
            
!

CSS

              
                
              
            
!

JS

              
                
class Ball extends Phaser.GameObjects.Sprite {
  constructor(scene, x, y, texture, options) {
    super(scene, x, y, texture);  
    this.scene = scene;
    this.scene.add.existing(this);
    this.canvas = scene.canvas;
    this.radius = this.displayHeight / 2;
    
    this.velocity = new Phaser.Math.Vector2();
    this.acceleration = new Phaser.Math.Vector2();
    this.newPos = new Phaser.Math.Vector2(x,y);
    this.friction = 0.9; // arbitrary factor to dampen the post-collision velocity
    this.angle = 0;

    this.response = new Phaser.Math.Vector2();
    this.collision = false;
    // set various options that determine object's behaviour
    if (options.bounceBeforeDeath == undefined) {
      // How many time object can bounce before death
      // -1 = infinite
      this.bounceBeforeDeath = -1
    } else {
      this.bounceBeforeDeath = options.bounceBeforeDeath
    };
    if (options.explode == undefined) {
      this.explode = false;
    } else {
      this.explode = options.explode
    };
    if (options.explosionSize == undefined) {
      this.explosionSize = 20;
    }
    else {
      this.explosionSize = option.explosionSize;
    }
    if (options.explosionDebris == undefined) {
      this.explosionDebris = 20;
    }
    else {
      this.explosionDebris = options.explosionDebris;
    }
    this.dead = false;
    this.sensor = new Phaser.Math.Vector2();
    this.world;
  }
  
  update(dt) {
   
    this.velocity.add(this.world.gravity.clone().scale(dt));
    // calculate the new position based on the velocity (but the actual position is not yet set to the new position)
    this.newPos.add(this.velocity.clone().scale(dt));
  
  }

  detectCollision() {
    
    // collision check with the ground
    this.collision = false;
    this.response.reset(); // reset the response vector (will hold the collision normal)

    this.angle = this.velocity.angle(); // get the heading of the object
    
    // iterate through semicircle of object radius rotated to direction of velocity
    for (let r = this.angle - Math.PI / 2; r < this.angle + Math.PI / 2; r += Math.PI / 8) {
      // calculate the test points on the circumference of object
      this.sensor.setToPolar(r, this.radius).add(this.newPos)
      // test if the test point is colliding with the ground
      const rgba = this.canvas.getPixel(this.sensor.x, this.sensor.y);
      if (rgba.a > 0) {
        // accumulate collision points to give resopnse vector, which is effectively normal to the area of contact
        this.response.add(this.newPos.clone().subtract(this.sensor));
        this.collision = true;
      }
    }
    
    this.response.normalize(); // normalise the response vector
    
  }
  
  collisionResponse() {
    
    if (this.collision) {
      // Calculate reflection vector of objects velocity vector, using response vector as normal
      const vn = this.velocity.dot(this.response); // magnitude of the velocity along the normal
      // Use friction coefficient to dampen response (approximating energy loss)
      this.velocity.subtract(this.response.scale(2 * vn)).scale(this.friction); 
   
      //Some objects will "die" after several bounces
      if ( this.bounceBeforeDeath > 0) {
        this.bounceBeforeDeath--;
        this.dead = (this.bounceBeforeDeath == 0);
        if (this.dead) {
          if (this.explode)	{
            this.boom(this.x, this.y, this.explosionSize);            
          };
          this.destroy();
        }
      }
    } else
    {
      // No collision so update objects position
      this.setPosition(this.newPos.x, this.newPos.y);

    }
  }
 
  boom( x,  y, radius) {
	  // Erase Terrain to form crater
    this.canvas.context.beginPath();
    this.canvas.context.arc(x, y, radius, 0, Math.PI*2);
    this.canvas.context.fill();
    this.canvas.update();
    
		// Launch debris
    for (let i = 0; i < this.explosionDebris; i++) {   
      const debris = new Ball(this.scene, x, y, "debris", {bounceBeforeDeath: 3});
      Phaser.Math.RandomXY(debris.velocity, 100)
      this.world.add(debris);
    }			

  }
 
}

class World {
  constructor() {
    this.gravity = new Phaser.Math.Vector2(0,100);
    this.bodies = [];
    
  }
  
  add(ball) {
    this.bodies.push(ball);
    ball.world = this;
    
  }
  
  step(dt) {
  
    this.bodies.forEach(b => {
      b.update(dt);
      b.detectCollision();
      b.collisionResponse();
      this.checkBoundary(b);
    });
    
  }
 
  checkBoundary(b) {
    if (b.y > height - b.radius) {
      b.y = height - b.radius;
      b.velocity.y *= -b.friction;
    } else if (b.y - b.radius <= 0) {
      b.y = b.radius;
      b.velocity.y *= -b.friction;
    }
    if (this.x >= width - b.radius) {
      b.x = width - this.radius;
      b.velocity.x *= -b.friction;
    } else if (b.x - b.radius <= 0) {
      b.x = this.radius;
      b.velocity.x *= -b.friction;
    }
  }
  
}

class Game extends Phaser.Scene {
  constructor() {
    super({key: "Game"});  
  }

  preload() {
    this.load.image("bomb", "https://raw.githubusercontent.com/cedarcantab/photonstorm/main/issue-007/assets/bomb.png");
    this.load.image("debris", "https://raw.githubusercontent.com/cedarcantab/photonstorm/main/issue-007/assets/debris.png");
  }
  
  create() {
    this.add.text(0,0,"CLICK MOUSE TO DROP BOMB!")
    // createCanvas creates a new Textures using a blank Canvas element of the size given
    this.canvas = this.textures.createCanvas('canvastexture', width, height);
    this.add.image(0, 0, 'canvastexture').setOrigin(0);
    this.ctx = this.canvas.context;
  
    this.world = new World(this.canvas, this.ctx);
 
 //   this.flatTerrain(this.ctx);
    this.sinTerrain(this.ctx);
 
    // 'destination-out' basically means the part of the destination image drawn over by the source image will be transparent
    this.canvas.context.globalCompositeOperation = 'destination-out';
    //  Now anything drawn to the canvas will use this op

    this.ball = new Ball(this, 300, 30, "bomb", {
      bounceBeforeDeath: 5, 
      explode: true
    });
    this.world.add(this.ball);
    this.input.on('pointerdown', p => {
      const ball = new Ball(this, p.x,p.y, "bomb", {bounceBeforeDeath: 5, explode: true});
      this.world.add(ball);
    })

  }
  
  update(t, dt) {
    this.world.step(dt*0.001);
  }

  flatTerrain(ctx) {
    const floor = 100;
    ctx.fillStyle = "green"
    for (let x = 0; x < width; x++) {
      ctx.fillRect(x, height - floor, 1, floor)
    }
    this.canvas.update();
  }
  
  sinTerrain(ctx) {

    ctx.fillStyle = "green"
    for (let x = 0; x < width; x++) {
      const curY = 300+ Math.sin(x/width*2*Math.PI)*50;
      ctx.fillRect(x, curY, 1, height - curY)
    }
    this.canvas.update();
  }

}

const config = {
  width: 600,
  height: 400,
  scene: [Game]
};

width = config.width;
height = config.height;

const game = new Phaser.Game(config);

              
            
!
999px

Console