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.

            
              <div class="camera"></div>
<div class="hud">
  <div class="heart heart-1"></div>
  <div class="heart heart-2"></div>
  <div class="heart heart-3"></div>
</div>
<div class="focus-target">click to focus</div>
            
          
!
            
              html, body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

html {
  overflow: hidden;
}

body {
  background: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/780791/background.png");
  color: grey;
  font-family: helvetica, arial;
  font-size: 20px;
  cursor: none;
}

canvas {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  pointer-events: none;
}

.camera, .hud, .focus-target {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
}

.hud {
  .heart {
    width: 32px;
    height: 28px;
    background-image: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/780791/heart-red.png");
    position: absolute;
    top: 15px;
  }
  
  .heart-1 {
    left: 15px;
  }
  
  .heart-2 {
    left: 57px;
  }
  
  .heart-3 {
    left: 99px;
  }
  
  .heart-grey {
    background-image: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/780791/heart-grey.png");
  }
}

.focus-target {
  padding: 25px;
  text-align: center;
}
            
          
!
            
              // Thank you for supporting my work. If you came here from the
// Humble Bundle; you probably don’t know that I do a lot of this
// writing and open source work for free. Please consider supporting
// my work at https://www.patreon.com/assertchris. You’ll receive support
// rewards and free me up to make more awesome code and books for you to read.

class Player {
  constructor(sprite, rectangle) {
    this.sprite = sprite
    this.rectangle = rectangle
    
    this.velocityX = 0
    this.maximumVelocityX = 8
    this.accelerationX = 2
    this.frictionX = 0.9
    
    this.velocityY = 0
    this.maximumVelocityY = 30
    this.accelerationY = 3
    this.jumpVelocity = -30
    
    this.climbingSpeed = 10
    
    this.isOnGround = false
    this.isOnLadder = false
    this.isOnSlope = false
  }

  animate(state) {
    if (state.keys[37] || state.keys[65]) { // left
      this.velocityX = Math.max(
        this.velocityX - this.accelerationX,
        this.maximumVelocityX * -1,
      )
    }

    if (state.keys[39] || state.keys[68]) { // right
      this.velocityX = Math.min(
        this.velocityX + this.accelerationX,
        this.maximumVelocityX,
      );
    }

    this.velocityX *= this.frictionX

    this.velocityY = Math.min(
      this.velocityY + this.accelerationY,
      this.maximumVelocityY,
    )

    state.objects.forEach((object) => {
      if (object === this) {
        return
      }

      const me = this.rectangle
      const you = object.rectangle
      const collides = object.collides

      if (me.x < you.x + you.width &&
          me.x + me.width > you.x &&
          me.y < you.y + you.height &&
          me.y + me.height > you.y) {

        if (object.constructor.name === "LeftSlope") {
          const meCenter = Math.round(me.x + (me.width / 2))
          const youRight = you.x + you.width
          const youBottom = you.y + you.height
          const highest = you.y - me.height
          const lowest = youBottom - me.height

          this.isOnGround = true
          this.isOnSlope = true

          me.y = lowest - (meCenter - you.x)
          me.y = Math.max(me.y, highest)
          me.y = Math.min(me.y, lowest)

          if (me.y >= lowest || me.y <= highest) {
            this.isOnSlope = false
          }

          return
        }

        if (object.constructor.name === "RightSlope") {
          const meCenter = Math.round(me.x + (me.width / 2))
          const youBottom = you.y + you.height
          const highest = you.y - me.height
          const lowest = youBottom - me.height

          this.isOnGround = true
          this.isOnSlope = true

          me.y = highest + (meCenter - you.x)
          me.y = Math.max(me.y, highest)
          me.y = Math.min(me.y, lowest)

          if (me.y >= lowest || me.y <= highest) {
            this.isOnSlope = false
          }

          return
        }

        if (object.constructor.name === "Ladder") {
          if (state.keys[38] || state.keys[40] || state.keys[87] || state.keys[83]) {
            this.isOnLadder = true
            this.isOnGround = false
            this.velocityY = 0
            this.velocityX = 0
          }

          if (state.keys[38] || state.keys[87]) {
            this.rectangle.y -= this.climbingSpeed
          }

          if (state.keys[40] || state.keys[83] && me.y + me.height < you.y + you.height) {
            this.rectangle.y += this.climbingSpeed
          }

          if (me.y <= you.x - me.height) {
            this.isOnLadder = false
          }

          return
        }
        
        if (object.constructor.name === "Blob" && !this.invulnerable) {
          if (this.velocityX >= 0) {
            this.velocityX = -10
          } else {
            this.velocityX = 10
          }

          this.velocityY *= -1

          this.invulnerable = true
          this.sprite.alpha = 0.5

          setTimeout(() => {
            this.invulnerable = false
            this.sprite.alpha = 1
          }, 2000)

          if (typeof this.onHurt === "function") {
            this.onHurt.apply(this)
          }
        }

        if (collides && this.velocityY > 0 && you.y >= me.y) {
          me.y = you.y - me.height + 1
          this.isOnGround = true
          this.velocityY = 0
          return
        }

        if (collides && this.velocityY < 0 && you.y <= me.y) {
          this.velocityY = this.accelerationY
          return
        }

        if (collides && this.velocityX < 0 && you.x <= me.x) {
          this.velocityX = 0
          return
        }

        if (collides && this.velocityX > 0 && you.x >= me.x) {
          this.velocityX = 0
          return
        }
      }
    })

    if (state.keys[32] && this.isOnGround) {
        this.velocityY = this.jumpVelocity
        this.isOnGround = false
        this.isOnSlope = false
    }

    this.rectangle.x += this.velocityX

    if (!this.isOnLadder && !this.isOnSlope) {
      this.rectangle.y += this.velocityY
    }

    this.sprite.x = this.rectangle.x
    this.sprite.y = this.rectangle.y
  }
}

class Box {
  get collides() {
    return true
  }
  
  constructor(sprite, rectangle) {
    this.sprite = sprite
    this.rectangle = rectangle
  }

  animate(state) {
    this.sprite.x = this.rectangle.x
    this.sprite.y = this.rectangle.y
  }
}

class Ladder extends Box {
  get collides() {
    return false
  }
}

class LeftSlope extends Box {
  get collides() {
    return false
  }
}

class RightSlope extends Box {
  get collides() {
    return false
  }
}

class Decal extends Box {
  get collides() {
    return false
  }
}

class Crosshair extends Decal {
  animate(state) {
    const rect = state.player.rectangle
    
    const centerX = rect.x + (rect.width / 2)
    const centerY = rect.y + (rect.height / 2)
    
    const radius = 70
    
    const targetX = centerX + Math.cos(state.angle) * radius
    const targetY = centerY - Math.sin(state.angle) * radius
    
    this.sprite.x = targetX
    this.sprite.y = targetY
  }
}

class Bullet extends Decal {
  animate(state) {
    const rect = state.player.rectangle
    
    this.x = this.x || rect.x + rect.width
    this.y = this.y || rect.y + (rect.height / 2)
    this.angle = this.angle || state.angle
    this.rotation = this.rotation || state.rotation
    this.radius = this.radius || 0
    
    this.radius += 10
    
    const targetX = this.x + Math.cos(this.angle) * this.radius
    const targetY = this.y - Math.sin(this.angle) * this.radius
    
    this.rectangle.x = targetX
    this.rectangle.y = targetY

    this.sprite.x = targetX
    this.sprite.y = targetY
    this.sprite.rotation = this.rotation
    
    state.objects.forEach((object) => {
      if (object === this) {
        return
      }

      const me = this.rectangle
      const you = object.rectangle

      if (me.x < you.x + you.width &&
          me.x + me.width > you.x &&
          me.y < you.y + you.height &&
          me.y + me.height > you.y) {

        if (object.constructor.name === "Blob") {
          state.game.removeObject(object)
          state.game.removeObject(this)
        }
      }
    })
  }
}

class Blob extends Box {
  constructor(sprite, rectangle) {
    super(sprite, rectangle)
    
    this.limit = 200
    this.left = true
  }
  animate(state) {
    if (this.left) {
      this.rectangle.x -= 2
    }
    
    if (!this.left) {
      this.rectangle.x += 2
    }
    
    this.limit -= 2
      
    if (this.limit <= 0) {
      this.left = !this.left
      this.limit = 200
    }
    
    this.sprite.x = this.rectangle.x
    this.sprite.y = this.rectangle.y
  }
}

class Game {
  constructor(w, h) {
    this.w = w
    this.h = h

    this.state = {
      "game": this,
      "keys": {},
      "clicks": {},
      "mouse": {},
      "objects": [],
      "player": null,
      "crosshair": null,
    }
    
    this.animate = this.animate.bind(this)
  }

  get stage() {
    if (!this._stage) {
      this._stage = this.newStage()
    }

    return this._stage
  }

  set stage(stage) {
    this._stage = stage
  }

  newStage() {
    return new PIXI.Container()
  }

  get renderer() {
    if (!this._renderer) {
      this._renderer = this.newRenderer()
    }

    return this._renderer
  }

  set renderer(renderer) {
    this._renderer = renderer
  }

  newRenderer() {
    return new PIXI.autoDetectRenderer(
      this.w, this.h, this.newRendererOptions(),
    )
  }

  newRendererOptions() {
    return {
      "antialias": true,
      "autoResize": true,
      "transparent": true,
      "roundPixels": true,
      "resolution": 2,
    }
  }
  
  animate() {
    requestAnimationFrame(this.animate)

    this.state.renderer = this.renderer
    this.state.stage = this.stage
    this.state.player = this.player
    this.state.crosshair = this.crosshair

    this.state.objects.forEach((object) => {
      object.animate(this.state)
    })

    if (this.player) {
      const offsetLeft = Math.round(
        this.player.rectangle.x + (this.player.rectangle.width / 2) - (window.innerWidth / 2)
      ) * -1

      const offsetTop = Math.round(
        this.player.rectangle.y + (this.player.rectangle.height / 2) - (window.innerHeight / 2)
      ) * -1

      this.element.style = `
        transform:
        scale(1.2)
        translate(${offsetLeft}px)
        translateY(${offsetTop}px)
      `
    }

    this.renderer.render(this.stage)
  }

  addEventListenerTo(element) {
    element.addEventListener("keydown", (event) => {
      this.state.keys[event.keyCode] = true
    })

    element.addEventListener("keyup", (event) => {
      this.state.keys[event.keyCode] = false
    })

    element.addEventListener("mousedown", (event) => {
      this.state.clicks[event.which] = {
        "clientX": event.clientX,
        "clientY": event.clientY,
      }

      if (event.button === 0) { // left click
        const rect = this.player.rectangle

        const bullet = new Bullet(
          new PIXI.Sprite.fromImage(
            "https://s3-us-west-2.amazonaws.com/s.cdpn.io/780791/bullet.png",
          ),
          new PIXI.Rectangle(
            rect.x + rect.width,
            rect.y,
            8,
            8,
          ),
        )

        this.addObject(bullet)

        setTimeout(() => {
          this.removeObject(bullet)
        }, 500)
      }
    })

    element.addEventListener("mouseup", (event) => {
      this.state.clicks[event.which] = false
    })

    element.addEventListener("mousemove", (event) => {
      this.state.mouse.clientX = event.clientX
      this.state.mouse.clientY = event.clientY

      const rect = this.player.rectangle

      const centerX = (window.innerWidth / 2) + (rect.width / 2)
      const centerY = (window.innerHeight / 2) + (rect.height / 2)

      const deltaX = event.clientX - centerX
      const deltaY = centerY - event.clientY

      const rotationX = event.clientX - centerX
      const rotationY = event.clientY - centerY

      this.state.angle = Math.atan2(deltaY, deltaX)
      this.state.rotation = Math.atan2(rotationY, rotationX)
    })
  }

  addRendererTo(element) {
    this.element = element
    this.element.appendChild(this.renderer.view)
  }

  addObject(object) {
    this.state.objects.push(object)
    this.stage.addChild(object.sprite)
  }
  
  removeObject(object) {
    this.state.objects = this.state.objects.filter(
      function(next) {
        return next !== object
      }
    )

    this.stage.removeChild(object.sprite)
  }
}

const width = window.innerWidth
const height = window.innerHeight + 200

const game = new Game(
  width,
  height,
)

game.addObject(
  new Box(
    new PIXI.extras.TilingSprite.fromImage(
      "https://s3-us-west-2.amazonaws.com/s.cdpn.io/780791/floor-tile.png",
      width,
      64,
    ),
    new PIXI.Rectangle(
      0,
      height - 64,
      width,
      64,
    ),
  ),
)

game.addObject(
  new Box(
    new PIXI.Sprite.fromImage(
      "https://s3-us-west-2.amazonaws.com/s.cdpn.io/780791/box.png",
    ),
    new PIXI.Rectangle(
      0 + 32,
      height - 44 - 64,
      44,
      44,
    ),
  ),
)

game.addObject(
  new Box(
    new PIXI.Sprite.fromImage(
      "https://s3-us-west-2.amazonaws.com/s.cdpn.io/780791/box.png",
    ),
    new PIXI.Rectangle(
      width - 32 - 44,
      height - 44 - 64,
      44,
      44,
    ),
  ),
)

game.addObject(
  new Box(
    new PIXI.Sprite.fromImage(
      "https://s3-us-west-2.amazonaws.com/s.cdpn.io/780791/platform.png",
    ),
    new PIXI.Rectangle(
      width - 400,
      height - 64 - 200,
      256,
      64,
    ),
  ),
)

game.addObject(
  new Ladder(
    new PIXI.extras.TilingSprite.fromImage(
      "https://s3-us-west-2.amazonaws.com/s.cdpn.io/780791/ladder.png",
      44,
      200,
    ),
    new PIXI.Rectangle(
      width - 250,
      height - 64 - 200,
      44,
      200,
    ),
  ),
)

game.addObject(
  new LeftSlope(
    new PIXI.Sprite.fromImage(
      "https://s3-us-west-2.amazonaws.com/s.cdpn.io/780791/slope-left.png",
    ),
    new PIXI.Rectangle(
      0 + 250,
      height - 64 - 64 + 1,
      64,
      64,
    ),
  ),
)

game.addObject(
  new RightSlope(
    new PIXI.Sprite.fromImage(
      "https://s3-us-west-2.amazonaws.com/s.cdpn.io/780791/slope-right.png",
    ),
    new PIXI.Rectangle(
      0 + 250 + 64 + 128,
      height - 64 - 64 + 1,
      64,
      64,
    ),
  ),
)

game.addObject(
  new Decal(
    new PIXI.Sprite.fromImage(
      "https://s3-us-west-2.amazonaws.com/s.cdpn.io/780791/hill-base.png",
    ),
    new PIXI.Rectangle(
      0 + 250,
      height - 64 + 1,
      128,
      64,
    ),
  ),
)

game.addObject(
  new Box(
    new PIXI.Sprite.fromImage(
      "https://s3-us-west-2.amazonaws.com/s.cdpn.io/780791/hill-top.png",
    ),
    new PIXI.Rectangle(
      0 + 250 + 64,
      height - 64 - 64 + 1,
      128,
      64,
    ),
  ),
)

game.addObject(
  new Blob(
    new PIXI.Sprite.fromImage(
      "https://s3-us-west-2.amazonaws.com/s.cdpn.io/780791/blob-idle-1.png",
    ),
    new PIXI.Rectangle(
      width - 450,
      height - 64 - 48,
      48,
      48,
    ),
  ),
)

const player = new Player(
  new PIXI.Sprite.fromImage(
    "https://s3-us-west-2.amazonaws.com/s.cdpn.io/780791/player-idle.png",
  ),
  new PIXI.Rectangle(
    Math.round(width / 2),
    Math.round(height / 2),
    44,
    56,
  ),
)

game.addObject(player)
game.player = player

let hearts = 3

player.onHurt = function() {
  document.querySelector(`.heart-${hearts}`).className += " heart-grey"
  
  hearts--
  
  if (hearts < 1) {
    alert("game over!")
    game.removeObject(player)
    game.removeObject(crosshair)
  }
}

const crosshair = new Crosshair(
  new PIXI.Sprite.fromImage(
    "https://s3-us-west-2.amazonaws.com/s.cdpn.io/780791/crosshair.png",
  ),
  new PIXI.Rectangle(
    50,
    50,
    18,
    18,
  ),
)

game.addObject(crosshair)
game.crosshair = crosshair

game.addEventListenerTo(window)
game.addRendererTo(document.querySelector(".camera"))
game.animate()
            
          
!
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