123

Pen Settings

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. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

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

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠ī¸ This feature can only be used by logged in users.

Code Indentation

     

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.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              canvas
  background: #26A69A
            
          
!
            
              /**
 * @fildesc As in a free fall horizontal velocity remains constant. Floor has the hight coefficient of restitution but less than one which means that maximum height will decrease over time. Collision with vertical walls is considered as fully elastic collision. Appropriate acceleration has been chosen for the model.
 */

/**
 * @classdesc Represents points and vectors and also provides functionality to add them toghether.
 */
class Vector {
  constructor(public x: number,  public y: number) {}

  static public add(vec1: Vector, vec2: Vector): Vector {
    return new Vector(vec1.x + vec2.x, vec1.y + vec2.y);
  }
  
  static public subtract(vec1: Vector, vec2: Vector): Vector {
    return new Vector(vec1.x - vec2.x, vec1.y - vec2.y);
  }
  
  static public dotProduct(vec1: Vector, vec2: Vector): number {
    return vec1.x * vec2.x + vec1.y * vec2.y;
  }
  
  static public distance(vec1: Vector, vec2: Vector): number {
    return Math.hypot(vec1.x - vec2.x, vec1.y - vec2.y);
  }
}

/**
 * @classdesc Only this class should be modified to set any parameters.
 */
class Config {
  public static readonly size = 25;
  
  public static get numberOfEmojis(): number {
    const emojiArea = this.size ** 2;
    const canvasArea = innerWidth * innerHeight;
    return Math.floor(canvasArea / emojiArea) / 2;
  }

  public static get emoji(): string {
    return this.emojis[Math.floor(Math.random() * this.emojis.length)];
  }
  
  public static get position(): Vector {
    return new Vector(
      (window.innerWidth - 2 * Config.size) * Math.random() + Config.size,
      (window.innerHeight - 2 * Config.size) * Math.random() + Config.size
    )
  }
  
  static get velocity(): Vector {
    return new Vector(
      Math.random() * 5 - 2.5,
      Math.random() * 5 - 2.5
    );
  }

  private static get emojis(): string[] {
    return [
      '😀', '😂', '😇', '😍', '😘',
      '😛', '🤑', '🤗', '🤓', '😎',
      '😤', '😡', 'đŸ˜ĩ', 'đŸ˜ŗ', '😨',
      '😴', '🤔', 'đŸ¤Ĩ', 'đŸ˜Ŧ', '🤐',
      'đŸ¤ĸ', '🤧', '😷', '🤒', '🤕'
    ];
    
    // return ['😀', '😃', '😄', '😁', '😆', '😅', '😂', 'đŸ¤Ŗ', 'â˜ēī¸', '😊', '😇', '🙂', '🙃', '😉', '😌', '😍', '😘', '😗', '😙', '😚', '😋', '😜', '😝', '😛', '🤑', '🤗', '🤓', '😎', '🤡', '🤠', '😏', '😒', '😞', '😔', '😟', '😕', '🙁', '☚ī¸', 'đŸ˜Ŗ', '😖', 'đŸ˜Ģ', '😩', '😤', '😠', '😡', 'đŸ˜ļ', '😐', '😑', 'đŸ˜¯', 'đŸ˜Ļ', '😧', '😮', '😲', 'đŸ˜ĩ', 'đŸ˜ŗ', '😱', '😨', '😰', 'đŸ˜ĸ', 'đŸ˜Ĩ', '🤤', '😭', '😓', 'đŸ˜Ē', '😴', '🙄', '🤔', 'đŸ¤Ĩ', 'đŸ˜Ŧ', '🤐', 'đŸ¤ĸ', '🤧', '😷', '🤒', '🤕'];
  }
}

/**
 * @classdesc Each emoji is an independend particle obeying physics law namely gravitational force and inelastic collitions with the ground.
 */
class Emoji {
  public position: Vector;
  public emoji: string;
  public size: number;
  public velocity: Vector;

  constructor(
    position = Config.position,
    velocity = Config.velocity,
    emoji = Config.emoji,
    size = Config.size
  ) {
    // Choosing random initial position for emoji.
    this.position = position;
      
    // Initialising with random emoji.
    this.emoji = emoji;
    
    // Setting size.
    this.size = size;
    
    // Setting horizontal velocity between -1, 1 and vertical velocity to be 0.
    this.velocity = velocity;
  }

  public move() {
    // Updating position.
    this.position = Vector.add(this.position, this.velocity);
    
    // Collision with vertical walls.
    if (
      this.position.x - this.size / 2 < 0 && this.velocity.x < 0
      ||
      this.position.x + this.size / 2 > window.innerWidth && this.velocity.x > 0
    ) {
      this.velocity.x = -this.velocity.x;
    }

    // Collision with horizontal walls.
    if (
      this.position.y - this.size / 2 < 0 && this.velocity.y < 0
      ||
      this.position.y + this.size / 2 > window.innerHeight && this.velocity.y > 0
    ) {
      this.velocity.y = -this.velocity.y;
    }
  }
  
  public get radius() {
    const radiusToSizeRatio = 0.46;
    return this.size * radiusToSizeRatio;
  }

  public draw(ctx: HTMLElement) {
    const xToSizeRatio = 0.5;
    const yToSizeRatio = 0.425;
    ctx.font = this.size + 'px Verdana';
    // ctx.beginPath();
    // ctx.arc(this.position.x, this.position.y, this.radius, 0, 2 * Math.PI);
    // ctx.stroke();
    ctx.fillText(
      this.emoji,
      this.position.x - this.size * xToSizeRatio,
      this.position.y + this.size * yToSizeRatio
    );
  }
}

/**
 * @classdesc Main class reponsible for running the experiment.
 */
class GravitatingEmojis {
  private canvas: HTMLElement;
  private context: HTMLElement;

  constructor() {
    // Creating a canvas.
    this.canvas = document.createElement('canvas');

    // Setting the canvas size.
    this.canvas.width = window.innerWidth;
    this.canvas.height = window.innerHeight;

    // Appending the canvas to body
    document.body.appendChild(this.canvas);

    // Getting context with alpha channel.
    this.ctx = this.canvas.getContext('2d', {alpha: false});

    // Initialisation of emojis.
    this.emojis = Array.from({length: Config.numberOfEmojis}, () => new Emoji());

    // Handling resize event.
    addEventListener('resize', this.resize.bind(this));

    // Handling click/reset event.
    addEventListener('click', this.click.bind(this));

    // Requesting animation frame.
    requestAnimationFrame(this.animationFrame.bind(this));
  }

  private animationFrame() {
    // Clearing canvas.
    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

    // Iterating through each emoji.
    for (let i = 0; i < this.emojis.length; i++) {
      const emoji1 = this.emojis[i];
      emoji1.move();
      emoji1.draw(this.ctx);
      for (let j = i + 1; j < this.emojis.length; j++) {
        const emoji2 = this.emojis[j];
        if (this.areColiding(emoji1, emoji2)) {
          if (this.areSimilar(emoji1, emoji2)) {
            this.resolveMerge(emoji1, emoji2);
          } else {
            this.resolveCollision(emoji1, emoji2);
          }
        }
      }
    }

    // Getting next frame.
    requestAnimationFrame(this.animationFrame.bind(this));
  }
  
  private areColiding(emoji1: Emoji, emoji2: Emoji) {
    return Vector.distance(emoji1.position, emoji2.position) < emoji1.radius + emoji2.radius;
  }
    
  private areSimilar(emoji1: Emoji, emoji2: Emoji) {
    return emoji1.emoji === emoji2.emoji;
  }

  private resolveMerge(emoji1: Emoji, emoji2: Emoji) {
    // Remove both identical emojis.
    this.emojis.splice(this.emojis.indexOf(emoji1), 1);
    this.emojis.splice(this.emojis.indexOf(emoji2), 1);
    
    // Create new emoji.
    const position = new Vector(
      (emoji1.position.x + emoji2.position.x) / 2,
      (emoji1.position.y + emoji2.position.y) / 2
    );
    
    // Weighted resultant velocity.
    const velocity = new Vector(
      (emoji1.velocity.x * emoji1.radius + emoji2.velocity.x * emoji2.radius) / (emoji1.radius + emoji2.radius),
      (emoji1.velocity.y * emoji1.radius + emoji2.velocity.y * emoji2.radius) / (emoji1.radius + emoji2.radius)
    );
    
    const emoji = emoji1.emoji;
    const size = Math.max(emoji1.size, emoji2.size) + Math.min(emoji1.size, emoji2.size) / 2;
    
    this.emojis.unshift(new Emoji(position, velocity, emoji, size));
  }
  
  private resolveCollision(emoji1: Emoji, emoji2: Emoji) {
    const velocity = Vector.subtract(emoji2.velocity, emoji1.velocity);
    const displacement = Vector.subtract(emoji2.position, emoji1.position);
    const dotProduct = Vector.dotProduct(velocity, displacement);
    if (dotProduct > 0 ) {
      return;
    }
    
        // Direction change.
    const radiusSum = emoji1.radius + emoji2.radius;
    const directionX1 = (emoji1.velocity.x * (emoji1.radius - emoji2.radius) + (2 * emoji2.radius * emoji2.velocity.x)) / radiusSum;
    const directionY1 = (emoji1.velocity.y * (emoji1.radius - emoji2.radius) + (2 * emoji2.radius * emoji2.velocity.y)) / radiusSum;
    const directionX2 = (emoji2.velocity.x * (emoji2.radius - emoji1.radius) + (2 * emoji1.radius * emoji1.velocity.x)) / radiusSum;
    const directionY2 = (emoji2.velocity.y * (emoji2.radius - emoji1.radius) + (2 * emoji1.radius * emoji1.velocity.y)) / radiusSum;
    emoji1.velocity = new Vector(directionX1, directionY1);
    emoji2.velocity = new Vector(directionX2, directionY2);
  }

  private resize() {
    this.canvas.width = window.innerWidth;
    this.canvas.height = window.innerHeight;
  }

  private click() {
    this.emojis = Array.from({length: Config.numberOfEmojis}, () => new Emoji());
  }
}

// Initialisation.
new GravitatingEmojis();
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.

Console