<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
  
  <title>jamiltron</title>
  <subtitle>Justin Hamilton — games, code, books, and other fixations.</subtitle>
  <link href="https://jamiltron.com/feed.xml" rel="self" />
  <link href="https://jamiltron.com/" />
  <updated>2026-07-19T00:00:00Z</updated>
  <id>https://jamiltron.com/</id>
  <author>
    <name>Justin Hamilton</name>
  </author>
  <entry>
    <title>Space Dregs</title>
    <link href="https://jamiltron.com/2026/07/space-dregs/" />
    <updated>2026-07-19T00:00:00Z</updated>
    <id>https://jamiltron.com/2026/07/space-dregs/</id>
    <content type="html">&lt;p&gt;Back in late high school or maybe early college I made a little Asteroids clone called &lt;a href=&quot;https://jamiltron.itch.io/space-dregs&quot;&gt;Space Dregs&lt;/a&gt;. I did this to learn the Allegro game programming library. Recetly I&#39;ve been going through old projects as I update my resume and portfolio, and I decided it might be fun to spruce up a few of them and port them to the web.&lt;/p&gt;
&lt;p&gt;I decided to make Space Dregs more free-roaming. I changed the score mechanism to a currency, and added a few backgrounds. Fuel was added to have something to buy, and upgrades came shortly after. The game established a loop of blasting asteroids, grabbing money, and buing upgrades.&lt;/p&gt;
&lt;p&gt;Adding pirates, I threw in a few basic missions, and started adding some events - mayday beacons, freighters getting attacked by raiders, and the ability to jump in and help or harm. I also hadded a faction system - killing pirates or freighters scales you in favor or disdain of their respective parties, changing the economy and the threat level of the game.&lt;/p&gt;
&lt;p&gt;It&#39;s pretty simple, but I am happy to continue improving it if people find the prototype the start of something they may find enjoyable.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Indie Web Migration</title>
    <link href="https://jamiltron.com/2026/07/indie-web-migration/" />
    <updated>2026-07-18T00:00:00Z</updated>
    <id>https://jamiltron.com/2026/07/indie-web-migration/</id>
    <content type="html">&lt;p&gt;For years &lt;code&gt;jamiltron.com&lt;/code&gt; was a Jekyll blog on GitHub Pages — which was fine, and free, and I ignored it for about five years. But I kept reading about the &lt;a href=&quot;https://indieweb.org/&quot;&gt;IndieWeb&lt;/a&gt; and got a little itch: I wanted to host the site on one of my servers, backed up, and using slightly more flexible technology than I felt GitHub Pages afforded me.&lt;/p&gt;
&lt;h2&gt;Indie Web&lt;/h2&gt;
&lt;p&gt;The whole pitch of the IndieWeb is simple: your website is your home on the internet, and everything else:  Mastodon, Bluesky, the sites and platforms that will inevitably enshittify next is an outpost. You post on places you own first, then syndicate out. If a silo dies, your writing doesn&#39;t go with it.&lt;/p&gt;
&lt;p&gt;So this site is now:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Self-hosted.&lt;/li&gt;
&lt;li&gt;The identity source of truth via &lt;a href=&quot;https://indieweb.org/rel-me&quot;&gt;&lt;code&gt;rel=&amp;quot;me&amp;quot;&lt;/code&gt;&lt;/a&gt; links, so I can log into IndieWeb services as &lt;code&gt;jamiltron.com&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Marked up with &lt;a href=&quot;https://microformats.org/&quot;&gt;microformats2&lt;/a&gt; — there&#39;s an &lt;code&gt;h-card&lt;/code&gt; for me and an &lt;code&gt;h-entry&lt;/code&gt; around every post.&lt;/li&gt;
&lt;li&gt;Wired for &lt;a href=&quot;https://indieweb.org/Webmention&quot;&gt;Webmentions&lt;/a&gt;: when someone likes or replies to one of these posts over on Mastodon or Bluesky, &lt;a href=&quot;https://brid.gy/&quot;&gt;Bridgy&lt;/a&gt; forwards it here and it shows up under the post.&lt;/li&gt;
&lt;li&gt;Replies from across the web, on my own page.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Stack&lt;/h2&gt;
&lt;p&gt;For the redesign I leaned onto a series of semi-humorous sites such as &lt;a href=&quot;https://perfectmotherfuckingwebsite.com/&quot;&gt;this&lt;/a&gt;: a little semantic HTML, a handful of CSS declarations, no framework, no tracking, no megabytes of JavaScript. The only script on the page is a tiny theme toggle.&lt;/p&gt;
&lt;p&gt;The stack, for the curious:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;a href=&quot;https://www.11ty.dev/&quot;&gt;Eleventy&lt;/a&gt;&lt;/strong&gt; builds it from Markdown to plain static files. No client-side anything.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;a href=&quot;https://catppuccin.com/&quot;&gt;Catppuccin&lt;/a&gt;&lt;/strong&gt; for the colors. Mocha by default, with a toggle for Frappé and Latte.&lt;/li&gt;
&lt;li&gt;Self-hosted &lt;strong&gt;Jost&lt;/strong&gt; for type (no Google Fonts phoning home).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;It&#39;s a couple hundred kilobytes and loads quickly.&lt;/p&gt;
&lt;h2&gt;Bringing the old stuff along&lt;/h2&gt;
&lt;p&gt;I also dragged a bunch of old posts from the original &lt;code&gt;jamiltron.com&lt;/code&gt; site, and I am half debating moving &lt;a href=&quot;https://aboleth-overlords.com&quot;&gt;aboleth-overlords&lt;/a&gt; here... that&#39;s still up for debate, though.&lt;/p&gt;
&lt;p&gt;If you want to say something about a post, reply to wherever I&#39;ve shared it and it&#39;ll find its way back here.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Roguelike Celebration 2016</title>
    <link href="https://jamiltron.com/2016/09/Roguelike-Celebration/" />
    <updated>2016-09-20T00:00:00Z</updated>
    <id>https://jamiltron.com/2016/09/Roguelike-Celebration/</id>
    <content type="html">&lt;p&gt;This weekend I had the opportunity to attend Roguelike Celebration. This was a great new conference held at Eventbrite. There were a lot of great speakers and awesome people there.&lt;/p&gt;
&lt;p&gt;I don&#39;t have a very detailed write up, but I do want to suggest to everyone interested in either Roguelikes, gaming history, or game design in general to attend next year&#39;s conference.&lt;/p&gt;
&lt;p&gt;One of my friends also came to the conference, and while he plays a lot of games he doesn&#39;t really seem to identify as a &amp;quot;Roguelike player.&amp;quot; Despite that, the quality and diversity of topics were able to interest him, and I have to say that I was pleasantly surprised by how great the talks were, and how well I think they translate to game design and design in general, even outside of Roguelikes.&lt;/p&gt;
&lt;p&gt;Definitely check this conference out if you have the chance!&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Kha Shmup Tutorial Updated</title>
    <link href="https://jamiltron.com/2016/09/KhaShmup-Tutorial-Updated/" />
    <updated>2016-09-18T00:00:00Z</updated>
    <id>https://jamiltron.com/2016/09/KhaShmup-Tutorial-Updated/</id>
    <content type="html">&lt;p&gt;It&#39;s been a little while and I wanted to make sure my KhaShmup tutorial worked with the latest version of Kha.&lt;/p&gt;
&lt;p&gt;I have gone through the code as well as my previous posts and updated what I think to be everything. Not a lot has changed — mostly how the khafile resolves projects, and also the &lt;code&gt;Audio1&lt;/code&gt; play method no longer takes a boolean to determine if you want to stream the audio or not.&lt;/p&gt;
&lt;p&gt;Let me know if I have missed anything, thank you!&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Kha Shmup Tutorial Wrap Up</title>
    <link href="https://jamiltron.com/2016/01/KhaShmup-Tutorial-Wrap-Up/" />
    <updated>2016-01-04T00:00:00Z</updated>
    <id>https://jamiltron.com/2016/01/KhaShmup-Tutorial-Wrap-Up/</id>
    <content type="html">&lt;h4&gt;Finished Product&lt;/h4&gt;
&lt;h4&gt;Wrap Up&lt;/h4&gt;
&lt;p&gt;We set out to learn how to make a basic game in &lt;a href=&quot;http://kha.ktxsoftware.com&quot;&gt;Kha&lt;/a&gt; and step-by-step we put together a game using basic features of Kha. We learned the basics of rendering sprites, recieving input, playing sound, and we wrote a basic animation system as well as object pools for the types of objects we were going to be creating and destroying over and over.&lt;/p&gt;
&lt;h4&gt;Extending the Game&lt;/h4&gt;
&lt;p&gt;This game can be extended in a number of ways, here are some of the things that immediately come to mind:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Provide levels for the player to get through - either by score-chasing or just playing through a specific sequence of enemies.&lt;/li&gt;
&lt;li&gt;Allow enemies to shoot back at the player.&lt;/li&gt;
&lt;li&gt;Add a cool scrolling background.&lt;/li&gt;
&lt;li&gt;Develop different kinds of enemies other than the basic one we have.&lt;/li&gt;
&lt;li&gt;Improve performance - there are a few points such as Gun.getActiveBullets() and EnemySpawner.getActiveEnemies() where we are generating a new array every frame - we could probably extend Hitbox to contain whether or not a given hitbox should generate collisions or not and remove this hit altogether. There are also a few points where we could cache values, short-circuit code, etc.&lt;/li&gt;
&lt;li&gt;Use a more robust collision system - for this game what we are doing works, but we may want to provide multiple collision callbacks, or even use something like &lt;a href=&quot;http://gamedevelopment.tutsplus.com/tutorials/quick-tip-use-quadtrees-to-detect-likely-collisions-in-2d-space--gamedev-374&quot;&gt;QuadTrees&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;Design an AudioManager to handle sound, so if the user wants to adjust the volume or turn sound off, its easily adjustable in one place.&lt;/li&gt;
&lt;li&gt;Use or develop a more fully-featured ui system, so that if the screen size is adjusted, the ui is appropriately scaled and adjusted.&lt;/li&gt;
&lt;li&gt;Develop an EventSystem so that classes can register to recieve certain types of events, or to send events.&lt;/li&gt;
&lt;li&gt;Generally clean up the code base, maybe develop the game using a different architecture, such as an &lt;a href=&quot;https://en.wikipedia.org/wiki/Entity_component_system&quot;&gt;entity-component-system&lt;/a&gt; or &lt;a href=&quot;https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller&quot;&gt;model-view-controller&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4&gt;Resources&lt;/h4&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/KTXSoftware/Kha&quot;&gt;Kha on Github&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://forum.ktxsoftware.com/category/2/kha&quot;&gt;Kha Forums&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/KTXSoftware/Kha/wiki&quot;&gt;Kha Wiki&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://luboslenco.com/kha3d/&quot;&gt;Kha 3D&lt;/a&gt; tutorials by Lubos Lenco.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/luboslenco&quot;&gt;Lubos Lenco’s github&lt;/a&gt; contains a lot of great stuff, including the &lt;a href=&quot;https://github.com/luboslenco/zui&quot;&gt;zui&lt;/a&gt; gui system for kha.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/triplefox/khaguide&quot;&gt;Another great Kha tutorial&lt;/a&gt; by James Hoffman.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://hxscout.com/&quot;&gt;hxScout&lt;/a&gt; for profiling your games.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://kenney.nl/assets&quot;&gt;Kenny’s assets&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://www.bfxr.net/&quot;&gt;bfxr.net&lt;/a&gt; for quick audio generation.&lt;/p&gt;
&lt;p&gt;Probably a ton more I am forgetting - please include more in the comments!&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Kha Shmup Tutorial Part 10</title>
    <link href="https://jamiltron.com/2016/01/KhaShmup-Tutorial-Part-10/" />
    <updated>2016-01-03T00:00:00Z</updated>
    <id>https://jamiltron.com/2016/01/KhaShmup-Tutorial-Part-10/</id>
    <content type="html">&lt;p&gt;We wrapped up &lt;a href=&quot;http://jamiltron.com/2015/12/KhaShmup-Tutorial-Part-9/&quot;&gt;the last post&lt;/a&gt; by adding a main menu and introducing game states, and we left off one more state - the game over state.&lt;/p&gt;
&lt;p&gt;We want to make sure that we appropriately handle the collision of the player and enemies, the displaying of a game over screen, and that we allow the player to restart the game if they wish. Let’s start by making some changes to our main game class:&lt;/p&gt;
&lt;h4&gt;KhaShmup.hx&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;package;

// ...

class KhaShmup {
  // ...

  private function renderGameOver(g: Graphics): Void {
    uiManager.renderGameOver(g);
  }

  public function render(framebuffer: Framebuffer): Void {
    if (Type.enumEq(gameState, GameState.Initializing)) {
      return;
    }

    var g = backbuffer.g2;

    // clear and draw to our backbuffer
    g.begin(bgColor);
    switch(gameState) {
    case GameState.MainMenu:
      renderMainMenu(g);
      updateMainMenu();
    case GameState.Playing:
      renderPlaying(g);
      updatePlaying();
    case GameState.Over:
      renderPlaying(g);
      renderGameOver(g);
      updateGameOver();
    default:
      // no-op
    }
    g.end();

    // draw our backbuffer onto the active framebuffer
    framebuffer.g2.begin();
    Scaler.scale(backbuffer, framebuffer, System.screenRotation);
    framebuffer.g2.end();
  }

  private function handleCollisions() {
    var bullets: Array&amp;lt;Hitboxed&amp;gt; = cast ship.gun.getActiveBullets();
    var enemies: Array&amp;lt;Hitboxed&amp;gt; = cast enemySpawner.getActiveEnemies();

    CollisionHandler.handleGroupCollisions(bullets, enemies, uiManager.scoreUp);
    CollisionHandler.handleSingleToGroupCollisions(ship, enemies, setGameOver);
  }

  private function setGameOver() {
    gameState = GameState.Over;
    controls.reset();
  }

  private function updateGameOver() {
    timer.update();
    enemySpawner.update(timer.deltaTime);

    if (controls.shoot) {
      reset();
      gameState = GameState.Playing;
    }
  }

  // ...
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We add in the render and update portions for when the game is in the Over state. The new render method just lets the ui manager render some text on screen as we’ll see in a bit, and the update method allows the player to press the shoot button, which resets the game.&lt;/p&gt;
&lt;p&gt;There’s also a new call to the collision handler to check for collisions between the player ship and the enemies, supplying the setGameOver method if there are matches. We also add in a new sound (made from &lt;a href=&quot;http://bfxr.net&quot;&gt;bfxr&lt;/a&gt;), so that the player will have their own explosion sound upond collision.&lt;/p&gt;
&lt;p&gt;Looking at these changes we see that we need to update our player Ship class, as well as the CollisionHandler.&lt;/p&gt;
&lt;h4&gt;Ship.hx&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;package;

// ...
import kha.Sound;
import kha.audio1.Audio;
// ...

class Ship implements Hitboxed {
  // ...
  private var isActive = true;

  public var explosionSound: Sound;
  public var hitbox: Hitbox;
  public var x(default, set): Int;
  public var y(default, set): Int;

  private function set_x(x: Int) {
    hitbox.updatePosition(x, y);
    return this.x = x;
  }

  private function set_y(y: Int) {
    hitbox.updatePosition(x, y);
    return this.y = y;
  }

  public function new(x: Int, y: Int, image: Image, explosionSound: Sound) {
    hitbox = new Hitbox(x, y, 0, 0, image.width, image.height);
    this.x = x;
    this.y = y;
    this.image = image;
    this.explosionSound = explosionSound;
  }

  public function hit(): Void {
    isActive = false;
    Audio.play(explosionSound, false);
  }

  public function render(g: Graphics): Void {
    if (!isActive) {
      return;
    }

    if (gun != null) {
      gun.render(g);
    }
    g.drawImage(image, x, y);
  }

    public function reset(x: Int, y: Int): Void {
    isActive = true;
    this.x = x;
    this.y = y;

    if (gun != null) {
      gun.reset();
    }
  }

  public function update(controls: Controls, deltaTime: Float) {
    if (!isActive) {
      return;
    }
    // ...
  }

  // ...
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We’ve changed Ship so that it implements Hitboxed, which requires us to supply a public Hitbox, as well as a hit method. We’ve also added in an isActive boolean so that the player can essentially be “turned off” during the game over screen.&lt;/p&gt;
&lt;p&gt;We also take in a sound upon construction that gets played when the player is hit, which is also where they become inactive.&lt;/p&gt;
&lt;p&gt;We take advantage of accessors to make sure that whenever the Ship’s x or y member variables are updated that the hitbox’s position is updated as well.&lt;/p&gt;
&lt;p&gt;Now let’s look at the small change we need to make to the CollisionHandler to account for our changes:&lt;/p&gt;
&lt;h4&gt;CollisionHandler.hx&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;package;

// ...

class CollisionHandler {
  // ...

  // convenience method for comparing a single entity vs many for collisions
  public static function handleSingleToGroupCollisions(single: Hitboxed, group: Array&amp;lt;Hitboxed&amp;gt;,
                                                       ?callback: Void-&amp;gt;Void = null): Void {
    for (g in group) {
      handleBiCollision(single, g, callback);
    }
  }
  // ...
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Nothing too fancy - just adding in a convenience method for checking collisions between one entity and several.&lt;/p&gt;
&lt;p&gt;Finally we need to make some adjustments to our UIManager:&lt;/p&gt;
&lt;h4&gt;UIManager.hx&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;package;

// ...

class UIManager {
  // ...
  private static inline var gameOverStr = &amp;quot;Game Over&amp;quot;;
  private static inline var restartStr = &amp;quot;Press Z to restart.&amp;quot;;

  // ...

  public function renderGameOver(g: Graphics): Void {
    g.font = font;
    g.fontSize = titleSize;
    
    var x = viewport.x + Math.round(viewport.width / 2);
    var gameOverW = g.font.width(titleSize, gameOverStr);
    g.drawString(gameOverStr, x - Math.round(gameOverW / 2), viewport.y + titleY);

    g.fontSize = instructionSize;
    var restartW = g.font.width(instructionSize, restartStr);
    g.drawString(restartStr, x - Math.round(restartW / 2), viewport.height - startY);
  }

  // ...
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Running the Application&lt;/h4&gt;
&lt;p&gt;Now when the player collides with an enemy they should blow up, the player should be displayed a “game over” message, and they should be able to restart the game by pressing the shoot button.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://jamiltron.com/images/khaShmup10.gif&quot; alt=&quot;KhaShmup10&quot;&gt;&lt;/p&gt;
&lt;p&gt;Make sure to look at my part 10 branch if you’re having problems: &lt;a href=&quot;https://github.com/jamiltron/KhaShmup/tree/part-10&quot;&gt;https://github.com/jamiltron/KhaShmup/tree/part-10&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;That kind of wraps up the game, hitting all of the goals we set out to do. In the next post we will be wrapping up, learning how to distribute a Kha game on the web, and discussing further enhancements that you can add to make this game more fun.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Kha Shmup Tutorial Part 9</title>
    <link href="https://jamiltron.com/2015/12/KhaShmup-Tutorial-Part-9/" />
    <updated>2015-12-30T00:00:00Z</updated>
    <id>https://jamiltron.com/2015/12/KhaShmup-Tutorial-Part-9/</id>
    <content type="html">&lt;p&gt;&lt;a href=&quot;http://jamiltron.com/2015/12/KhaShmup-Tutorial-Part-8/&quot;&gt;We finished adding score to our main game&lt;/a&gt;, so now let’s start wrapping up by adding a main menu.&lt;/p&gt;
&lt;p&gt;We are going to be changing our UIManager a little bit to accomodate these changes. This UIManager is pretty naive - we are assuming quite a bit in this tutorial making a few things easier for us:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;The screen will remain at 800x600 and we do not have to worry about additional resolutions or resizing.&lt;/li&gt;
&lt;li&gt;We only have a few elements we need to render, and thus hardcoding values in a couple places will be easier than spending the time to create a more versatile and generic solution.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Developing a robust UI can be a pretty lengthy topic on its own, you may want to use something like &lt;a href=&quot;https://github.com/luboslenco/zui&quot;&gt;zui&lt;/a&gt; or &lt;a href=&quot;http://haxeui.org&quot;&gt;haxeui&lt;/a&gt; (which currently doesn’t support Kha, but is supposed to be coming in version 2).&lt;/p&gt;
&lt;p&gt;Developing a more customized solution may be a fun project for your own game, but for now we’re just going to hammer out a solution that works for us for the time being:&lt;/p&gt;
&lt;h4&gt;UIManager.hx&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;package;

import kha.Font;
import kha.graphics2.Graphics;

class UIManager {
  private static inline var scoreX = 10;
  private static inline var scoreY = 10;
  private static inline var titleY = 60;
  private static inline var titleStr = &amp;quot;Kha Shmup&amp;quot;;
  private static inline var keysStr = &amp;quot;Arrow Keys to move, Z key to shoot.&amp;quot;;
  private static inline var keysY = 130;
  private static inline var startStr = &amp;quot;Press Z to start.&amp;quot;;
  private static inline var startY = 100;

  public var font: Font;
  public var scoreSize: Int;
  public var titleSize: Int;
  public var instructionSize: Int;
  public var viewport: Rectangle;

  private var score: Int;

  public function new(font: Font, scoreSize: Int, titleSize: Int, 
                      instructionSize: Int, viewport: Rectangle) {
    this.font = font;
    this.scoreSize = scoreSize;
    this.titleSize = titleSize;
    this.instructionSize = instructionSize;
    this.viewport = viewport;
  }

  public function scoreUp(): Void {
    score += 1;
  }

  public function renderScore(g: Graphics): Void {
    g.font = font;
    g.fontSize = scoreSize;
    g.drawString(&amp;quot;score: &amp;quot; + score, viewport.x + scoreX, viewport.y + scoreY);
  }

  public function renderMainMenu(g: Graphics): Void {
    g.font = font;
    g.fontSize = titleSize;
    var x = viewport.x + Math.round(viewport.width / 2);

    var titleW = g.font.width(titleSize, titleStr);
    g.drawString(titleStr, x - Math.round(titleW / 2), viewport.y + titleY);

    g.fontSize = instructionSize;
    var keysW = g.font.width(instructionSize, keysStr);
    g.drawString(keysStr, x - Math.round(keysW / 2), viewport.height - keysY);

    var startW = g.font.width(instructionSize, startStr);
    g.drawString(startStr, x - Math.round(startW / 2), viewport.height - startY);
  }

  public function reset(): Void {
    score = 0;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The biggest changes is instead of a render method, we have shifted to rendering the main menu, or rendering the score. Notice the g.font.width method - this method will give you the width of a string when rendered using the set font, as well as a provided font size. There is also a corresponding height method.&lt;/p&gt;
&lt;p&gt;We pretty much hardcore where the text is going to appear, with a little bit of flexibility to adjust it given a viewport. We are manually justifying these labels, but you can see how you may allow the user to define ui elements and provide a justification.&lt;/p&gt;
&lt;p&gt;The two methods are pretty straight forward - renderScore is the same as this object’s previous render method, and renderMainMenu draws three lines - the title, instructions, and what button to press to begin playing.&lt;/p&gt;
&lt;p&gt;We are now going to adjust our main game class to account for different states, and to render and update differently:&lt;/p&gt;
&lt;h4&gt;KhaShmup.hx&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;package;

// ...
import kha.graphics2.Graphics;
// ...

enum GameState {
  Initializing;
  MainMenu;
  Playing;
  Over;
}

class KhaShmup {
  // ...
  private var gameState: GameState;
  // make sure to delete the &#39;initialized&#39; var, as
  // gamestate will take care of what it was doing

  // ...
  private function loadingFinished(): Void {
    gameState = GameState.MainMenu;
    uiManager = new UIManager(Assets.fonts.kenpixel_mini_square, 20,    
      80, 30,new Rectangle(0, 0, screenWidth, screenHeight));
    // ...
  }

  private function reset() {
    controls.reset();
    ship.reset(Std.int(screenWidth / 2) - Std.int(ship.width / 2), 
      Std.int(screenHeight / 2) - Std.int(ship.height / 2));
    enemySpawner.reset();
    uiManager.rest();
    timer.reset();    
  }  

  private function renderMainMenu(g: Graphics): Void {
    uiManager.renderMainMenu(g);
  }

  private function renderPlaying(g: Graphics): Void {
    enemySpawner.render(g);
    ship.render(g);
    uiManager.renderScore(g);
  }

  public function render(framebuffer: Framebuffer): Void {
    if (Type.enumEq(gameState, GameState.Initializing)) {
      return;
    }

    var g = backbuffer.g2;

    // clear and draw to our backbuffer
    g.begin(bgColor);
    switch(gameState) {
    case GameState.MainMenu:
      renderMainMenu(g);
      updateMainMenu();
    case GameState.Playing:
      renderPlaying(g);
      updatePlaying();
    default:
      // no-op
    }
    g.end();

    // draw our backbuffer onto the active framebuffer
    framebuffer.g2.begin();
    Scaler.scale(backbuffer, framebuffer, System.screenRotation);
    framebuffer.g2.end();
  }

  private function updateMainMenu() {
    if (controls.shoot) {
      reset();
      gameState = GameState.Playing;
    }
  }

  private function updatePlaying() {
    timer.update();
    enemySpawner.update(timer.deltaTime);
    updateShip();
    handleCollisions();
  }
  // ...
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The first major difference is the addition of a GameState enum. This will track what part of the game we are in, and what update and render methods to be called. We’ve also removed the initialized boolean variable as gameState will now take care of flagging when we are initialized.&lt;/p&gt;
&lt;p&gt;We have adjusted our render method to check what state we are in and then call the added methods for rendering the main menu state, or the playing state (and we will add the game over state next time). We have also added a reset method - this is handy to set everything back to pretty close to how everything was upon initialization. We’re mostly using it to toggle the start button so the player doesn’t immediately shoot after moving through the menu, but this method will also be useful when we want to start the game over.&lt;/p&gt;
&lt;p&gt;We now need to add a few reset methods to various classes.&lt;/p&gt;
&lt;h4&gt;Controls.hx&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;//...

class Controls {
 // ...
  public function reset() {
    left = false;
    right = false;
    up = false;
    down = false;
    shoot = false;
  }
  // ...  
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Ship.hx&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;// ...
class Ship {
  // ...
  public function reset(x: Int, y: Int) {
    this.x = x;
    this.y = y;

    if (gun != null) {
      gun.reset();
    }
  }
  // ...
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Gun.hx&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;// ...
class Gun {
  // ...
  public function reset() {
    cooldownLeft = 0;
    for (bullet in bullets) {
      bullet.isActive = false;
    }
  }
  // ...
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;EnemySpawner.hx&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;// ...
class EnemySpawner {
  // ...
  public function reset() {
    currentTime = 0;
    spawnNextTime = generateRandomSpawnTime(spawnMinTime, spawnMaxTime);
    for (enemy in enemies) {
      enemy.isActive = false;
    }
  }
  // ...
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Running the Application&lt;/h4&gt;
&lt;p&gt;After our current changest you should see a main menu and you should be able to press Z to move to playing the game.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://jamiltron.com/images/khaShmup9.png&quot; alt=&quot;KhaShmup9&quot;&gt;&lt;/p&gt;
&lt;p&gt;As always, check out my part 9 branch if you’re having issues: &lt;a href=&quot;https://github.com/jamiltron/KhaShmup/tree/part-9&quot;&gt;https://github.com/jamiltron/KhaShmup/tree/part-9&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;We have one more state to add to the game before putting on the finishing touches, which is the promised game-over state.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Kha Shmup Tutorial Part 8</title>
    <link href="https://jamiltron.com/2015/12/KhaShmup-Tutorial-Part-8/" />
    <updated>2015-12-28T00:00:00Z</updated>
    <id>https://jamiltron.com/2015/12/KhaShmup-Tutorial-Part-8/</id>
    <content type="html">&lt;p&gt;&lt;a href=&quot;http://jamiltron.com/2015/12/KhaShmup-Tutorial-Part-7/&quot;&gt;A week or so ago&lt;/a&gt; we finished up with some death animation when we shot our enemies, so in this tutorial we are going to be tracking how many enemies we’ve destroyed.&lt;/p&gt;
&lt;p&gt;We will start by defining a UIManager to help us keep track of the various UI we’ll be doing in this game, which for this tutorial will be just displaying a score label and amount.&lt;/p&gt;
&lt;h4&gt;UIManager.hx&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;package;

import kha.Font;
import kha.graphics2.Graphics;

class UIManager {

  public var font: Font;
  public var x: Int;
  public var y: Int;
  public var fontSize: Int;

  private var score: Int;

  public function new(x: Int, y: Int, font: Font, fontSize: Int) {
    this.x = x;
    this.y = y;
    this.font = font;
    this.fontSize = fontSize;
  }

  public function scoreUp(): Void {
    score += 1;
  }

  public function render(g: Graphics): Void {
    g.font = font;
    g.fontSize = fontSize;
    g.drawString(&amp;quot;score: &amp;quot; + score, x, y);
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This class receives a font upon creation, as well as a position for where to display the label, and a font size for how large we want the display.&lt;/p&gt;
&lt;p&gt;This has a render method that sets the font used by our graphics2 instance, the fontSize, and then proceeds to draw the label and the core at our defined position.&lt;/p&gt;
&lt;p&gt;There is also a function called scoreUp, which just increments the score. We will see how we’ll be using this as a callback to our collision method.&lt;/p&gt;
&lt;p&gt;Let’s change CollisionHandler.hx a bit:&lt;/p&gt;
&lt;h4&gt;CollisionHandler.hx&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;package;

class CollisionHandler {

  // checks if 2 entities collide, and if so &#39;hits&#39; them both, and calls a callback
  public static function handleBiCollision(h1: Hitboxed,     
                                           h2: Hitboxed,     
                                           ?callback: Void-&amp;gt;Void = null): Void {
    if (testCollision(h1, h2)) {
      h1.hit();
      h2.hit();
      if (callback != null) {
        callback();
      }
    }
  }

  // compare every entity from leftGroup with everyone in rightGroup
  public static function handleGroupCollisions(leftGroup: Array&amp;lt;Hitboxed&amp;gt;,     
                                               rightGroup: Array&amp;lt;Hitboxed&amp;gt;,     
                                               ?callback: Void-&amp;gt;Void = null): Void {
    for (left in leftGroup) {
      for (right in rightGroup) {
        handleBiCollision(left, right, callback);
      }
    }
  }

  public static function testCollision(h1: Hitboxed, h2: Hitboxed): Bool {
    return h1.hitbox.overlaps(h2.hitbox);
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The big change here is that we are providing an optional callback method to our “handle” methods. When we have a collision we check if this callback is null, and if it is not - we call it back. There is an obvious limitation to the fact that we can only set one callback per method, and if you want to supply more methods in your own game you obviously can pass a collection or methods.&lt;/p&gt;
&lt;p&gt;Let’s wire this all up in KhaShmup.hx:&lt;/p&gt;
&lt;h4&gt;KhaShmup.hx&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;package;

// ...

class KhaSmup {

  // ...
  private var uiManager: UIManager;
  // ...

  private function loadingFinished(): Void {
    // ...
    uiManager = new UIManager(10, 10,
      Assets.fonts.kenpixel_mini_square, 20);
  }

  private function handleCollisions() {
    var bullets: Array&amp;lt;Hitboxed&amp;gt; = cast ship.gun.getActiveBullets();
    var enemies: Array&amp;lt;Hitboxed&amp;gt; = cast enemySpawner.getActiveEnemies();

    CollisionHandler.handleGroupCollisions(bullets, enemies, uiManager.scoreUp);
  }

  // ...
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This should be clear - we just instantiate our ui manager and we pass the uiManager’s scoreUp method as the callback for the collisions between bullets and enemies.&lt;/p&gt;
&lt;p&gt;I am using the KenPixel Mini Square font from Kenny.nl’s &lt;a href=&quot;http://kenney.nl/assets/kenney-fonts&quot;&gt;Font Pack&lt;/a&gt;. You can use your own font if you wish, just make sure you change the referenced assets when instantiating the uiManager.&lt;/p&gt;
&lt;h4&gt;Running the Application&lt;/h4&gt;
&lt;p&gt;Now run the game and you should see score ticking up when you shoot enemies:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://jamiltron.com/images/khaShmup8.gif&quot; alt=&quot;KhaShmup8&quot;&gt;&lt;/p&gt;
&lt;p&gt;Check my part 8 branch if you don’t see this: &lt;a href=&quot;https://github.com/jamiltron/KhaShmup/tree/part-8&quot;&gt;https://github.com/jamiltron/KhaShmup/tree/part-8&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;We’re getting close to finishing our game. &lt;a href=&quot;http://jamiltron.com/2015/12/KhaShmup-Tutorial-Part-9/&quot;&gt;Next time&lt;/a&gt; let’s add a main menu.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Kha Shmup Tutorial Part 7</title>
    <link href="https://jamiltron.com/2015/12/KhaShmup-Tutorial-Part-7/" />
    <updated>2015-12-19T00:00:00Z</updated>
    <id>https://jamiltron.com/2015/12/KhaShmup-Tutorial-Part-7/</id>
    <content type="html">&lt;p&gt;&lt;a href=&quot;http://jamiltron.com/2015/12/KhaShmup-Tutorial-Part-6/&quot;&gt;Yesterday&lt;/a&gt; we coded up some collision detection so that the player could shoot enemies. Today we will be adding very basic animations to make that a little more satisfying.&lt;/p&gt;
&lt;h4&gt;Animation.hx&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;package;

import kha.Image;

class Animation {
  private var currentTime: Float;
  private var index: Int;

  public var frames: Array&amp;lt;Image&amp;gt;;
  public var frameDuration: Float;
  public var isDone(get, null): Bool;
  public var playState: PlayState;

  private function get_isDone(): Bool {
    return (Type.enumEq(playState, PlayState.Once) &amp;amp;&amp;amp;
            index &amp;gt;= frames.length);
  }

  public function new(frameDuration: Float, frames: Array&amp;lt;Image&amp;gt;, playState: PlayState) {
    this.playState = playState;
    this.frameDuration = frameDuration;
    this.frames = frames;
    index = 0;
  }

  public function reset(): Void {
    index = 0;
    currentTime = 0;
  }

  public function update(deltaTime: Float) {
    currentTime += deltaTime;

    if (currentTime &amp;gt;= frameDuration) {
      currentTime -= frameDuration;
      index += 1;
    }

    if (index &amp;gt;= frames.length) {
      if (Type.enumEq(playState, PlayState.Loop)) {
        index = 0;
      } else {
        index = frames.length;
      }
    }
  }

  public function getCurrentFrame(): Image {
    return frames[index];
  }

  public function getFrame(i: Int): Image {
    return frames[i];
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is a very basic animation system that allows us to supply a frameDuration - which is the amount of time each frame takes, a series of images to represent each frame, and a state dictating whether or not we want to loop our animation or only play it once.&lt;/p&gt;
&lt;p&gt;Everytime we call update we pass in the deltaTime. This gets added to the currentTime, and if its longer than the frameDuration we reset currentTime plus the difference, and then we increment the index used to retrieve the current frame. We also have some logic for whether or not we should loop the animation, and if it is done playing or not.&lt;/p&gt;
&lt;p&gt;Now this implementation has a few issues. For one - we don’t have a way to really say where we want to orient each frame. This means if we have different sizes of images for the animation they snap to the top-left of the entity’s origin by default. We also don’t have a way to differentiate frame lengths.&lt;/p&gt;
&lt;p&gt;All of this can be added in, but we do not need them.&lt;/p&gt;
&lt;p&gt;Here is the PlayState that describes if we are looping an animation or not.&lt;/p&gt;
&lt;h4&gt;PlayState.hx&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;package;

enum PlayState {
  Loop;
  Once;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The reason I put this in its own file is that we reference it from other classes outside of Animation. I like to have a dedicated file for any class or enum that gets referenced by multiple classes, no matter how small, because it makes it easier for me to remember where to find definitions.&lt;/p&gt;
&lt;p&gt;Now we have to update our Enemy to get the Animations to play:&lt;/p&gt;
&lt;h4&gt;Enemy.hx&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;package;

import kha.Image;
import kha.Sound;
import kha.audio1.Audio;
import kha.graphics2.Graphics;

enum EnemyState {
  Active;
  InActive;
  Exploding;
}

class Enemy implements Hitboxed {
  private var activeAnimation: Animation;
  private var explodeAnimation: Animation;
  private var explosionSound: Sound;
  private var enemyState: EnemyState;

  public var animation: Animation;
  public var hitbox: Hitbox;
  public var isActive(get, set): Bool;
  public var x: Int;
  public var y: Int;
  public var width(get, null): Int;
  public var height(get, null): Int;
  public var speed = 200.0;

  private function get_isActive(): Bool {
    return !Type.enumEq(enemyState, EnemyState.InActive);
  }

  private function set_isActive(value: Bool): Bool {
    if (value) {
      enemyState = EnemyState.Active;
    } else {
      enemyState = EnemyState.InActive;
    }

    return value;
  }

  private function get_width(): Int {
    return activeAnimation.getFrame(0).width;
  }

  private function get_height(): Int {
    return activeAnimation.getFrame(0).height;
  }

  public function new(x: Int, y: Int, activeAnimation: Animation, 
                      explodeAnimation: Animation, explosionSound: Sound) {
    this.activeAnimation = activeAnimation;
    this.explodeAnimation = explodeAnimation;
    this.explosionSound = explosionSound;
    hitbox = new Hitbox(x, y, 2, 0, activeAnimation.getFrame(0).width - 4, 
                        Std.int(activeAnimation.getFrame(0).height / 2));
    activate(x, y);
  }

  public function activate(x: Int, y: Int): Void {
    this.x = x;
    this.y = y;
    hitbox.updatePosition(x, y);
    enemyState = EnemyState.Active;
    setAnimation(activeAnimation);
    hitbox.enabled = true;
  }

  public function hit(): Void {
    Audio.play(explosionSound, true);
    enemyState = EnemyState.Exploding;
    setAnimation(explodeAnimation);
    hitbox.enabled = false;
  }

  public function render(g: Graphics): Void {
    if (!isActive) {
      return;
    }

    if (!animation.isDone) {
      g.drawImage(animation.getCurrentFrame(), x, y);
    }
  }

  public function update(deltaTime: Float): Void {
    if (!isActive) {
      return;
    }

    if (Type.enumEq(enemyState, EnemyState.Active)) {
      y += Math.round(speed * deltaTime);
      hitbox.updatePosition(x, y);
    }
    animation.update(deltaTime);

    if (Type.enumEq(enemyState, EnemyState.Exploding) &amp;amp;&amp;amp;animation.isDone) {
      isActive = false;
    }
  }

  private function setAnimation(newAnimation: Animation) {
    animation = newAnimation;
    animation.reset();
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;So a few things have changed since we last saw this file. There’s no more image field - now there are two animations. We also no longer track isActive as explicit flag - now its based on whether or not the EnemyState enum is set to Active or not.&lt;/p&gt;
&lt;p&gt;When updating an enemy we also update the animation, and if the enemy is exploding we make sure to set it to be inActive so the Enemy can be pooled once the animation is through.&lt;/p&gt;
&lt;p&gt;When we hit the enemy we still play a sound, swap state to exploding, but we also set the hitbox’s enabled field to false, which prevents us from colliding with the enemy while they are exploding. This requires an update to Hitbox.hx&lt;/p&gt;
&lt;h4&gt;Hitbox.hx&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;package;

class Hitbox {
  public var enabled: Bool;
  public var rectangle(default, null): Rectangle;
  public var parentX: Int;
  public var parentY: Int;
  public var offsetX: Int;
  public var offsetY: Int;
  public var width: Int;
  public var height: Int;

  public function new(parentX: Int, parentY: Int, offsetX: Int, offsetY: Int, width: Int, height: Int) {
    this.parentX = parentX;
    this.parentY = parentY;
    this.offsetX = offsetX;
    this.offsetY = offsetY;
    this.width = width;
    this.height = height;
    enabled = true;

    rectangle = new Rectangle(parentX + offsetX, parentY + offsetY, width, height);
  }

  public function overlaps(other: Hitbox): Bool {
    if (!enabled || !other.enabled) {
      return false;
    }

    return rectangle.overlaps(other.rectangle);
  }

  public function updatePosition(parentX: Int, parentY: Int): Void {
    this.parentX = parentX;
    this.parentY = parentX;
    rectangle.x = parentX + offsetX;
    rectangle.y = parentY + offsetY;
    rectangle.width = width;
    rectangle.height = height;
  }

}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Whenever a hitbox is not enabled OR the other hitbox, we do not count the collision. We have one more big change, which is in the EnemySpawner:&lt;/p&gt;
&lt;h4&gt;EnemySpawner.hx&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;package;

import kha.Assets;
import kha.Image;
import kha.Sound;
import kha.graphics2.Graphics;

class EnemySpawner {
  private var enemyImage: Image;
  private var activeAnimation: Animation;
  private var explodeAnimation: Animation;
  private var explodeSound: Sound;
  private var minSpawnX: Int;
  private var maxSpawnX: Int;
  private var maxPositionY: Int;
  private var spawnMinTime: Float;
  private var spawnMaxTime: Float;
  private var spawnNextTime: Float;
  private var currentTime: Float;
  private var enemies: Array&amp;lt;Enemy&amp;gt;;

  public function new(spawnMinTime: Float, spawnMaxTime: Float, 
                      ?minSpawnX: Int = 0, maxSpawnX: Int = 0, maxPositionY: Int = 600) {
    setAssets();
    this.spawnMinTime = spawnMinTime;
    this.spawnMaxTime = spawnMaxTime;
    this.minSpawnX = minSpawnX;
    this.maxSpawnX = maxSpawnX;
    this.maxPositionY = maxPositionY;
    currentTime = 0;
    enemies = new Array&amp;lt;Enemy&amp;gt;();
    spawnNextTime = generateRandomSpawnTime(spawnMinTime, spawnMaxTime);
  }

  private function generateRandomSpawnTime(spawnMinTime: Float, spawnMaxTime: Float): Float {
    return spawnMinTime + Math.random() * (spawnMaxTime - spawnMinTime);
  }

  private function generateRandomX(minSpawnX, maxSpawnX): Int {
    return Std.random(maxSpawnX - enemyImage.width) + minSpawnX;
  }

  private function setAssets() {
    enemyImage = Assets.images.enemyShip;
    var explodeFrames = new Array&amp;lt;Image&amp;gt;();
    explodeFrames.push(Assets.images.smokeOrange0);
    explodeFrames.push(Assets.images.smokeOrange1);
    explodeFrames.push(Assets.images.smokeOrange2);
    explodeFrames.push(Assets.images.smokeOrange3);
    activeAnimation = new Animation(1, [enemyImage], PlayState.Loop);
    explodeAnimation = new Animation(0.1, explodeFrames, PlayState.Once);
    explodeSound = Assets.sounds.enemyExplosion;
  }

  private function spawn(x: Int, y: Int): Void {
      for (i in 0...enemies.length) {
        if (!enemies[i].isActive) {
          enemies[i].activate(x, y);
          return;
        }
      }

    enemies.push(new Enemy(x, y, activeAnimation, explodeAnimation, explodeSound));
  }

  public function getActiveEnemies(): Array&amp;lt;Enemy&amp;gt; {
    var actives = new Array&amp;lt;Enemy&amp;gt;();

    for (i in 0...enemies.length) {
      if (enemies[i].isActive) {
        actives.push(enemies[i]);
      }
    }
    return actives;
  }

  public function update(deltaTime: Float) {
    currentTime += deltaTime;

    if (currentTime &amp;gt;= spawnNextTime) {
      currentTime = 0;
      spawnNextTime = generateRandomSpawnTime(spawnMinTime, spawnMaxTime);
      spawn(generateRandomX(minSpawnX, maxSpawnX), -enemyImage.height);
    }

    for (i in 0...enemies.length) {
      var enemy = enemies[i];
      enemy.update(deltaTime);

      if (enemy.isActive &amp;amp;&amp;amp; enemy.y &amp;gt; maxPositionY) {
        enemy.isActive = false;
      }
    }
  }

  public function render(g: Graphics) {
    for (i in 0...enemies.length) {
      enemies[i].render(g);
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The major changes lie in the creation of the animation - we call a method to set our assets, and from there we load up the images and construct the animation objects.&lt;/p&gt;
&lt;p&gt;I have added four explosion sprites to the Assets folder. These are all one image, just scaled down. We could have just progressively scaled this image down instead of setting up animations like this - but I wanted to elaborate how we would draw keyframes in a game.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://jamiltron.com/images/smokeOrange0.png&quot; alt=&quot;Explosion 0&quot;&gt; &lt;img src=&quot;https://jamiltron.com/images/smokeOrange1.png&quot; alt=&quot;Explosion 1&quot;&gt; &lt;img src=&quot;https://jamiltron.com/images/smokeOrange2.png&quot; alt=&quot;Explosion 2&quot;&gt; &lt;img src=&quot;https://jamiltron.com/images/smokeOrange3.png&quot; alt=&quot;Explosion 3&quot;&gt;&lt;/p&gt;
&lt;p&gt;Also remember the whole lack of orientation regarding frames I mentioned above? That means each image, even though the sprite gets smaller and smaller had to be the same size and the image had to pasted in the middle. A good “next step” task would be to implement a Frame data type that could wrap each image and specify an offset from the parent’s position.&lt;/p&gt;
&lt;h4&gt;Running the Application&lt;/h4&gt;
&lt;p&gt;You should now see the enemies disappearing into a cloud of smoke when you shoot them&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://jamiltron.com/images/khaShmup7.gif&quot; alt=&quot;Explosion&quot;&gt;&lt;/p&gt;
&lt;p&gt;Check my part 7 branch if this does not work for you: &lt;a href=&quot;https://github.com/jamiltron/KhaShmup/tree/part-7&quot;&gt;https://github.com/jamiltron/KhaShmup/tree/part-7&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;In &lt;a href=&quot;http://jamiltron.com/2015/12/KhaShmup-Tutorial-Part-8/&quot;&gt;part 8&lt;/a&gt; we will start displaying score for the player, counting the number of enemies defeated.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Kha Shmup Tutorial Part 6</title>
    <link href="https://jamiltron.com/2015/12/KhaShmup-Tutorial-Part-6/" />
    <updated>2015-12-18T00:00:00Z</updated>
    <id>https://jamiltron.com/2015/12/KhaShmup-Tutorial-Part-6/</id>
    <content type="html">&lt;p&gt;In the &lt;a href=&quot;http://jamiltron.com/2015/12/KhaShmup-Tutorial-Part-5/&quot;&gt;last blog post&lt;/a&gt; we started spawning enemies randomly on the screen, this time we’re going to be adding some collision detection so the player can shoot. We’ll start how we always do - basic, and the proceed to get more advanced. Since we will be developing a few different cases of collision, let’s add an interface for anything that has a hitbox - which we will use as our bounding box determining where game entities collide.&lt;/p&gt;
&lt;h4&gt;Hitboxed.hx&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;package;

interface Hitboxed {
  public var hitbox: Hitbox;
  public function hit(): Void;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Pretty simple - we provide access to a variable hitbox, and we provide a method to call when the hitbox is hit. Let’s look at the implementation of the referenced hitbox:&lt;/p&gt;
&lt;h4&gt;Hitbox.hx&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;package;

class Hitbox {
  public var rectangle(default, null): Rectangle;
  public var parentX: Int;
  public var parentY: Int;
  public var offsetX: Int;
  public var offsetY: Int;
  public var width: Int;
  public var height: Int;

  public function new(parentX: Int, parentY: Int, offsetX: Int, offsetY: Int, width: Int, height: Int) {
    this.parentX = parentX;
    this.parentY = parentY;
    this.offsetX = offsetX;
    this.offsetY = offsetY;
    this.width = width;
    this.height = height;

    rectangle = new Rectangle(parentX + offsetX, parentY + offsetY, width, height);
  }

  public function overlaps(other: Hitbox): Bool {
    return rectangle.overlaps(other.rectangle);
  }

  public function updatePosition(parentX: Int, parentY: Int): Void {
    this.parentX = parentX;
    this.parentY = parentX;
    rectangle.x = parentX + offsetX;
    rectangle.y = parentY + offsetY;
    rectangle.width = width;
    rectangle.height = height;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I’ll explain this class more in a bit, but let’s first glance at Rectangle.hx&lt;/p&gt;
&lt;h4&gt;Rectangle.hx&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;package;

class Rectangle {
  public var x: Int;
  public var y: Int;
  public var width: Int;
  public var height: Int;

  public function new(x: Int, y: Int, width: Int, height: Int) {
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
  }

  public function overlaps(other: Rectangle): Bool {
    return x &amp;lt;= other.x + other.width &amp;amp;&amp;amp; 
           x + width &amp;gt;= other.x &amp;amp;&amp;amp; 
           y &amp;lt;= other.y + other.height &amp;amp;&amp;amp; 
           y + height &amp;gt;= other.y;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Rectangle is pretty much what it sounds like - it has a 2d position, and a width and a height. It also provides a method for testing if another rectangle overlaps it. If one part of this rectangle is even touching another rectangle this method will return true.&lt;/p&gt;
&lt;p&gt;This method of collision detection is known as “Axis Aligned Bounding Box” - which is a fancy term for saying “check if two boxes, aligned by axis, are overlapping.” The “axis-aligned” part is important - you can’t test for hitboxes that have been rotated differently - there are algorithms for that, but this one is geared for boxes that essentially have the same degree of rotation as each other.&lt;/p&gt;
&lt;p&gt;Back to Hitbox.hx - you may wonder why I chose to use a seperate data structure instead of just using a rectangle directly. The reason why I chose this is mostly due to the different between the parent position and the offset. Often in games you don’t neccessarily have a character’s hitbox completely surround their sprite, and this is especially true in shmup games. You’ll sometimes have the hitbox represent some smaller internal structure - maybe just the cockpit of the ship, or sometimes you may just want to have a little leeway space among the sprite so they can get very close to others without triggering collision.&lt;/p&gt;
&lt;p&gt;The updatePosition method exists so that the parent object can pass its own updated position to the hitbox, and then the hitbox itself and its internal rectangle gets adjusted accourdingly. You can ofcourse get fancy and have custom setter properties for the hitbox’s position that automatically updates the rectangle, but I feel this simple solution works for our case.&lt;/p&gt;
&lt;p&gt;Hopefully this all makes sense but if it doesn’t or you have a better, simpler way of handling this please let me know. Let’s go ahead and implement this interface in Bullet.hx and Enemy.hx:&lt;/p&gt;
&lt;h4&gt;Bullet.hx&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;// ...

class Bullet implements Hitboxed {
  // ...

  public var hitbox: Hitbox;

  public function new(x: Int, y: Int, image: Image) {
    this.image = image;
    hitbox = new Hitbox(x, y, 0, 0, image.width, image.height);
    activate(x, y);
  }
    
  public function hit(): Void {
    isActive = false;
  }

  public function update(deltaTime: Float): Void {
    if (!isActive) {
      return;
    }

    y -= Math.round(speed * deltaTime);
    hitbox.updatePosition(x, y);
  }

  // ...
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Enemy.hx&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;package;

import kha.Assets;
import kha.Image;
import kha.audio1.Audio;
import kha.graphics2.Graphics;

class Enemy implements Hitboxed {
  // ...
  public var hitbox: Hitbox;

  // ...
  public function new(x: Int, y: Int, image: Image) {
    this.image = image;
    hitbox = new Hitbox(x, y, 2, 0, image.width - 4, Std.int(image.height / 2));
    activate(x, y);
  }

  public function hit(): Void {
    Audio.play(Assets.sounds.enemyExplosion, false);
    isActive = false;
  }

  public function update(deltaTime: Float): Void {
    if (!isActive) {
      return;
    }

    y += Math.round(speed * deltaTime);
    hitbox.updatePosition(x, y);
  }
    
  // ...
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now I want to develop a convenience handler for performing these collision checks.&lt;/p&gt;
&lt;h4&gt;CollisionHandler.hx&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;package;

class CollisionHandler {
  // checks if 2 entities collide, and if so &#39;hits&#39; them both
  public static function handleBiCollision(h1: Hitboxed, h2: Hitboxed): Void {
    if (testCollision(h1, h2)) {
      h1.hit();
      h2.hit();
    }
  }

  // compare every entity from leftGroup with every entity in rightGroup
  public static function handleGroupCollisions(leftGroup: Array&amp;lt;Hitboxed&amp;gt;, rightGroup: Array&amp;lt;Hitboxed&amp;gt;): Void {
    for (left in leftGroup) {
      for (right in rightGroup) {
        handleBiCollision(left, right);
      }
    }
  }

  public static function testCollision(h1: Hitboxed, h2: Hitboxed): Bool {
    return h1.hitbox.overlaps(h2.hitbox);
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is a pretty basic class that (currently) requires no state. It provides a few static convenience methods for iterating over groups of Hitboxed classes, tests for collision between two entities, and hits both if they do collide. Let’s tie this into KhaShmup.hx, abbreviate for space:&lt;/p&gt;
&lt;h4&gt;KhaShmup.hx&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;// ...

class KhaShmup {
  // ...

  private function update() {
    timer.update();
    enemySpawner.update(timer.deltaTime);
    updateShip();
    handleCollisions();
  }

  private function handleCollisions() {
    var bullets: Array&amp;lt;Hitboxed&amp;gt; = cast ship.gun.getActiveBullets();
    var enemies: Array&amp;lt;Hitboxed&amp;gt; = cast enemySpawner.getActiveEnemies();

    CollisionHandler.handleGroupCollisions(bullets, enemies);
  }    

  // ...
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The case call on both of these methods are a little weird. This call basically tells the typechecker that we are casting from the provided types (which will be Array and Array) to the declared type of Array. This is because type parameters in Array are _invariant_. The concept of variance in computer science is somewhat technical but interesting if you are into type theory, so you can read more about it [here](https://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)) and [here is a link](http://haxe.org/manual/type-system-variance.html) to it being addressed in the Haxe documentation.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Note:&lt;/em&gt; I originally had gun be private in Ship.hx, but I decided to make it public just to make calling this method on it easier. If I really wanted to keep gun private, which isn’t neccessarily a bad idea, I would just provide a similar getActiveBullets method in Ship that called down to Gun’s method.&lt;/p&gt;
&lt;p&gt;Speaking of these methods, let’s define them:&lt;/p&gt;
&lt;h4&gt;Gun.hx&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;// ...

class Gun {
  // ...
  public function getActiveBullets(): Array&amp;lt;Bullet&amp;gt; {
    var actives = new Array&amp;lt;Bullet&amp;gt;();

    for (i in 0...bullets.length) {
      if (bullets[i].isActive) {
        actives.push(bullets[i]);
      }
    }
    return actives;
  }
  // ...  
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;EnemySpawner.hx&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;// ...

class EnemySpawner {
  // ...
  public function getActiveEnemies(): Array&amp;lt;Enemy&amp;gt; {
    var actives = new Array&amp;lt;Enemy&amp;gt;();

    for (i in 0...enemies.length) {
      if (enemies[i].isActive) {
        actives.push(enemies[i]);
      }
    }
    return actives;
  }
  // ...  
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Running the Application&lt;/h4&gt;
&lt;p&gt;Running now should have similar results as before - you can move, enemies spawn randomly, but now when you shoot an enemy it should disappear and play an explosion sound.&lt;/p&gt;
&lt;p&gt;Check my part-6 branch if this does not work for you: &lt;a href=&quot;https://github.com/jamiltron/KhaShmup/tree/part-6&quot;&gt;https://github.com/jamiltron/KhaShmup/tree/part-6&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;In &lt;a href=&quot;http://jamiltron.com/2015/12/KhaShmup-Tutorial-Part-7&quot;&gt;part 7&lt;/a&gt; we will continue on this thread, adding in basic animations for the enemy ships’ destruction.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Kha Shmup Tutorial Part 5</title>
    <link href="https://jamiltron.com/2015/12/KhaShmup-Tutorial-Part-5/" />
    <updated>2015-12-16T00:00:00Z</updated>
    <id>https://jamiltron.com/2015/12/KhaShmup-Tutorial-Part-5/</id>
    <content type="html">&lt;p&gt;&lt;a href=&quot;http://jamiltron.com/2015/12/KhaShmup-Tutorial-Part-4/&quot;&gt;We can now move and shoot&lt;/a&gt; so let’s lay the foundation of providing something to shoot at.&lt;/p&gt;
&lt;h4&gt;Enemy.hx&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;package;

import kha.Image;
import kha.graphics2.Graphics;

class Enemy {
  private var image: Image;

  public var x: Int;
  public var y: Int;
  public var width(get, null): Int;
  public var height(get, null): Int;
  public var speed = 200.0;
  public var isActive = true;

  private function get_width(): Int {
    return image.width;
  }

  private function get_height(): Int {
    return image.height;
  }

  public function new(x: Int, y: Int, image: Image) {
    this.image = image;
    activate(x, y);
  }

  public function activate(x: Int, y: Int): Void {
    this.x = x;
    this.y = y;
    isActive = true;
  }

  public function render(g: Graphics): Void {
    if (!isActive) {
      return;
    }
    g.drawImage(image, x, y);
  }

  public function update(deltaTime: Float): Void {
    if (!isActive) {
      return;
    }

    y += Math.round(speed * deltaTime);
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This enemy looks pretty similar - they are pretty much the same as bullets, and they share a lot of resemblance to the Ship. This is ok for our tutorial because we aren’t going to get too complicated, but this is probably the point where you will want to DRY up the code. DRY stands for “Don’t Repeat Yourself”, and means we want to stop duplicating the share it between the classes - you could do this with an base class they inherit from, or a component that these classes hold. I personally would use something like the &lt;a href=&quot;http://www.ashframework.org/&quot;&gt;Ash Entity-Component-System&lt;/a&gt; from the start, but that’s somewhat outside of the scope of this tutorial and possibly a topic for a later date.&lt;/p&gt;
&lt;p&gt;As I said above this tutorial is pretty simple, and a little duplication won’t kill us, so I am leaving it as is, but this is one of the many “naive” parts of this tutorial I spoke about earlier that you’d want to clean up for a more complex game.&lt;/p&gt;
&lt;p&gt;Since we have an Enemy, let’s get a way to get them on screen:&lt;/p&gt;
&lt;h4&gt;EnemySpawner.hx&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;package;

import kha.Image;
import kha.graphics2.Graphics;

class EnemySpawner {
  private var minSpawnX: Int;
  private var maxSpawnX: Int;
  private var maxPositionY: Int;
  private var enemyImage: Image;
  private var spawnMinTime: Float;
  private var spawnMaxTime: Float;
  private var spawnNextTime: Float;
  private var currentTime: Float;
  private var enemies: Array&amp;lt;Enemy&amp;gt;;

  public function new(enemyImage: Image, spawnMinTime: Float, spawnMaxTime: Float, 
                      ?minSpawnX: Int = 0, maxSpawnX: Int = 0, maxPositionY: Int = 600) {
    this.enemyImage = enemyImage;
    this.spawnMinTime = spawnMinTime;
    this.spawnMaxTime = spawnMaxTime;
    this.minSpawnX = minSpawnX;
    this.maxSpawnX = maxSpawnX;
    this.maxPositionY = maxPositionY;
    currentTime = 0;
    enemies = new Array&amp;lt;Enemy&amp;gt;();
    spawnNextTime = generateRandomSpawnTime(spawnMinTime, spawnMaxTime);
  }

  private function generateRandomSpawnTime(minTime: Float, maxTime: Float): Float {
    return minTime + Math.random() * (maxTime - minTime);
  }

  private function generateRandomX(minSpawnX, maxSpawnX): Int {
    return Std.random(maxSpawnX - minSpawnX) + minSpawnX;
  }

  private function spawn(x: Int, y: Int): Void {
      for (i in 0...enemies.length) {
        if (!enemies[i].isActive) {
          enemies[i].activate(x, y);
          return;
        }
      }

    enemies.push(new Enemy(x, y, enemyImage));
  }

  public function update(deltaTime: Float) {
    currentTime += deltaTime;

    if (currentTime &amp;gt;= spawnNextTime) {
      currentTime = 0;
      spawnNextTime = generateRandomSpawnTime(spawnMinTime, spawnMaxTime);
      spawn(generateRandomX(minSpawnX, maxSpawnX - enemyImage.width), -enemyImage.height);
    }

    for (i in 0...enemies.length) {
      var enemy = enemies[i];
      enemy.update(deltaTime);

      if (enemy.isActive &amp;amp;&amp;amp; enemy.y &amp;gt; maxPositionY) {
        enemy.isActive = false;
      }
    }
  }

  public function render(g: Graphics) {
    for (i in 0...enemies.length) {
      enemies[i].render(g);
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Much like the Gun of last lesson - this is an object that basically holds and generates enemies, as well as performing some object pooling and positioning logic.&lt;/p&gt;
&lt;p&gt;We use two floats to determine when to spawn enemies - the minimum time we wait to spawn, and the maximum. We randomly select a float between these two, and then once the currentTime is equal to or greater than that, we spawn an enemy just above the screen, and between minSpawnX and maxSpawnX. You may notice two different random methods - Std.random(int) and Math.random(): Std.random(val) will return an integer between 0 and val whereas Math.random returns a float between 0 and 1.0. Because we are generating pure ints in the random position, and floats in the time we use these two different methods, but if you chose to only allow enemies to spawn on whole seconds you could use Std.random in both places.&lt;/p&gt;
&lt;p&gt;This spawn logic is pretty simple - as a further exercise you may want to add some additional logic - like maybe you still want to spawn an enemy on a random time, but the time that you generate must always on a quarter second interval.&lt;/p&gt;
&lt;p&gt;One more note on code quality - the entire timing logic is a good candidate for being broken out into its own class. You generally want classes to do as little as possible. Again this is an issue of “works for us as is”, but I just thought I should bring it up.&lt;/p&gt;
&lt;p&gt;Now let’s tie this spawner back into KhaShmup.hx. I’ll abbreviate this class as its getting somewht big. Make sure to check the &lt;a href=&quot;https://github.com/jamiltron/KhaShmup/tree/part-5&quot;&gt;part-5 branch&lt;/a&gt; if you have any confusion.&lt;/p&gt;
&lt;h4&gt;KhaShmup.hx&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;...

class KhaShmup {

  ...
  private var enemySpawner: EnemySpawner;

  public function loadingFinished(): Void {
    ...
    enemySpawner = new EnemySpawner(Assets.images.enemyShip, 1.0, 3.0, 0, screenWidth, screenHeight);
    ...
  }
    
  public function render(framebuffer: Framebuffer): Void {
    ...
    g.begin(bgColor);
    enemySpawner.render(g);
    ship.render(g);
    g.end();
    ...
  }

  public function update() {
    timer.update();
    enemySpawner.update(timer.deltaTime);
    updateShip();
  }

  ...
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Running the Application&lt;/h4&gt;
&lt;p&gt;You should now see enemies spawning from the top of the screen and move to the bottom in random intervals. We can’t shoot them just yet, but we’ll be getting to that in part 6.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://jamiltron.com/images/khaShmup5.gif&quot; alt=&quot;Lasers&quot;&gt;&lt;/p&gt;
&lt;p&gt;If you don’t see this, check out my part-5 branch:&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/jamiltron/KhaShmup/tree/part-5&quot;&gt;https://github.com/jamiltron/KhaShmup/tree/part-5&lt;/a&gt;&lt;/p&gt;
&lt;h4&gt;In Summary&lt;/h4&gt;
&lt;p&gt;We got enemies on screen, and the next logical step is to allow them to be shot. We’ll be going over some basic collision detection &lt;a href=&quot;http://jamiltron.com/2015/12/KhaShmup-Tutorial-Part-6/&quot;&gt;next time&lt;/a&gt;.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Kha Shmup Tutorial Part 4</title>
    <link href="https://jamiltron.com/2015/12/KhaShmup-Tutorial-Part-4/" />
    <updated>2015-12-15T00:00:00Z</updated>
    <id>https://jamiltron.com/2015/12/KhaShmup-Tutorial-Part-4/</id>
    <content type="html">&lt;p&gt;&lt;a href=&quot;http://jamiltron.com/2015/12/KhaShmup-Tutorial-Part-3/&quot;&gt;Previously on KhaSmup&lt;/a&gt; we added keyboard support and limited the ship to only be pilotable on the visible screen. In this tutorial we are going to add the ability to shoot as well as the sounds of the shot. First thing we have to do is add a bullet.&lt;/p&gt;
&lt;h4&gt;Bullet.hx&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;package;

import kha.Image;
import kha.graphics2.Graphics;

class Bullet {
  private var image: Image;

  public var x: Int;
  public var y: Int;
  public var speed: Int = 600;
  public var isActive: Bool = true;

  public function new(x: Int, y: Int, image: Image) {
    this.image = image;
    activate(x, y);
  }

  public function activate(x: Int, y: Int) {
    this.x = x;
    this.y = y;
    isActive = true;
  }

  public function render(g: Graphics): Void {
    if (!isActive) {
      return;
    }

    g.drawImage(image, x, y);
  }

  public function update(deltaTime: Float): Void {
    if (!isActive) {
      return;
    }

    y -= Math.round(speed * deltaTime);
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Most of this should be pretty obvious - it shows a lot of similarity to the Ship. The major difference is we have an isActive field. You may be wondering what this is for - let’s take a look at Gun.hx, which is what we will be using to manage these bullets:&lt;/p&gt;
&lt;h4&gt;Gun.hx&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;package;

import kha.Image;
import kha.Sound;
import kha.audio1.Audio;
import kha.graphics2.Graphics;

class Gun {
  private var bulletImage: Image;
  private var bulletSound: Sound;
  private var shotInterval: Float;
  private var cooldownLeft: Float;
  private var bullets: Array&amp;lt;Bullet&amp;gt;;

  public function new(shotInterval: Float, bulletImage: Image, bulletSound: Sound) {
    this.shotInterval = shotInterval;
    this.bulletImage = bulletImage;
    this.bulletSound = bulletSound;
    cooldownLeft = 0;
    bullets = new Array&amp;lt;Bullet&amp;gt;();
  }

  public function shoot(x: Int, y: Int): Void {
    if (cooldownLeft &amp;lt;= 0) {
      Audio.play(bulletSound, false);
      cooldownLeft = shotInterval;
      var adjX: Int = x - Std.int(bulletImage.width / 2);

      for (i in 0...bullets.length) {
        if (!bullets[i].isActive) {
          bullets[i].activate(adjX, y);
          return;
        }
      }

      bullets.push(new Bullet(adjX, y, bulletImage));
    }
  }

  public function update(deltaTime: Float) {
    cooldownLeft -= deltaTime;
    if (cooldownLeft &amp;lt; 0) {
      cooldownLeft = 0;
    }

    for (i in 0...bullets.length) {
      var bullet = bullets[i];
      bullet.update(deltaTime);

      if (bullet.isActive &amp;amp;&amp;amp; bullet.y + bulletImage.height &amp;lt; 0) {
        bullets[i].isActive = false;
      }
    }
  }

  public function render(g: Graphics) {
    for (i in 0...bullets.length) {
      bullets[i].render(g);
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This class is has a few new features. For one, it uses a countdown feature - we have a shotInterval variable that defines how long in seconds we wait between two shots. When the user shoots, we check if the cooldownLeft is at zero, and if it is - we set it to the interval , create a bullet, and play a sound. The Audio.play method takes a sound and a boolean to specify if you want it to loop or not. This sound is played by calling Audio.play, which is how we can interface with Kha’s audio1 api.&lt;/p&gt;
&lt;p&gt;The bullet creation may look a little interesting - we have an array, and when we create a bullet we iterate through this array looking for an inactive bullet, and if we don’t find one - we create a new one. If we do happen to find an inactive bulelt we just use the inactive one and we activate it.&lt;/p&gt;
&lt;p&gt;This is a very naive form of &lt;a href=&quot;https://en.wikipedia.org/wiki/Object_pool_pattern&quot;&gt;object pooling&lt;/a&gt;. The idea behind pooling is that sometimes object initialization is costly, so we decide to limit this cost by keeping around already initialized objects. This can also help out with languages that have garbage collection such as Haxe. Garbage collection is a great tool, but it can sometimes hamper the experience of games - causing a spike in lag as unused objects are cleaned up. By pooling we still hold onto references of objects, preventing them from being collected until we no longer hold a reference to the pool AND the object.&lt;/p&gt;
&lt;p&gt;Objects that are good candidates for pooling are those that you tend to create and destroy a whole lot - like these bullets. Generally you will want to profile your game (using a tool such as &lt;a href=&quot;http://hxscout.com/&quot;&gt;hxScout&lt;/a&gt;) before you commit to pooling - as holding a ton of objects in memory has its own downsides.&lt;/p&gt;
&lt;p&gt;There are much more general implementations of pools out there - and you will probably want to use something a little stronger if you start making a bigger game, but this implementation was chosen to be demonstrative and to introduce the concept if you’ve never seen it.&lt;/p&gt;
&lt;p&gt;Note that we have the bullet coming right out of the gun - but obviously you can change this up and make the gun cooler by having two bullets shoot, or even something crazier.&lt;/p&gt;
&lt;p&gt;Now that we have our gun, let’s add it to our ship:&lt;/p&gt;
&lt;h4&gt;Ship.hx&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;package;

import kha.Image;
import kha.graphics2.Graphics;

class Ship {
  private var image: Image;
  private var gun: Gun;
  private var gunOffsetY = 10;

  public var x: Int;
  public var y: Int;
  public var width(get, null): Int;
  public var height(get, null): Int;
  public var speed = 300.0;

  public function new(x: Int, y: Int, image: Image) {
    this.x = x;
    this.y = y;
    this.image = image;
  }

  public function attachGun(gun: Gun) {
    this.gun = gun;
  }

  function get_width(): Int {
    return image.width;
  }

  function get_height(): Int {
    return image.height;
  }

  public function render(g: Graphics) {
    if (gun != null) {
      gun.render(g);
    }
    g.drawImage(image, x, y);
  }

  public function update(controls: Controls, deltaTime: Float) {
    if (controls.left &amp;amp;&amp;amp; !controls.right) {
      x -= Math.round(speed * deltaTime);
    } else if (controls.right &amp;amp;&amp;amp; !controls.left) {
      x += Math.round(speed * deltaTime);
    }

    if (controls.up &amp;amp;&amp;amp; !controls.down) {
      y -= Math.round(speed * deltaTime);
    } else if (controls.down &amp;amp;&amp;amp; !controls.up) {
      y += Math.round(speed * deltaTime);
    }

    if (gun != null) {
      if (controls.shoot) {
        gun.shoot(x + Std.int(image.width / 2), y - gunOffsetY);
      }
      gun.update(deltaTime);
    }
  } 
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The gun gets inserted in pretty much as is, the only major difference is that we check if this gun is null before rendering it or shooting it. This allows us to instantiate ships without guns.&lt;/p&gt;
&lt;p&gt;Obviously we have to update our controls.&lt;/p&gt;
&lt;h4&gt;Controls.hx&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;package;

import kha.Key;

class Controls {
  public var left: Bool;
  public var right: Bool;
  public var up: Bool;
  public var down: Bool;
  public var shoot: Bool;

  public function new() {}

  public function keyDown(key: Key, value: String) { 
    switch (key) {
    case LEFT:
      left = true;
    case RIGHT:
      right = true;
    case UP:
      up = true;
    case DOWN:
      down = true;
    case CHAR:
      if (value == &amp;quot;z&amp;quot;) {
        shoot = true;
      }
    default:
      // no-op
    }
  }

  public function keyUp(key: Key, value: String) { 
    switch (key) {
    case LEFT:
      left = false;
    case RIGHT:
      right = false;
    case UP:
      up = false;
    case DOWN:
      down = false;
    case CHAR:
      if (value == &amp;quot;z&amp;quot;) {
        shoot = false;
      }
    default:
      //no-op
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The addition here is that we add a new switch case to both methods checking for CHAR, which is the key type representing a character. Now this gets into the kind-of weird part of Kha sending a char key’s value as a string - we have to then check the value in a sub-condition. Not exactly how I would have chosen to do this, but it works.&lt;/p&gt;
&lt;p&gt;Let’s wrap this up by updating KhaShmup:&lt;/p&gt;
&lt;h4&gt;KhaShmup.hx&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;package;

import kha.Assets;
import kha.Color;
import kha.Framebuffer;
import kha.Image;
import kha.Key;
import kha.Scaler;
import kha.System;
import kha.input.Keyboard;

class KhaShmup {

  private static var bgColor = Color.fromValue(0x26004d);

  public static inline var screenWidth = 800;
  public static inline var screenHeight = 600;
  public static inline var gunSpeed = 0.25;

  private var backbuffer: Image;
  private var controls: Controls;
  private var initialized = false;
  private var ship: Ship;
  private var timer: Timer;

  public function new() {
    Assets.loadEverything(loadingFinished);
  }

  private function loadingFinished(): Void {
    initialized = true;

    // create a buffer to draw to
    backbuffer = Image.createRenderTarget(screenWidth, screenHeight);

    // create our player
    var shipImg = Assets.images.playerShip;
    ship = new Ship(Std.int(screenWidth / 2) - Std.int(shipImg.width / 2), 
      Std.int(screenHeight / 2) - Std.int(shipImg.height / 2), 
      shipImg);
    controls = new Controls();
    timer = new Timer();
    Keyboard.get().notify(keyDown, keyUp);
    setupShip();
  }

  public function render(framebuffer: Framebuffer): Void {
    if (!initialized) {
      return;
    }

    var g = backbuffer.g2;

    // clear and draw to our backbuffer
    g.begin(bgColor);
    ship.render(g);
    g.end();

    // draw our backbuffer onto the active framebuffer
    framebuffer.g2.begin();
    Scaler.scale(backbuffer, framebuffer, System.screenRotation);
    framebuffer.g2.end();

    update();
  }

  private function setupShip() {
    ship = new Ship(Std.int(screenWidth / 2) - Std.int(ship.width / 2), 
      Std.int(screenHeight / 2) - Std.int(ship.height / 2), 
      Assets.images.playerShip);
    ship.attachGun(new Gun(gunSpeed, Assets.images.bullet, Assets.sounds.bulletShoot));
  }

  private function update() {
    timer.update();
    updateShip();
  }

  private function updateShip() {
    ship.update(controls, timer.deltaTime);

    // limit the ship to the width of the screen
    if (ship.x &amp;lt; 0) {
      ship.x = 0;
    } else if (ship.x + ship.width &amp;gt; screenWidth) {
      ship.x = screenWidth - ship.width;
    }

    // limit the ship to the height of the screen
    if (ship.y &amp;lt; 0) {
      ship.y = 0;
    } else if (ship.y + ship.height &amp;gt; screenHeight) {
      ship.y = screenHeight - ship.height;
    }
  }

  private function keyDown(key: Key, value: String): Void {
    controls.keyDown(key, value);
  }

  private function keyUp(key: Key, value: String): Void {
    controls.keyUp(key, value);
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Almost the exact same as before, aside from the instantiation of the Gun and attaching it to the Ship. Also we grab the bullet.wav sound out of the assets. For that you should go to &lt;a href=&quot;http://www.bfxr.net/&quot;&gt;bfxr.net&lt;/a&gt;, create a sound you enjoy, then export it as a wav file to your Assets folder, and adjust the name to “bulletShoot.wav”.&lt;/p&gt;
&lt;h4&gt;Running the Application&lt;/h4&gt;
&lt;p&gt;You’ll now be able to move the ship, and when you hit the z button you’ll shoot a bullet out.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://jamiltron.com/images/khaShmup4.gif&quot; alt=&quot;Lasers&quot;&gt;&lt;/p&gt;
&lt;p&gt;If you don’t see this, check out my part-4 branch:&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/jamiltron/KhaShmup/tree/part-4&quot;&gt;https://github.com/jamiltron/KhaShmup/tree/part-4&lt;/a&gt;&lt;/p&gt;
&lt;h4&gt;In Summary&lt;/h4&gt;
&lt;p&gt;We’re starting to see a game form piece-by-piece. We learned how to shoot, how to play a sound, and we learned a little bit about object pooling to delay initialization/garbage-collection costs. In &lt;a href=&quot;http://jamiltron.com/2015/12/KhaShmup-Tutorial-Part-5/&quot;&gt;part 5&lt;/a&gt; we’ll be adding some targets for the player to shoot.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Kha Shmup Tutorial Part 3</title>
    <link href="https://jamiltron.com/2015/12/KhaShmup-Tutorial-Part-3/" />
    <updated>2015-12-14T00:00:00Z</updated>
    <id>https://jamiltron.com/2015/12/KhaShmup-Tutorial-Part-3/</id>
    <content type="html">&lt;p&gt;In &lt;a href=&quot;http://jamiltron.com/2015/12/KhaShmup-Tutorial-Part-2/&quot;&gt;part 2&lt;/a&gt; we got the player’s ship on screen. This time we’re going to give the player some control over it.&lt;/p&gt;
&lt;h4&gt;Timer.hx&lt;/h4&gt;
&lt;p&gt;Something you’ve probably came across if you’ve read any tutorials on making simple games is frame independent movement, sometimes called &lt;a href=&quot;https://en.wikipedia.org/wiki/Delta_timing&quot;&gt;delta timing&lt;/a&gt;. The basic idea is that if you have two computers - both of which are playing your game. Each computer has a player that holds down the “move right” button, but let’s say that once computer just updates slower than the other. If your movement code is based on number of updates called, you are going to have different experiences between these two computers - one player’s character will lag behind the other.&lt;/p&gt;
&lt;p&gt;To combat this you can base your movement code on the amount of time in frames. This way when the slower computer updates inbetween frames, the movement will be scale accordingly, meaning the character on each computer will appear to move the exact same distance.&lt;/p&gt;
&lt;p&gt;To achieve this we will be creating a file called Timer.hx:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;package;

import kha.Scheduler;

class Timer {
  public var deltaTime(default, null): Float;
  public var lastTime(default, null): Float;

  public function new() {
    reset();
  }

  public function update() {
    var currentTime = Scheduler.time();
    deltaTime = currentTime - lastTime;
    lastTime = currentTime;
  }

  public function reset() {
    lastTime = Scheduler.time();
    deltaTime = 0;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you haven’t seen the notation on deltaTime and lastTime before, those are &lt;a href=&quot;http://haxe.org/manual/class-field-property.html&quot;&gt;properties&lt;/a&gt;, they allow to specify additional contraints to your fields. The first in that tuple defines the read access, and the second specifies the write access. We are saying that deltaTime and lastTime have default read access, meaning anyone who has an instance of a Timer can read either of these fields. The null in the second position means that these fields are only set-able from within an instance of Timer itself. So this is a basic “read-only” property.&lt;/p&gt;
&lt;p&gt;This class keeps track of the lastTime (that is, the previously seen timestamp provided by Kha), and everytime there is a call to update we’re calculating the deltaTime by finding the difference between the currentTime, and we are resetting lastTime.&lt;/p&gt;
&lt;h4&gt;Controls.hx&lt;/h4&gt;
&lt;p&gt;The next thing we need is a way to keep track of controls. Open up a file named Controls.hx:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;package;

import kha.Key;

class Controls {
  public var left: Bool;
  public var right: Bool;
  public var up: Bool;
  public var down: Bool;

  public function new() {}

  public function keyDown(key: Key) { 
    switch (key) {
    case LEFT:
      left = true;
    case RIGHT:
      right = true;
    case UP:
      up = true;
    case DOWN:
      down = true;
    default:
      // no-op
    }
  }

  public function keyUp(key: Key) { 
    switch (key) {
    case LEFT:
      left = false;
    case RIGHT:
      right = false;
    case UP:
      up = false;
    case DOWN:
      down = false;
    default:
      //no-op
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This class is pretty much just two big switches to swap four different flags - each flag represents a possible button, and depending on the Key passed to either switch, we update the flag. We’ll see more about keys in a bit.&lt;/p&gt;
&lt;p&gt;We will be using these classes in our main game class, but let’s update our Ship first to take into account controls and time, and we’ll add in some properties for fun:&lt;/p&gt;
&lt;h4&gt;Ship.hx&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;package;

import kha.Image;
import kha.graphics2.Graphics;

class Ship {
  private var image: Image;

  public var x: Int;
  public var y: Int;
  public var width(get, null): Int;
  public var height(get, null): Int;
  public var speed = 300.0;

  public function new(x: Int, y: Int, image: Image) {
    this.x = x;
    this.y = y;
    this.image = image;
  }

  private function get_width(): Int {
    return image.width;
  }

  private function get_height(): Int {
    return image.height;
  }

  public function render(g: Graphics) {
    g.drawImage(image, x, y);
  }

  public function update(controls: Controls, deltaTime: Float) {
    if (controls.left &amp;amp;&amp;amp; !controls.right) {
      x -= Math.round(speed * deltaTime);
    } else if (controls.right &amp;amp;&amp;amp; !controls.left) {
      x += Math.round(speed * deltaTime);
    }

    if (controls.up &amp;amp;&amp;amp; !controls.down) {
      y -= Math.round(speed * deltaTime);
    } else if (controls.down &amp;amp;&amp;amp; !controls.up) {
      y += Math.round(speed * deltaTime);
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;There are a few changes here - let’s start with the width and height properties. We see that we have specified null write-access, but the read-access is specified with a “get”. You will also notice to methods below - get_width, and get_height. These methods correspond to the getters for those fields. This allows us to read width or height given an instance of a ship as you would any other field, but we are returning the width and height of the image associated with the ship. This allows us to retrieve these properties from the private variable image, without having to change image’s visibility.&lt;/p&gt;
&lt;p&gt;The second change is the update method: this is a method taking in controls and deltaTime. We are then updating the ship’s position based on this, and we are using deltaTime to scale this movement, giving us our frame-independent movement. Note that we are rounding this value - x and y are Ints, which was something we decided on because the image filtering may change when an image is on non-integer pixels. Now, this may be fine for your game and you may want to experiment with this, but for this game keeping positions as integers keeps the images smooth and crisp.&lt;/p&gt;
&lt;p&gt;Now let’s go back to our KhaShmup game class and take into account the changes.&lt;/p&gt;
&lt;h4&gt;KhaShmup.hx&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;package;

import kha.Assets;
import kha.Color;
import kha.Framebuffer;
import kha.Image;
import kha.Key;
import kha.Scaler;
import kha.System;
import kha.input.Keyboard;

class KhaShmup {

  private static var bgColor = Color.fromValue(0x26004d);

  public static inline var screenWidth = 800;
  public static inline var screenHeight = 600;

  private var backbuffer: Image;
  private var controls: Controls;
  private var initialized = false;
  private var ship: Ship;
  private var timer: Timer;

  public function new() {
    Assets.loadEverything(loadingFinished);
  }

  private function loadingFinished(): Void {
    initialized = true;

    // create a buffer to draw to
    backbuffer = Image.createRenderTarget(screenWidth, screenHeight);

    // create our player
    var shipImg = Assets.images.playerShip;
    ship = new Ship(Std.int(screenWidth / 2) - Std.int(shipImg.width / 2), 
      Std.int(screenHeight / 2) - Std.int(shipImg.height / 2), 
      shipImg);
    controls = new Controls();
    timer = new Timer();
    Keyboard.get().notify(keyDown, keyUp);
  }

  public function render(framebuffer: Framebuffer): Void {
    if (!initialized) {
      return;
    }

    var g = backbuffer.g2;

    // clear and draw to our backbuffer
    g.begin(bgColor);
    ship.render(g);
    g.end();

    // draw our backbuffer onto the active framebuffer
    framebuffer.g2.begin();
    Scaler.scale(backbuffer, framebuffer, System.screenRotation);
    framebuffer.g2.end();

    update();
  }

  private function update() {
    timer.update();
    updateShip();
  }

  private function updateShip() {
    ship.update(controls, timer.deltaTime);

    // limit the ship to the width of the screen
    if (ship.x &amp;lt; 0) {
      ship.x = 0;
    } else if (ship.x + ship.width &amp;gt; screenWidth) {
      ship.x = screenWidth - ship.width;
    }

    // limit the ship to the height of the screen
    if (ship.y &amp;lt; 0) {
      ship.y = 0;
    } else if (ship.y + ship.height &amp;gt; screenHeight) {
      ship.y = screenHeight - ship.height;
    }
  }

  private function keyDown(key: Key, value: String): Void {
    controls.keyDown(key);
  }

  private function keyUp(key: Key, value: String): Void {
    controls.keyUp(key);
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;There are a bunch of changes here. For one we instantiate our timer and our controls.&lt;/p&gt;
&lt;p&gt;Secondly, in loadingFinished we make a call to Keyboard.get().notify, and we provide two methods we define at the bottom of this file - keyDown and keyUp. This is registering our methods to Kha’s input system, so that when the keyboard has a key up or key down, the appropriate method gets called. These are where we update our Controls instance. Note that both of these methods take a Key - which is an enum saying what &lt;em&gt;kind&lt;/em&gt; of key is pressed - in this key we are caring only about specific directional keys, but this could also be something like the Shift key, or even a character key. This leads to the second parameter of these methods - the String value. Kha sends character keys such as the “A” key as a String. I think this is somewhat of a weird decision, as I would have much preferred the traditional keycode, but this is how Kha was built.&lt;/p&gt;
&lt;p&gt;At the end of our render method we also make a call to update, and here is where we update both the timer as well as the ship. We pass our ship the controls, and we know it will update its position. We then limit the ship’s movement to be within our screen, disallowing the player from flying off camera.&lt;/p&gt;
&lt;h4&gt;Running the Application&lt;/h4&gt;
&lt;p&gt;Now when you run the application you should see your ship like before, but by pressing the arrow keys your ship should be moving. If you are not able to do this, check out my part-3 branch:&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/jamiltron/KhaShmup/tree/part-3&quot;&gt;https://github.com/jamiltron/KhaShmup/tree/part-3&lt;/a&gt;&lt;/p&gt;
&lt;h4&gt;In Summary&lt;/h4&gt;
&lt;p&gt;We learned how to use a timer to get frame-independent movement, and we also built a class to contain our game’s controls. In &lt;a href=&quot;http://jamiltron.com/2015/12/KhaShmup-Tutorial-Part-4/&quot;&gt;part 4&lt;/a&gt; we will be adding more controls, allowing the player to shoot, and we will also be learning about object pooling.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Kha Shmup Tutorial Part 2</title>
    <link href="https://jamiltron.com/2015/12/KhaShmup-Tutorial-Part-2/" />
    <updated>2015-12-10T00:00:00Z</updated>
    <id>https://jamiltron.com/2015/12/KhaShmup-Tutorial-Part-2/</id>
    <content type="html">&lt;p&gt;&lt;a href=&quot;http://jamiltron.com/2015/12/KhaShmup-Tutorial-Part-1/&quot;&gt;Last time&lt;/a&gt; we started up a Kha program and got a nice purple screen rendering. This time we will be displaying a sprite representing the player.&lt;/p&gt;
&lt;h4&gt;Ship.hx&lt;/h4&gt;
&lt;p&gt;Create a new file named Ship.hx in the Sources directory and fill it up like so:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;package;

import kha.Image;
import kha.graphics2.Graphics;

class Ship {
  private var image: Image;

  public var x: Int;
  public var y: Int;

  public function new(x: Int, y: Int, image: Image) {
    this.x = x;
    this.y = y;
    this.image = image;
  }

  public function render(g: Graphics) {
    g.drawImage(image, x, y);
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This should be fairly straight-forward - its a class containing an image, and a 2d position. It also contains a render function - taking in a &lt;a href=&quot;https://github.com/KTXSoftware/Kha/blob/master/Sources/kha/graphics2/Graphics.hx&quot;&gt;graphics2&lt;/a&gt; instance and draws the Ship’s image using it. Note that we do not call begin or end on g, we will be calling this outside of this class. Now we have to load the ship’s image asset.&lt;/p&gt;
&lt;h4&gt;Assets and khafile.js&lt;/h4&gt;
&lt;p&gt;Go into the khafile.js project file and make sure it looks like this:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;let project = new Project(&#39;KhaSmup&#39;);

project.addAssets(&#39;Assets/**&#39;);
project.addSources(&#39;Sources&#39;);

resolve(project);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The only change is adding an assets directory. Now make sure to create this directory in the root of the project, and add an image to it name playerShip.png. I am using one of the ships from &lt;a href=&quot;http://kenney.nl/assets&quot;&gt;Kenny.nl’s game asset pack&lt;/a&gt;, which is a great collection of assets for several genres of games. I am using the following ship:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://jamiltron.com/images/playerShip.png&quot; alt=&quot;Player Ship&quot;&gt;&lt;/p&gt;
&lt;h4&gt;KhaShmup.hx&lt;/h4&gt;
&lt;p&gt;We need to make a few changes to KhaShmup.hx to load the assets and to initialize our ship:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;package;

import kha.Assets;
import kha.Color;
import kha.Framebuffer;
import kha.Image;
import kha.Scaler;
import kha.System;

class KhaShmup {

  private static var bgColor = Color.fromValue(0x26004d);

  public static inline var screenWidth = 800;
  public static inline var screenHeight = 600;

  private var backbuffer: Image;
  private var initialized = false;
  private var ship: Ship;

  public function new() {
    Assets.loadEverything(loadingFinished);
  }

  private function loadingFinished(): Void {
    initialized = true;

    // create a buffer to draw to
    backbuffer = Image.createRenderTarget(screenWidth, screenHeight);

    // create our player
    var shipImg = Assets.images.playerShip;
    ship = new Ship(Std.int(screenWidth / 2) - Std.int(shipImg.width / 2), 
      Std.int(screenHeight / 2) - Std.int(shipImg.height / 2), 
      shipImg);
  }

  public function render(framebuffer: Framebuffer): Void {
    if (!initialized) {
      return;
    }

    var g = backbuffer.g2;

    // clear and draw to our backbuffer
    g.begin(bgColor);
    ship.render(g);
    g.end();

    // draw our backbuffer onto the active framebuffer
    framebuffer.g2.begin();
    Scaler.scale(backbuffer, framebuffer, System.screenRotation);
    framebuffer.g2.end();
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Let’s go over the changes.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;public function new() {
    Assets.loadEverything(loadingFinished);
  }
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;When we initialize our game, we now tell Kha’s Asset system to load everything (which is only one image at the moment), and once everything is loaded we call our loadingFinished method.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;private function loadingFinished(): Void {
    initialized = true;

    // create a buffer to draw to
    backbuffer = Image.createRenderTarget(screenWidth, screenHeight);

    // create our player
    var shipImg = Assets.images.playerShip;
    ship = new Ship(Std.int(screenWidth / 2) - Std.int(shipImg.width / 2), 
      Std.int(screenHeight / 2) - Std.int(shipImg.height / 2), 
      shipImg);
  }
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This loadingFinished callback sets an initialized flag to true, we load the ship’s image, and instantiate the ship.&lt;/p&gt;
&lt;p&gt;You may be wondering about the Std.int calls in the ship’s initialization. Std.int(x / y) will perform integer division on platforms that support that. In Kha we are don’t have to align images to whole integer positions, but when an image is not on whole images a different filtering method may be used. In my case I found that this often resulted in visual artifacts of blurriness, so whenever I can I keep images on whole integer positions.&lt;/p&gt;
&lt;p&gt;The call to Assets.images.playerShip may seem odd, but essentially Kha is running a macro to generate this accessor based on the image in our Assets directory, so once Kha has loaded all of the assets, we can grab any image (or sound, etc) using this format.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;public function render(framebuffer: Framebuffer): Void {
    if (!initialized) {
      return;
    }

    var g = backbuffer.g2;

    // clear and draw to our backbuffer
    g.begin(bgColor);
    ship.render(g);
    g.end();

    // draw our backbuffer onto the active framebuffer
    framebuffer.g2.begin();
    Scaler.scale(backbuffer, framebuffer, System.screenRotation);
    framebuffer.g2.end();
  }
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The major difference here is that we are checking our initialized flag to make sure we have loaded the assets we are intending to render. The other change is that we make the call to the ship’s render method, providing it a graphics instance.&lt;/p&gt;
&lt;h4&gt;Running the application&lt;/h4&gt;
&lt;p&gt;Now when you run the application you should be seeing this:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://jamiltron.com/images/part2.png&quot; alt=&quot;Part 2&quot;&gt;&lt;/p&gt;
&lt;p&gt;If you do not, check out part-2 of my branch.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/jamiltron/KhaShmup/tree/part-2&quot;&gt;https://github.com/jamiltron/KhaShmup/tree/part-2&lt;/a&gt;&lt;/p&gt;
&lt;h4&gt;In Summary&lt;/h4&gt;
&lt;p&gt;We loaded up some assets and rendered an image representing the player. In &lt;a href=&quot;http://jamiltron.com/2015/12/KhaShmup-Tutorial-Part-3/&quot;&gt;part 3&lt;/a&gt; we will learn how to use keyboard as input and we will get the player moving around the screen.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Kha Shmup Tutorial Part 1</title>
    <link href="https://jamiltron.com/2015/12/KhaShmup-Tutorial-Part-1/" />
    <updated>2015-12-09T00:00:00Z</updated>
    <id>https://jamiltron.com/2015/12/KhaShmup-Tutorial-Part-1/</id>
    <content type="html">&lt;p&gt;Continuing from the &lt;a href=&quot;http://jamiltron.com/2015/12/KhaShmup-Tutorial-Intro/&quot;&gt;previous tutorial&lt;/a&gt; we’ve made sure we are running a recent version of &lt;a href=&quot;http://haxe.org/&quot;&gt;Haxe&lt;/a&gt; (I am running 3.2.1), a recent version of &lt;a href=&quot;https://nodejs.org/en/&quot;&gt;NodeJS&lt;/a&gt; (5.0.0 for me), as well as the &lt;a href=&quot;https://git-scm.com/&quot;&gt;git&lt;/a&gt; version control system.&lt;/p&gt;
&lt;h4&gt;Game Features&lt;/h4&gt;
&lt;p&gt;Throughout this tutorial we will be building a small space shooter. I want to build a small game, but to make sure its not trivial. This game will have the following features:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;A ship the player can move around.&lt;/li&gt;
&lt;li&gt;Enemies who randomly spawn.&lt;/li&gt;
&lt;li&gt;The ability to shoot lasers to destroy enemies.&lt;/li&gt;
&lt;li&gt;A score representing the amount of enemies destroyed, represented with text.&lt;/li&gt;
&lt;li&gt;The “ability” to lose if the player collides with an enemy.&lt;/li&gt;
&lt;li&gt;A few game states, such as main menu, playing, and game over.&lt;/li&gt;
&lt;li&gt;Music and sounds.&lt;/li&gt;
&lt;li&gt;Object pooling on the bullets the player can shoot, as well as the enemy.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;I think this will be enough to showcase several of Kha’s features and allow for further expansion. This tutorial will be built in a somewhat naive fashion - we are mostly trying to provide a starting point for making a game in Kha. Refactoring into a solid code-base is left as an exercise to the reader :P&lt;/p&gt;
&lt;h4&gt;Getting Started&lt;/h4&gt;
&lt;p&gt;Kha is typically handled as a git submodule to another project, which is how we will be using it. Check out a basic empty project by typing the following into your console:&lt;/p&gt;
&lt;p&gt;&lt;code&gt;git clone --recursive https://github.com/KTXSoftware/Empty.git&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;After cloning if you want to rename the directory feel free to do so.&lt;/p&gt;
&lt;p&gt;You’ll see a few files and directories in here:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Kha - this contains the sources for the Kha framework as well as the tools it uses. You shouldn’t have to mess with this.&lt;/li&gt;
&lt;li&gt;Sources - is where all of the source files for our game will live.&lt;/li&gt;
&lt;li&gt;khafile.js - this is the build file for the entire project.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4&gt;khafile.js&lt;/h4&gt;
&lt;p&gt;Let’s open up khafile.js and get rid of everything and replace it with the following:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;let project = new Project(&#39;KhaSmup&#39;);

project.addSources(&#39;Sources&#39;);

resolve(project);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This defines a project named ‘KhaShmup’ and makes sure to tell the project to use the files found in the Sources directory. Let’s check out that directory now.&lt;/p&gt;
&lt;p&gt;In Sources we find two files - Empty.hx, and Main.hx. Main is the entry point for the program and Empty is the “game.” We can get rid of this as we’ll be using a class for our own game.&lt;/p&gt;
&lt;h4&gt;Main.hx&lt;/h4&gt;
&lt;p&gt;Start by opening up Main.hx and enter the following:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;package;

import kha.System;

class Main {

  public static function main() {
    System.init({ title: &amp;quot;KhaShmup&amp;quot;, width: 800, height: 600 }, init);
  }

  private static function init() {
    var game = new KhaShmup();
    System.notifyOnRender(game.render);
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This class has an entry point main which initializes Kha’s system, sets the window name as “KhaShmup”, the width of the window to 800, the height to 600, and provides a callback of the function init once the System is ready to go.&lt;/p&gt;
&lt;p&gt;The callback is where we create an instance of our game and we tell the system that when it renders we want to call our game’s render method.&lt;/p&gt;
&lt;h4&gt;KhaShmup.hx&lt;/h4&gt;
&lt;p&gt;Create a file in the Sources directory named KhaShmup.hx and add the following lines to it:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-haxe&quot;&gt;package;

import kha.Color;
import kha.Framebuffer;
import kha.Image;
import kha.Scaler;
import kha.System;

class KhaShmup {

  private static var bgColor = Color.fromValue(0x26004d);
  public static inline var screenWidth = 800;
  public static inline var screenHeight = 600;

  private var backbuffer: Image;

  public function new() {
    // create a buffer to draw to
    backbuffer = Image.createRenderTarget(screenWidth, screenHeight);
  }

  public function render(framebuffer: Framebuffer): Void {
    var g = backbuffer.g2;

    // clear our backbuffer using graphics2
    g.begin(bgColor);
    g.end();

    // draw our backbuffer onto the active framebuffer
    framebuffer.g2.begin();
    Scaler.scale(backbuffer, framebuffer, System.screenRotation);
    framebuffer.g2.end();
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is our main game class. We start by instantiating a “back buffer” - this allows us to use &lt;a href=&quot;https://en.wikipedia.org/wiki/Multiple_buffering&quot;&gt;double buffering&lt;/a&gt; so that we draw to a “back” buffer - one that is not rendered to the screen yet, and when it becomes time to do so we just swap the currently rendered buffer with our back buffer.&lt;/p&gt;
&lt;p&gt;In the render method we recieve a framebuffer - the currently rendered buffer. We then get a member “g2” from our backbuffer. This is an instance of the &lt;a href=&quot;https://github.com/KTXSoftware/Kha/blob/master/Sources/kha/graphics2/Graphics.hx&quot;&gt;graphics2 api&lt;/a&gt; in Kha. This is pretty much the api you will be using for 2d rendering, html5 canvas, etc. Kha versions its apis into numbers, so there is a g4 representing 3d graphics, multiple audio apis, etc.&lt;/p&gt;
&lt;p&gt;With this instance we clear it to our preset background color - which is kind of a dark purple.&lt;/p&gt;
&lt;p&gt;We then draw our purple backbuffer onto the frame buffer. The Scaler.scale method basically scales the “source” image - our backbuffer, to the size of our “destination” image - the framebuffer, and the renders the source onto the destination. The begin and end methods on the graphics instances are done so that Kha can batch draw operations where possible, providing pretty great rendering performance.&lt;/p&gt;
&lt;h4&gt;Running the application&lt;/h4&gt;
&lt;p&gt;There are a number of different ways you can run a Kha application but the way that I typically do is to navigate to the root of the project directory and to run the following:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;node Kha/make html5     
node Kha/make --server
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This will compile the html5 target and then serve it on localhost:8080. If you go there you should see a big purple screen.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://jamiltron.com/images/HelloPurpleScreen.png&quot; alt=&quot;Hello, Purple Screen&quot;&gt;&lt;/p&gt;
&lt;p&gt;If you don’t you can compare your code to the part-1 branch of my repo:&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/jamiltron/KhaShmup/tree/part-1&quot;&gt;https://github.com/jamiltron/KhaShmup/tree/part-1&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;An interesting thing about the build system is that Kha will generate projects for your targeted platform. For example if I wanted an XCode project for OSX, running&lt;/p&gt;
&lt;p&gt;&lt;code&gt;node Kha/make osx&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;would build an XCode project in the build directory. I then could open up in XCode allowing me to use all the tools associated with that platform. That’s a pretty cool feature as sometimes tracking down issues in the output of compiled Haxe code from the terminal can be pretty frustrating. However if I want to quickly compile and run natively for osx, I could just run&lt;/p&gt;
&lt;p&gt;&lt;code&gt;node Kha/make osx --run&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;Again, if you have any issues, compare your code to my repo: &lt;a href=&quot;https://github.com/jamiltron/KhaShmup/tree/part-1&quot;&gt;https://github.com/jamiltron/KhaShmup/tree/part-1&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;I know it seems like we haven’t gotten that far, but getting all of the required software and spinning up a project will be a good starting point for rendering an image on screen, which we will get to in &lt;a href=&quot;http://jamiltron.com/2015/12/KhaShmup-Tutorial-Part-2/&quot;&gt;part 2&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Thank you for reading!&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Kha Shmup Tutorial Intro</title>
    <link href="https://jamiltron.com/2015/12/KhaShmup-Tutorial-Intro/" />
    <updated>2015-12-08T00:00:00Z</updated>
    <id>https://jamiltron.com/2015/12/KhaShmup-Tutorial-Intro/</id>
    <content type="html">&lt;h3&gt;Kha Shmup Tutorial Part 0&lt;/h3&gt;
&lt;p&gt;&lt;a href=&quot;http://kha.ktxsoftware.com&quot;&gt;Kha&lt;/a&gt; describes itself as a “super-portable dev kit.” The tool is kind of equivalent to the &lt;a href=&quot;http://haxe.org/&quot;&gt;Haxe&lt;/a&gt; version of &lt;a href=&quot;https://www.libsdl.org/&quot;&gt;SDL&lt;/a&gt;. Essentially its a tool by which you can use Haxe to make games or other media applications, and it allows you to target Linux, OSX, Windows, Android, iOS, HTML5, and several other targets very efficiently.&lt;/p&gt;
&lt;p&gt;Kha has always seemed super interesting to me - I love Haxe, and I am always on the lookout for open source game frameworks that have a high degree of portability. I love and continue to use &lt;a href=&quot;http://unity3d.com/&quot;&gt;Unity3d&lt;/a&gt;, but I feel it has a few downsides when it comes to 2d development, and often I feel its closed-source nature fights against it. Recently I was trying to learn the low-level Transport Layer Networking in Unity, and there were often questions I had that would have been easily grokkable had I access to the source.&lt;/p&gt;
&lt;p&gt;Kha seems like a great tool, but I have had many complaints about it, which I have seen shared among a few other developers who have tried getting into it - it uses an unfamiliar build system, its api is somewhat of a moving target, and worst of all - it lacks documentation.&lt;/p&gt;
&lt;p&gt;That last part is often a curse that kills many open source projects - no matter how good your software may be, if people can’t figure out how to use it, it won’t get used. When people are looking for a library or framework to use they aren’t often willing to read a majority of the code base, post on forums, jump into irc channels and the like.&lt;/p&gt;
&lt;p&gt;The lack of documentation is one that is pretty easily solved - people who have actually penetrated and started undestanding the software just have to write down, talk about, or cast themselves discussing it.&lt;/p&gt;
&lt;p&gt;I decided rather than look at Kha and say “Eh, not enough docs for me..” that I should try to understand as much of it as I can and write down what will hopefully be helpful to others. The Kha community has been very welcoming and helpful to me, someone who basically just pops up once and a while and asks “how do I…”&lt;/p&gt;
&lt;p&gt;So my process of documenting will be the creation of a very small shoot ‘em up game, or “shmup.” I will be going step-by-step on github, so hopefully as I explain each step you will be able to see the code and how one might grow a small Kha program.&lt;/p&gt;
&lt;p&gt;I will be assuming that you know Haxe. If you do not &lt;a href=&quot;http://haxe.org/documentation/introduction/&quot;&gt;the documentation&lt;/a&gt; is alright to get started. For reference I am using 3.2.1 on OSX, but this should work on Linux or Windows.&lt;/p&gt;
&lt;p&gt;To run my examples you will need a copy of NodeJS, which you can download &lt;a href=&quot;http://nodejs.org/&quot;&gt;here&lt;/a&gt;. You will also need a version of &lt;a href=&quot;https://git-scm.com/&quot;&gt;git&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Kha is often included as a submodule within an individual Kha project, which is how I have it set up in this tutorial. You can use Kha from haxelib, but the version I am targeting has not been released to haxelib yet. I will update these tutorials when it has.&lt;/p&gt;
&lt;p&gt;Once you have Haxe ready to go and a recent version of NodeJS, we will be ready to begin putting our game together.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Global Game Jam 2015</title>
    <link href="https://jamiltron.com/2015/01/Global-Game-Jam-2015/" />
    <updated>2015-01-28T00:00:00Z</updated>
    <id>https://jamiltron.com/2015/01/Global-Game-Jam-2015/</id>
    <content type="html">&lt;p&gt;This past Sunday I had the pleasure of attending Global Game Jam 2015 at Oakland’s &lt;a href=&quot;http://themade.org&quot;&gt;Museum of Art and Digital Entertainment&lt;/a&gt;, which is always a great place - definitely something you should check out if you are visiting the Bay Area or live here and haven’t been there recently.&lt;/p&gt;
&lt;p&gt;They were kind to host this year’s Global Game Jam for the Bay Area, and the theme this year was “What do we do next?” My team had a pretty awesome sound engineer join us, so we definitely wanted to make a collaborative, multiplayer-instrument.&lt;/p&gt;
&lt;p&gt;Unfortunately he became ill and had to leave the jam, which left the rest of us working on adding sounds, filters, and the like to the game, which we only sort of understood.&lt;/p&gt;
&lt;p&gt;I do not think we got as far as making a “game” as I would have liked, but I am still proud of what we made, and am very grateful of my awesome team.&lt;/p&gt;
&lt;p&gt;If you want you can check out the game &lt;a href=&quot;http://globalgamejam.org/2015/games/sound-beasts&quot;&gt;here&lt;/a&gt;. If you do, let me know what you think!&lt;/p&gt;
&lt;p&gt;Again, thanks to my awesome team and to the great folks at &lt;a href=&quot;http://themade.org&quot;&gt;MADE&lt;/a&gt;.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Networked Platformer</title>
    <link href="https://jamiltron.com/2014/12/Networked-Platformer/" />
    <updated>2014-12-21T00:00:00Z</updated>
    <id>https://jamiltron.com/2014/12/Networked-Platformer/</id>
    <content type="html">&lt;p&gt;This weekend I decided I wanted to try my hand at making a non-turn-based game using &lt;a href=&quot;https://www.exitgames.com/en/PUN&quot;&gt;Photon Unity Networking&lt;/a&gt;. The only multiplayer games I have ever designed have been basically “call a REST service with move data, have the server validate the move, respond with result” type of stuff. Nothing built for actual real-time gameplay.&lt;/p&gt;
&lt;p&gt;Digging into Photon has been pretty easy. The docs are decent enough, and there are a moderate amount of examples online. Photon really lets you get up and running using the Photon Cloud to start testing out your networked game.&lt;/p&gt;
&lt;p&gt;So here’s a shot at what I have been making:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://jamiltron.com/images/SuperCoinAlien.png&quot; alt=&quot;Super Coin Alien&quot;&gt;&lt;/p&gt;
&lt;p&gt;Basically its a simple multiplayer version of &lt;a href=&quot;http://www.supercratebox.com/&quot;&gt;Super Crate Box&lt;/a&gt;. Players can move left and right, jump, shoot each other, shoot enemies, and collect coins. This weekend I have been focusing on the multiplayer aspects of it - trying to make sure that if I booted up two instances of the game, that gameplay looked alright. Again, reiterating that I have never done real-time multiplayer before, I had no idea how tricky this stuff can get.&lt;/p&gt;
&lt;p&gt;So the basics of Photon comes down to two aspects - RPCs and serializing data. Since the game is a fast-paced 2d platformer, I currently don’t have much RPCs I need, so this post will only focus on the serialization aspect.&lt;/p&gt;
&lt;p&gt;What you do is attach a component called a PhotonView to your entity, and match it up with a Component that this view is observing. So in my case, I attached a PhotonView to each of the players and pointed it to the component that controls them.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://jamiltron.com/images/PhotonViewComponent.png&quot; alt=&quot;Photon View&quot;&gt;&lt;/p&gt;
&lt;p&gt;In this observed component you then write a serialize view method:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-csharp&quot;&gt;void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info) {
  if (stream.isWriting) { // this our component, we are writing out
    stream.SendNext(transform.position);
  } else { // this is not our component, we are reading
    Vector3 newPosition = (Vector3) stream.ReceiveNext();
    transform.position = newPosition;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In the above example, the stream.isWriting is called a couple times a frame via the PhotonView (adjustable via the sendRateOnSerialize property) and sends out the position of the entity.&lt;/p&gt;
&lt;p&gt;If this component is attached to an entity that the client does not own, it will instead read in data from the stream and deserialize it. In this case we read in the entity’s position data and immediately set the entity’s current position to it.&lt;/p&gt;
&lt;p&gt;The problem here is that updates are not smooth - they come unreliably at different intervals depending on latency and other factors, so the entity appears extremely jittery.&lt;/p&gt;
&lt;p&gt;One way most people seem to handle this is to do linear interpolation between the entity’s read value and its current value, somewhat like this.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-csharp&quot;&gt;Vector3 syncPosition = new Vector3.zero;

void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info) {
  if (stream.isWriting) { // this our component, we are writing out
    stream.SendNext(transform.position);
  } else { // this is not our component, we are reading
    syncPosition = (Vector3) stream.ReceiveNext();
  }
}

void Update() {
  if (photonView.isMine) {
    // ... update normally
  } else {
    transform.position = Vector3.Lerp(transform.position, syncPosition, 10f * Time.deltaTime);
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This seems like a fine enough solution, but I found for my game that it still suffered from jitters.&lt;/p&gt;
&lt;p&gt;The current solution I am trying attempt to extrapolate the next position from the velocity, so that rending happens a lot more smoothly. Of course, I lose some accuracy doing this - characters rubber-band between positions a bit, they sometimes leap into the ground before being corrected, etc. But for a prototype it works well enough. Here’s an example of this:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-csharp&quot;&gt;public float interpolationSmoothing = 1000f;
public float teleportatThreshold = 2f;

void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info) {
  if (stream.isWriting) {
    stream.SendNext(transform.position);
    stream.SendNext(velocity);
  } else {
    syncPosition = (Vector3) stream.ReceiveNext();
    syncVelocity = (Vector3) stream.ReceiveNext();

    lastSyncTime = PhotonNetwork.time;
  }
}

void Update() {
  if (!photonView.isMine) {
    float timeSinceLastUpdate = (float) (PhotonNetwork.time - lastSyncTime);

    float speed = syncVelocity.magnitude &amp;gt;= 1 ? syncVelocity.magnitude : interpolationSmoothing;

    Vector3 extrapolatedPosition = syncPosition + syncVelocity * timeSinceLastUpdate;
    Vector3 newPosition = Vector3.MoveTowards(transform.position, extrapolatedPosition, speed * Time.deltaTime);

    if (Vector3.Distance(transform.position, extrapolatedPosition) &amp;gt; teleportThreshold) {
      newPosition = extrapolatedPosition;
    }

    transform.position = newPosition;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Again, not perfect but good for a prototype. I don’t think I can do much prediction (even though I kind of am in the extrapolation) since players can jump or turn around at any moment.&lt;/p&gt;
&lt;p&gt;Any suggestions? Anything I could read or look over in regards to this? Like I said I have this good for a prototype, but I’m not completely happy with this. Any more learning I can do on the subject would be great!&lt;/p&gt;
&lt;p&gt;Thanks for reading!&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Review Series</title>
    <link href="https://jamiltron.com/2014/12/Review-Series/" />
    <updated>2014-12-04T00:00:00Z</updated>
    <id>https://jamiltron.com/2014/12/Review-Series/</id>
    <content type="html">&lt;p&gt;Since I very rarely blog I have decided that I would like my hand at sort-of reviewing the various gaming and tech books I have been reading. This is both to increase the content of this blog, but also to keep a log of what I have been reading, as well as my thoughts on these books. Hopefully this will also generate discussion so I can further learn about the stuff I have been reading about.&lt;/p&gt;
&lt;p&gt;I intend to try to blog about what I have been reading every week. I will try to keep it to discussing what I have read so far, and what I think. I am hoping this will keep me on track with what I am reading, instead of hoping around from book to book so often, which has been my typical mode for technical books for the past year or so.&lt;/p&gt;
&lt;p&gt;I will start with a book that I read pieces of online, but have just purchased a physical copy of - &lt;a href=&quot;http://gameprogrammingpatterns.com/&quot;&gt;Game Programming Patterns&lt;/a&gt;. This book is wonderfully free, so feel free to read along if you like!&lt;/p&gt;
</content>
  </entry>
  <entry>
    <title>Ludum Dare 29</title>
    <link href="https://jamiltron.com/2014/04/Ludum_Dare/" />
    <updated>2014-04-24T00:00:00Z</updated>
    <id>https://jamiltron.com/2014/04/Ludum_Dare/</id>
    <content type="html">&lt;p&gt;I am very excited to be participating in the &lt;a href=&quot;http://www.ludumdare.com/compo/&quot;&gt;Ludum Dare&lt;/a&gt; 29th 48-hour game jam this weekend. I am going to try to follow the strict “Compo” rules, which is 48-hours only, only using material made during the event, source code required, etc., but I may fall back on the more relaxed 72-hour jam version if I fall behind.&lt;/p&gt;
&lt;p&gt;I am anticipating on using &lt;a href=&quot;http://unity3d.com/&quot;&gt;Unity&lt;/a&gt; for this. In the spirit of “you can only use code you’ve blogged about”, I’ve created a skeleton of a basic Unity game &lt;a href=&quot;https://github.com/jamiltron/ld29&quot;&gt;on my github&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;I look forward to jamming with everyone else participating. Here’s to many great games!&lt;/p&gt;
</content>
  </entry>
</feed>