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

              
                <div class="info">
  From the tutorial: <a href="http://flippinawesome.org/2013/12/02/building-a-2d-browser-game-with-physicsjs/">Building a 2D Browser Game with PhysicsJS</a> on flippinawesome.
</div>
              
            
!

CSS

              
                html, body {
    padding: 0;
    margin: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
}
body:after {
    font-size: 30px;
    line-height: 140px;
    text-align: center;
    color: rgb(60, 16, 11);
    background: rgba(255, 255, 255, 0.6);
    position: absolute; 
    top: 50%;
    left: 50%;
    width: 400px;
    height: 140px;
    margin-left: -200px;
    margin-top: -70px;
    border-radius: 5px;
}
body.before-game:after {
    content: 'press "z" to start';
}
body.lose-game:after {
    content: 'press "z" to try again';
}
body.win-game:after {
    content: 'Win! press "z" to play again';
}
/* spaceship from: http://millionthvector.blogspot.ca/p/free-sprites.html */
/* starfield from: https://gamedevtuts.s3.amazonaws.com/043_freeShmupSprites/Free_Shmup_Sprites_Starfield.png */
body {
  background: url(https://raw.github.com/wellcaffeinated/PhysicsJS/ship-demo/examples/spaceship/images/starfield.png) 0 0 repeat;
}


.info {
    display: none;
    position: absolute;
    z-index: 2;
    top: 0;
    left: 0;
    font-size: 20px;
    color: #ffd;
    padding: 4px;
}
.info a {
    color: #ffd;
}
body.before-game .info {
    display: block;
}
              
            
!

JS

              
                // main.js begins
require(
  {
    baseUrl: 'http://wellcaffeinated.net/PhysicsJS/examples/spaceship/',
    packages: [{
      name: 'physicsjs',
      location: 'http://wellcaffeinated.net/PhysicsJS/assets/scripts/vendor/physicsjs-0.5.2/',
      main: 'physicsjs-0.5.2.min'
    }]
  },
  [
  'require',
  'physicsjs',
  
  // custom modules
  'js/player',
  'js/player-behavior',
  'js/ufo',
  
  // official modules
  'physicsjs/renderers/canvas',
  'physicsjs/bodies/circle',
  'physicsjs/bodies/convex-polygon',
  'physicsjs/behaviors/newtonian',
  'physicsjs/behaviors/sweep-prune',
  'physicsjs/behaviors/body-collision-detection',
  'physicsjs/behaviors/body-impulse-response'
], function(
  require,
  Physics
){
  document.body.className = 'before-game';
  var par = parent;
    try {
      par && par.innerWidth;
    } catch( e ){
      par = window;
    }
  var inGame = false;
  document.addEventListener('keydown', function( e ){
    
    if (!inGame && e.keyCode === 90){
      document.body.className = 'in-game';
      inGame = true;
      newGame();
    }
  });
  
  var renderer = Physics.renderer('canvas', {
    el: 'viewport',
    width: par.innerWidth,
    height: par.innerHeight,
    // meta: true,
    // debug:true,
    styles: {
      'circle': {
        strokeStyle: 'rgb(0, 30, 0)',
        lineWidth: 1,
        fillStyle: 'rgb(100, 200, 50)',
        angleIndicator: false
      },
      'convex-polygon' : {
        strokeStyle: 'rgb(60, 0, 0)',
        lineWidth: 1,
        fillStyle: 'rgb(60, 16, 11)',
        angleIndicator: false
      }
    }
  });
  
  window.addEventListener('resize', function(){
    renderer.el.width = par.innerWidth;
    renderer.el.height = par.innerHeight;
  });
  
  var init = function init( world, Physics ){
    
    // bodies
    var ship = Physics.body('player', {
      x: 400,
      y: 100,
      vx: 0.08,
      radius: 30
    });
    
    var playerBehavior = Physics.behavior('player-behavior', { player: ship });
    
    var ufos = [];
    for ( var i = 0, l = 30; i < l; ++i ){
      
      var ang = 4 * (Math.random() - 0.5) * Math.PI;
      var r = 700 + 100 * Math.random() + i * 10;
      
      ufos.push( Physics.body('ufo', {
        x: 400 + Math.cos( ang ) * r,
        y: 300 + Math.sin( ang ) * r,
        vx: 0.03 * Math.sin( ang ),
        vy: - 0.03 * Math.cos( ang ),
        angularVelocity: (Math.random() - 0.5) * 0.001,
        radius: 50,
        mass: 30,
        restitution: 0.6
      }));
    }
    
    var planet = Physics.body('circle', {
      // fixed: true,
      // hidden: true,
      mass: 10000,
      radius: 140,
      x: 400,
      y: 300
    });
    planet.view = new Image();
    planet.view.src = require.toUrl('images/planet.png');
    
    // render on every step
    world.subscribe('step', function(){
      // middle of canvas
      var middle = { 
        x: 0.5 * par.innerWidth, 
        y: 0.5 * par.innerHeight
      };
      // follow player
      renderer.options.offset.clone( middle ).vsub( ship.state.pos );
      world.render();
    });
    
    // count number of ufos destroyed
    var killCount = 0;
    world.subscribe('blow-up', function( data ){
      
      killCount++;
      if ( killCount === ufos.length ){
        world.publish('win-game');
      }
    });
    
    // blow up anything that touches a laser pulse
    world.subscribe('collisions:detected', function( data ){
      var collisions = data.collisions
      ,col
      ;
      
      for ( var i = 0, l = collisions.length; i < l; ++i ){
        col = collisions[ i ];
        
        if ( col.bodyA.gameType === 'laser' || col.bodyB.gameType === 'laser' ){
          if ( col.bodyA.blowUp ){
            col.bodyA.blowUp();
          } else if ( col.bodyB.blowUp ){
            col.bodyB.blowUp();
          }
          return;
        }
      }
    });
    
    // draw minimap
    world.subscribe('render', function( data ){
      // radius of minimap
      var r = 100;
      // padding
      var shim = 15;
      // x,y of center
      var x = renderer.el.width - r - shim;
      var y = r + shim;
      // the ever-useful scratchpad to speed up vector math
      var scratch = Physics.scratchpad();
      var d = scratch.vector();
      var lightness;
      
      // draw the radar guides
      renderer.drawCircle(x, y, r, { strokeStyle: '#090', fillStyle: '#010' });
      renderer.drawCircle(x, y, r * 2 / 3, { strokeStyle: '#090' });
      renderer.drawCircle(x, y, r / 3, { strokeStyle: '#090' });
      
      for (var i = 0, l = data.bodies.length, b = data.bodies[ i ]; b = data.bodies[ i ]; i++){
        
        // get the displacement of the body from the ship and scale it
        d.clone( ship.state.pos ).vsub( b.state.pos ).mult( -0.05 );
        // color the dot based on how massive the body is
        lightness = Math.max(Math.min(Math.sqrt(b.mass*10)|0, 100), 10);
        // if it's inside the minimap radius
        if (d.norm() < r){
          // draw the dot
          renderer.drawCircle(x + d.get(0), y + d.get(1), 1, 'hsl(60, 100%, '+lightness+'%)');
        }
      }
      
      scratch.done();
    });
    
    // add things to the world
    world.add([
      ship,
      playerBehavior,
      planet,
      Physics.behavior('newtonian', { strength: 1e-4 }),
      Physics.behavior('sweep-prune'),
      Physics.behavior('body-collision-detection'),
      Physics.behavior('body-impulse-response'),
      renderer
    ]);
    world.add( ufos );
  };
  
  var world = null;
  var newGame = function newGame(){
    
    if (world){
      world.destroy();
    }
    
    world = Physics( init );
    world.subscribe('lose-game', function(){
      document.body.className = 'lose-game';
      inGame = false;
    });
    world.subscribe('win-game', function(){
      world.pause();
      document.body.className = 'win-game';
      inGame = false;
    });
  };
  
  // subscribe to ticker and start looping
  Physics.util.ticker.subscribe(function( time ){
    if (world){
      world.step( time ); 
    }
  }).start();
});
              
            
!
999px

Console