BROADCAST: The AI in 1849 (November 6th)

by Alex J. Champandard at November 01, 2014 08:00 AM

This upcoming broadcast on Thursday, November 6th at 19:00 UTC will take place online within your browser using streaming audio/video:

“Join us for this interview with Robert Zubek about the rule based city simulation 1849. More details about the exact date of the interview will follow shortly!”

To subscribe for email reminders and check the exact time in your current timezone, visit this broadcast's page on AiGameDev.com.

Xcode Plugin Providing Automatic Configurable Debugger And Utilities Panel Hiding

by Johann at November 01, 2014 06:32 AM

Early this year I mentioned a handy Xcode plugin called BBUDebuggerTuckAway which automatically hides the debugger console when you start typing in the code editor.

Here’s another Xcode 6 plugin for optimizing screen usage called DBSmartPanels that optimizes that automatically hides the debugger and utilities when you don’t need them from Dave Blundell.

The hiding occurs when you open an interface file, open a text document, or start typing in a text document and DBSmartPanels allows you to customize this behavior.

This image from the readme shows the different customization actions available:

You can find DBSmartPanels on Github here.

A nice plugin for hiding the screen real estate.

See More: Xcode Plugins

Be the first to comment...

Example And Guide: An Optimized Reaction Diffusion Simulation Using The Metal Graphics API

by Johann at November 01, 2014 12:46 AM

In the last couple of months I mentioned an extensive collection of iOS 8 source code including some examples using Metal along with an in-depth beginners tutorial on using Metal.

Here’s a guide and example submitted by Simon Gladman in which he has created and optimized a reaction diffusion simulation using the Metal API.

This video shows the simulation in action:

There are three guides explaining the creation of this example covering the initialisation of metal through to optimizing the project to the point where 1,000 reaction diffusion solver iterations per second are displayed on an iPad Air 2.

You can find the three parts to the tutorial on the FlexMonkey blog: Part 1, Part 2, Part 3

You can find the Metal Reaction Diffusion Example source code on Github here.

A nice example of some high performance programming using the Metal framework.

Be the first to comment...

CppCon 2014: Mike Acton "Data-Oriented Design and C++"

by Timothy Lottes (noreply@blogger.com) at October 31, 2014 10:04 PM

Guide to Creating a Game On iPad -- Vector Graphics in Codea

by Mike@gamefromscratch.com at October 31, 2014 03:22 PM

Now that we know how to create vector graphics on iPad, let's take a look at the process of getting them into and using them in Codea.  This part is insanely easy, in fact if this was all there was to it, I could cover this entire process in a single Tweet!  Let’s do it.

First of course you need to create a vector graphic in some application and save it as PDF to your Dropbox folder.

Then fire up Codea, create a new project with the following code:

function draw()
background(40, 40, 50)
sprite("Dropbox:Jet",WIDTH/2,HEIGHT/2)
end


Yeah... that's it.  Select the image from your Dropbox, run it and you will see:

So basically vectors are treated exactly the same as bitmaps as far as Codea is concern.  Well, with a few exceptions… you can scale them as much as you want and never lose visual fidelity.

You can scale by passing in the width and height to the sprite call, like so:

sprite("Dropbox:Jet",WIDTH/2,HEIGHT/2,100,100)


So then, vectors are easy to load, look great, scale well are pretty easy to draw... perfect no?

Well… no, there is a catch.  Performance.

Let’s take a quick look at how vectors perform, using the following code:

-- VectorTest
function setup()
fontSize(160)
fill(255, 0, 25, 255)
end

function draw()
background(40, 40, 50)

local outString = "fps:" .. math.floor( 1/DeltaTime)
local dimensions = textSize(outString)

strokeWidth(5)

for i= 1,100 do
local x = math.random(WIDTH)
local y = math.random(HEIGHT)
sprite("Dropbox:Jet 2",x,y)
end

text(outString,WIDTH-dimensions/2,80)
end


Here it is running on my iPad Air with drawing 100 vectors:

60 FPS is as good as we can get, so so far so good!  Now lets see what happens when we crank the number up to 500.

Oh…

From my tests, you can draw about 200 vector images before framerate starts to drop down.  You can easily draw twice that many normal sprites without seeing a noticeable drop in framerate.

Right now our simple frame rate counter is changing far too often to be of much use.  So instead I am going to sample and average across minutes.  Basically every frame we take a sampling of framerate, after a second elapses we move that sample to other array, average and display the results.  So basically we sample the data per frame, but average it out over the span of a second.  This should give us a much smoother frame rate total.  Here is the updated code:

-- VectorTest
frameRateSamples = { 60 }
fpsSampledPerSecond = { 60 }
elapsedTime = 0

function setup()
fontSize(160)
fill(255, 0, 25, 255)
end

function mean( t )
local sum = 0
local count= 0

for k,v in pairs(t) do
if type(v) == 'number' then
sum = sum + v
count = count + 1
end
end

return math.floor(sum / count)
end

function draw()
background(40, 40, 50)

elapsedTime = elapsedTime + DeltaTime
if(elapsedTime < 1) then
table.insert(frameRateSamples,math.floor(1/DeltaTime))
else
print("Second elapsed")
table.insert(fpsSampledPerSecond,mean(frameRateSamples))
framerateSamples = {}
elapsedTime = 0
-- ever 360 seconds reset the table so it doesnt grow forever
if #fpsSampledPerSecond > 360 then
fpsSampledPerSecond = { 60 }
end
end

local outString = "fps:" .. mean(fpsSampledPerSecond)
local dimensions = textSize(outString)

strokeWidth(5)

for i= 1,200 do
local x = math.random(WIDTH)
local y = math.random(HEIGHT)
sprite(“YourImageHere",x,y)
end

text(outString,WIDTH-dimensions/2,80)
end



Now when we run it, we get the follow values, after letting each run for over 60 seconds to take the seed value out of the equation:

 Image Type FPS at 100 FPS at 250 FPS at 500 FPS at 1000 FPS at 1500 FPS at 2000 Vector 58 38 21 23 15 9 Bitmap 58 37 21 21 17 10

Hmmm, that's interesting.  So once the framerate sampling is smoothed out, the performance between vector and bitmap graphics is basically identical.  In both cases too, oddly enough, 500 sprites caused a drop in performance compared to 1,000…  very very very odd.

Now let’s take a look at if scaling is a factor.  In this test we will scale the vector down to 32x32, vs drawing a fixed 32x32 sprite and see if it impacts performance.

As a 32x32 pixel image, at 2000 sprites, the framerate a solid 57.

As a vector scaled down to 32x32 in the sprite call the framerate at 2000 sprites is 57.

There you have it, contrary to my initial findings, the performance between identically sized bitmap and vector images in Codea is about the same.  Internally, Codea must be rasterizing vectors before drawing them.

So, why did my initial tests show a massive improvement in bitmap performance over vectors as the count increased?  Well, that’s because I compared apples to oranges… I used a “nearly the same dimensions” graphic for the test, and that was a huge mistake. Something critical you can take away from this experiment is the size of the sprite being blitted has a huge impact on performance, much more so than the type of sprite.  As you saw above, we can blit > 2000 32x32 pixel images without a drop in performance, while the same number of 200x200 pixel images brings it to it’s knees.

So, in a nutshell, its equally as valid to use a vector with code than it is a bitmap.  And as you can see, it uses the exact same code.  Oh, and if you are by chance wondering why we were toping out at 57-58FPS instead of 60 you would expect, that is simply because I floored() the results (aka, rounded down) to make the numbers prettier.  Since I was measuring relative performance, not overall performance, the actual framerate really didn’t matter all that much.

Open Source iOS Framework For Easily Creating Node Based Visual Editors

by Johann at October 31, 2014 06:30 AM

Last week I mentioned a great open source library from Krzysztof Zablocki for creating playgrounds in objective-c.

Here’s another interesting open source project from Krzyszstof providing a framework for creating node based visual editors very easily called KZNodes.

With KZNodes you can easily create nodes, attach, and modify those nodes visually, and see the results in real-time. This is great if you would like to create a simple editor for your designer to tweak visual components within an app, or you could even create an editor for users of your apps.

This video demonstration from Krzyszstof provides a nice overview of KZNodes and some possible uses.

You can find KZNodes on Github here.

A great framework for creating visual editors.

Be the first to comment...

Swift Based ActiveRecord/MagicalRecord Helpers For Working With Core Data

by Johann at October 30, 2014 07:50 PM

Earlier this month I mentioned a nice Swift library for working with SQLite databases and I’ve also mentioned a nice Swift based helper library for working with Core Data called AlecrimCoreData.

Here’s another open source Swift library that provides a number of helpers and extensions inspired by the Active Record pattern and MagicalRecord for Core Data called SuperRecord from Michael Armstrong.

Included within SuperRecord are a number of ActiveRecord inspired finders including some very nice helpers for performing batch updates that work with UITableView, and UICollectionView.

You can find SuperRecord on Github here.

A nice set of Active Record inspired helpers created in Swift.

Be the first to comment...

Maxwell GM204 OpenGL Extensions

October 30, 2014 11:20 AM

Cyril Crassin discusses the new OpenGL extensions supported by NVIDIA’s latest Maxwell 2 generation of GPUs such as the GeForce 980 GTX. NVIDIA’s latest GameWorks SDK provides example code for some of these extensions.

Open Source iOS Library Extending UITextView With Annotations, A Change API And More

by Johann at October 30, 2014 06:25 AM

Last month I mentioned a nice library from the LinkedIn engineering team for easily scheduling bakcground fetches called Selene.

Here’s an interesting open source library from the Linkedin engineering team called Hakawai that greatly extends the functionality of UITextView.

Added with Hawakai is a nice high-level change api that offers more than UITextViewDelegate, block-based APIs for working with text view contents, special social media style annotations within the view, and more.

This is a listing of the Hawakai features as stated in the readme:

- A convenient drop-in replacement for UITextView instances, including those in Storyboards or XIBs.
- Easily add, remove, and transform the text view’s plain and attributed text using a set of powerful block-based APIs.
- Work with attribute formatting and easily register or unregister custom attributes with enhanced attribute APIs.
- Easily add, remove, and manage accessory views, UI elements that can be added to or removed from the text view for additional functionality.
- Lock the current line of text to the top or the bottom of the text view using single-line viewport mode.
- Programmatically dismiss autocorrect suggestions, and temporarily override the autocorrect, autocorrection, and spell checking modes.
- Extend functionality by registering or unregistering plug-ins.
- Custom ’rounded rect background’ attribute, and a custom layout manager allowing additional attributes to be defined.
- The fact that this text view implements a custom layout manager and text container fixes several UITextView bugs by default.
- EXPERIMENTAL – Easily monitor user changes to the text view’s contents using the optional Abstraction Layer; two-stage insertion for Chinese and Japanese keyboards is also properly handled. The Abstraction Layer is built into the text view; it can also be pulled out and used independently if you desire.

You can find Hakawai on Github here.

You can read more about Hakawai on the Linkedin Engineering blog.

An nice enhanced version of the UITextView.

Be the first to comment...

CfP: Optimization of Parallel Scientific Applications with Accelerated HPC

by dom at October 29, 2014 10:09 PM

Since 2011, the most powerful supercomputers systems ranked in the Top500 list have been hybrid systems composed of thousands of nodes that includes CPUs and accelerators, as Xeon Phi and GPUs. Programming and deploying applications on those systems is still a challenge due to complexity of the system and the need to mix several programming interfaces (MPI, CUDA, Intel Xeon Phi) in the same application. This special issue of the International Journal of Computers & Electrical Engineering is aimed at exploring the state of the art of developing applications in accelerated massive HPC architectures, including practical issues of hybrid usage models with MPI, OpenMP, and other accelerators programming models. The idea is to publish novel work on the use of available programming interfaces (MPI, CUDA, Intel Xeon Phi) and tools for code development, application performance optimizations, application deployment on accelerated systems, as well as the advantages and limitations of accelerated HPC systems. Experiences with real-world applications, including scientific computing, numerical simulations, healthcare, energy, data-analysis, etc. are also encouraged.

The topics of specific interest for this Special Issue include the following:

• Hybrid and heterogeneous programming with MPI and accelerators
• Performance evaluation of scientific applications based on accelerators
• Automatic performance tuning of scientific applications with accelerators
• Integrating accelerators on existing HPC run-times and middleware
• Energy efficient HPC solutions based on accelerators
• Storage cache solutions based on SSD accelerators
• Real-world scientific and engineering applications using accelerated HPC

The special issue will invite extended versions of the best papers of ESAA 2014, “International Workshop on Enhancing Parallel Scientific Applications with Accelerated HPC” at the EuroMPI/Asia 2014 on September 2014 in Kyoto, but it is also open to other authors. For work that has been published previously in the workshop or conference, it is required that submissions to the special issue have at least 30% new content/contribution. Each submission will be peer-reviewed to ensure a very high quality of papers selected for the Special Issue.

CfP: GPGPU 2015

by dom at October 29, 2014 10:02 PM

The goal of this workshop is to provide a forum to discuss new and emerging general-purpose purpose programming environments and platforms, as well as evaluate applications that have been able to harness the horsepower provided by these platforms. This year’s work is particularly interested on new heterogeneous GPU platforms, new forms of concurrency, and novel/irregular applications that can leverage these platforms. Papers are being sought on many aspects of GPUs, including (but not limited to):

• GPU applications
• GPU programming environments
• GPU runtime systems
• GPU compilation
• GPU architectures
• Multi-GPU systems
• GPU power/efficiency
• GPU reliability
• GPU benchmarking/measurements
• Heterogeneous GPU platforms that incorporate GPUs

Papers are due on December 1, 2014, and all submissions must be made electronically through the conference web site. For details, contact David Kaeli (kaeli@ece.neu.edu).

Creating Vector Game Art using iDraw on iPad

by Mike@gamefromscratch.com at October 29, 2014 08:26 PM

As part of the ongoing Guide to Creating a Game Entirely on an iPad series, we recently looked at a number of 2D raster and vector graphics programs available on iOS.  One of the programs that really stood out was iDraw, a vector drawing program.  I’ve actually used iDraw for a while now, going back to the concept art I did for the Blender tutorial series and I am certainly a fan.  Although both Inkscape (Desktop) and Inkpad (iPad) are available for free, I find both to be pretty unwieldy at times.  iDraw just hits that sweet spot between usability and functionality, at least for me.

In this video I take a more in-depth look at iDraw.

In this video I show the functionality available in iDraw.  THe first half of the video I complete this game art tutorial that was written for Inkscape, so if you are familiar with Inkscape, you can see how iDraw works at the same task.  If you’ve got no experience with vector graphics at all, this video should certainly give you the basics.   The last half of the video is a tour of iDraw’s additional functionality.

If you have a Mac or iPad and are looking for a vector graphics solution, iDraw is certainly worth checking out.  iDraw is available for $8.99 on the AppStore for iPad, while it is also available (with almost identical functionality) on the Mac for$24.99.   If you are looking for a tutorial on creating vector graphics, or are looking for more details on using vector graphics for game dev, 2dgameartforprogrammers is a great resource you should check out.

… I still hate the name iDraw though.  I hate an irrational hatred for all iNaming iProducts, I think many others do too!  Get over the name though and you will find an excellent product.

Next up, I will look at using Vector graphics from a Codea code perspective, to see how it’s done and what the performance is like.  Stay tuned!

Open Source Swift Based Component For Creating Customizable Progress Indicators With UIBezierPath

by Johann at October 29, 2014 07:47 PM

Previously I mentioned a nice objective-c based open source library that includes many different styles of progress indicators called M13ProgressSuite.

Here’s an open source Swift based component allowing you to create customizable progress indicators in Swift called KYCircularProgress from Kenji Yokoyama.

KYCircularProgress allows you to easily create circular progress indicators, or you can create progress indicators with a completely custom appearance using UIBezierPath. You can also specify whether to use a line fill or a gradient style of fill.

Here’s an image from the readme showing several progress indicators created with KYCircularProgress:

You can find KYCircularProgress on Github here.

A nice component for creating customizable progress indicators.

Be the first to comment...

Windy Trees: Computing Stress Response for Developmental Tree Models

by christopherbatty at October 29, 2014 06:49 PM

Sören Pirk, Till Niese, Torsten Hädrich, Bedrich Benes, Oliver Deussen

We present a novel method for combining developmental tree models with turbulent wind fields. The tree geometry is created from internal growth functions of the developmental model and its response to external stress is induced by a physically-plausible wind field that is simulated by Smoothed Particle Hydrodynamics (SPH). Our tree models are dynamically evolving complex systems that (1) react in real-time to high-frequent changes of the wind simulation; and (2) adapt to long-term wind stress. We extend this process by wind-related effects such as branch breaking as well as bud abrasion and drying. In our interactive system the user can adjust the parameters of the growth model, modify wind properties and resulting forces, and define the tree’s long-term response to wind. By using graphics hardware, our implementation runs at interactive rates for moderately large scenes composed of up to 20 tree models.

Windy Trees: Computing Stress Response for Developmental Tree Models

IGDA Webinar: Kickstarter

by noreply@blogger.com (Sande Chen) at October 29, 2014 02:40 PM

In this video, Howard Tsao, Team Lead of Muse Games, describes how Muse Games created successful Kickstarter campaigns to fund Guns of Icarus Online, its multiplayer airship combat game.

Remember to sign up for the next Game Design Webinar November 19 on the evolution of game design. Creative Producer Patrick Holleman presents the history of game design from Dungeons & Dragons to the modern era.

Adventures in Phaser with TypeScript–Tilemaps Part 2 Now with more stuff!

by Mike@gamefromscratch.com at October 29, 2014 01:22 PM

In the previous tutorial we took a look at creating, loading and displaying a tilemap in Phaser and for many simple projects this may be enough.  That said, there are two very common scenarios this doesn’t really address, and we will look at those in this tutorial.  The first is positioning a sprite within a tilemap.  The second is collision detections between tiles and sprites.

Placing a sprite within a tilemap is a pretty common behavior, but the way you deal with it isn’t immediately obvious in Phaser.  To understand what I am going on about it’s good to understand how layers of tilemaps work.  You may recall in our previous example, our tilemap was composed on three layers, one for the background, one for the midground (a word I apparently made up) and one for the foreground.  Basically the background is where you would put the stuff that happens behind the scene, things like clouds or the blue sky for example.  The midground is generally where the bulk of the stuff in your world would go.  The foreground then is the stuff drawn on top of the midground.

Quite often your playersprite will then be drawn in front of the foreground.  That said, what happens when your player is behind something in the world, such as say… a shrubbery?  How do we deal with this?  Well first, let’s visualize how the layers of a tilemap come together.

No better way than an image, right?

Think of each layer of tiles as sheets laid one over the next.  The top most layer obscuring the contents behind it, and that layer obscuring the contents behind it.

So, in Phaser, what determines draw order?  Simple, the order they were added in.  Change the order layers are drawn, you change what draws on top of what.  Know this then, how do we could we for example draw our character sprite between the foreground and midground layer so it appears behind the chandelier, like so:

The answer is actually quite simple but possibly a bit confusing, let’s look at the code:

/// <reference path="phaser.d.ts"/>
class SimpleGame {
game: Phaser.Game;
map: Phaser.Tilemap;
player: Phaser.Sprite;

constructor() {
this.game = new Phaser.Game(640, 480, Phaser.AUTO, 'content', {
});
}
this.game.load.tilemap("ItsTheMap", "map.json", null, Phaser.Tilemap.TILED_JSON);
}
render() {

}
create() {
this.map = this.game.add.tilemap("ItsTheMap", 32, 32, 50, 20);

this.map.createLayer("Background").resizeWorld();
this.map.createLayer("Midground");
this.map.createLayer("Foreground");

this.player = new Phaser.Sprite(this.game,200,50,"Decepticon");
}
}

window.onload = () => {
var game = new SimpleGame();
};

And when we run it:

Note the order we called createLayer matches the order we want the layers drawn, from back to front.  After that we load our sprite then do something a bit different from what we’ve done in the past.  Previously we just added Sprites using this.game.add().  Now however we want a bit more control of where they are added.  This is why we created our Sprite instead using new, then explicitly added it to the world using addAt().  By adding it at index 2 ( the 3rd item ) this means we will be between the mid and foreground in the world list.

You should be aware however that this is incredibly fragile an approach.  You can only rely on layers being where they are because they are the only other objects we’ve created.  In a non-trivial example, you will dozens or hundreds of other objects in your scene, this may not be as easy to figure out.  There are of course alternatives.  One of the easiest, and possibly crudest options, would be too iterate through the world, find the index of layer you want to insert before and then insert like so:

        var index: number;
this.game.world.forEach((child) => {
index++;
if (child.layer.name = "Foreground")
index = child.index;
}, this, false);
this.game.world.addAt(this.player, index);

I suppose I should point out this particular solution iterates through every item in the world, even if the first child is what you are looking for. Also, it doesn't take into account the possibility that the given child doesn't even exist, which is probably a bad idea. That all said, I think you get the gist of how this works.  As you may notice, the world variable is pretty important, as essentially it is the scene graph, the source of all things to be rendered.  At the end of the day though, it’s just a group that we covered earlier.

Ok… that was a really long way of saying the order you add things to the world is really important… let’s move on, collisions.

Quite often you are going to want to test to see if “stuff” (scientific term there… ) hits other “stuff”.  In this particular case, we want to see if our game sprite collides with the “floor”.  First lets take a look at adding physics to our game sprite.  I’ve used physics in past tutorials, but havent gone into detail how these things work… and I am not going to here either.  For now just think of it as the work of moon wizards.  I will cover physics at a later point, I promise!

So, back to enabling physics and gravity for game sprites.  Here’s how:

    create() {
// Enable the physics system in Phaser
this.map = this.game.add.tilemap("ItsTheMap", 32, 32, 50, 20);

this.map.createLayer("Background").resizeWorld();
var world = this.map.createLayer("Midground");
this.map.createLayer("Foreground");

this.player = new Phaser.Sprite(this.game, 200, 50, "Decepticon");
// Apply physics to our game sprite
// Turn on gravity.  10pixels / second along the y axis
this.player.body.gravity.y = 10;

}

The comments explain the basics of what’s going on, like I said, I will go into a bit more detail later.  Now if you run the code with the above changes the player sprite ( the Decepticon logo ) will slowly fall to the bottom of the screen, to infinity and beyond.

Now what we would prefer to see is the sprite stop when it collided with the tiles composing the floor.  This takes a bit of understanding of how tilemaps are actually stored as data.  Open up map.json and you will see a layer contains an array called data full of tiles that make up the layer, like so:

Each of those indices present a location within your sprite image.  Let’s take a look back in Tiled for a second.

You can see the ID of each tile by simply clicking it in the Tilesets window.  In this case we are going to want the ID of each red topped brick.  Specifically we want the ID of the tiles that make up these particular tiles

In my particular case, the IDs were 32,33,34,35 and 36.  Now that we know the IDs of the tiles we want to collide with, lets set that up.  Code time!

/// <reference path="phaser.d.ts"/>
class SimpleGame {
game: Phaser.Game;
map: Phaser.Tilemap;
layer: Phaser.TilemapLayer;
player: Phaser.Sprite;

constructor() {
this.game = new Phaser.Game(640, 480, Phaser.AUTO, 'content', {
});
}
this.game.load.tilemap("ItsTheMap", "map.json", null, Phaser.Tilemap.TILED_JSON);
}
update() {
// You actually need to perform the collision test between the map and player sprite
}
render() {
// Display the outline of the physics body
this.game.debug.body(this.player);
}
create() {
// Enable the physics system in Phaser
this.map = this.game.add.tilemap("ItsTheMap", 32, 32, 50, 20);

this.map.createLayer("Background").resizeWorld();
this.layer = this.map.createLayer("Midground");
this.map.createLayer("Foreground");

this.player = new Phaser.Sprite(this.game, 200, 40, "Decepticon");
// Apply physics to our game sprite
// Turn on gravity.  10pixels / second along the y axis
this.player.body.gravity.y = 10;
this.player.body.collideWorldBounds = true;

// Now setup the tiles in our midground layer for collisions
// When using multiple layers it is critical you specify the layer the collisions occur on!
this.map.setCollisionBetween(32, 36,true,this.layer.index,true);

// Add a keyboard handler on 'R' pressed the resets the sprite to it's starting position
this.player.position.set(200, 40);
});
}
}

window.onload = () => {
var game = new SimpleGame();
};

Here is the code running.

No IFrame for you!

Click in the IFrame and press R to reset the sprite to it’s starting position.

Most of the important bits are commented in the source code, but a few things are worth noting.  The most important is how you add collision tests to individual tiles within the world.  As mentioned earlier, you need the tile ID of the tile within the layer.  You then use setCollision methods to mark which tiles perform collisions.  In this example we used setCollisionBetween() which allows you to specify a range of tiles to collide with.  There is also a version that takes an individual tile ID as well as one that takes an array.  The critical part of this call is you have to provide the layer where the collision takes place.  Also of importance is the call to physics.arcade.collide() which tells Phaser to check for a collision between that layer and your player sprite.

One other thing you may notice is in render(), I call game.debug.body(this.player).  This causes the renderer to draw a bounding box around the physics shape of our sprite.  This is important because it exposes a very common bug that I thought I would address.  Notice when you run the applicaion, once gravity is done, our image is resting above the ground like this:

This is because our source image has some empty pixels.  The physics bounding volume is going to be around the entire sprite, not just drawn pixels.  If you are using physics, be sure your image is cropped as much as possible!

So that illustrates how to insert a sprite between tilemap layers and how to perform collisions against tiles.  That should be the majority of what you need to get started using tilemaps.

Before we continue, I should answer a commonly asked question.  What about isometric maps?  Yes, Tiled can export isometric tilemaps, but currently Phaser does not support them.  There are some third party code samples to load them, but nothing in the core as of yet.

Code Example: An iPhone Springboard Protoype Based On The Apple Watch

by Johann at October 29, 2014 06:19 AM

Last month I mentioned an extensive Apple Watch GUI PSD Design Kit for those looking to get an early start on designing for the Apple Watch.

Here’s an interesting source code example from Lucas Menge bringing an Apple Watch style home screen to the iPhone called WatchSpringboard-Protoype.

The example provides the same icon layout as on the apple watch, interactivity features, app opening transitions and many nice touches to make things work right on the iPhone.

Here’s a video showing the WatchSpringboard-Prototype in action:

You can find the source code WatchSpringboard-Prototype on Github here.

A nice example showing how well this style of layout could work on the iPhone.

Be the first to comment...

Open Source Library For Easily Creating A Custom Touch ID Or Passcode Lock Screen

by Johann at October 28, 2014 07:18 PM

Last month I mentioned a nice tutorial on integrating Touch ID within an app.

Here’s an open source linbrary from Venmo providing an easy way to set up a custom Touch ID or passcode lock screen from Venmo called VenTouchLock.

With VenTouchLock you create a splash screen (a sample is included), and your users will need to specify a passcode elsewhere in your app. On the lock screen the user will be able to unlock using touch on devices where Touch ID is available or they can also use the passcode.

This animation shows VenTouchLock in action:

You can find VENTouchLock on Github here.

A nice library for easily setting up a Touch ID based lock screen.

Be the first to comment...

Re-using actions in LibGDX

by Mike@gamefromscratch.com at October 28, 2014 04:56 PM

A question came up in a comment in the Scene2D part of the LibGDX tutorial series about re-using actions.  You very much can re-use actions, so I decided to do it in post form here.  This entire post is mostly just one large code sample.  It’s just easier to do it here than in comments.  For a greater context of what this code is doing, see the earlier linked tutorial section.

Here is a sample showing action re-use.

package com.gamefromscratch;

public class Scenetest implements ApplicationListener, InputProcessor {

public class MyActor extends Actor {
Texture texture = new Texture(Gdx.files.internal("badlogic.jpg"));

public MyActor(){
setBounds(getX(),getY(),texture.getWidth(),texture.getHeight());
}

@Override
public void draw(Batch batch, float alpha){
batch.draw(texture,this.getX(),getY());
}
}

private Stage stage;
private MyActor myActor;
MoveToAction moveToOrigin,moveToCenter;

@Override
public void create() {
stage = new Stage();
myActor = new MyActor();

myActor.setPosition(Gdx.graphics.getWidth()/2 - myActor.getWidth()/2,
Gdx.graphics.getHeight()/2 - myActor.getHeight()/2);

moveToOrigin = new MoveToAction();
moveToOrigin.setPosition(0f, 0f);
moveToOrigin.setDuration(2f);

moveToCenter = new MoveToAction();
moveToCenter.setPosition(Gdx.graphics.getWidth()/2 - myActor.getWidth()/2,
Gdx.graphics.getHeight()/2 - myActor.getHeight()/2);
moveToCenter.setDuration(2f);

Gdx.input.setInputProcessor(this);
}

@Override
public void dispose() {
}

@Override
public void render() {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();
}

@Override
public void resize(int width, int height) {
}

@Override
public void pause() {
}

@Override
public void resume() {
}

@Override
public boolean keyDown(int keycode) {
if(keycode == Input.Keys.NUM_1)
if(myActor.getActions().contains(moveToOrigin,true)) {
// this is "A" currently running action, do nothing
// If you wanted you could restart the action which
// would cause the duration to start over, like so:
moveToOrigin.restart();
// This action will now have a 2 second tween between
// its current location and target
}
else {
moveToOrigin.reset();
}
if(keycode == Input.Keys.NUM_2)
if(myActor.getActions().contains(moveToCenter,true)) {
// this is "A" currently running action so do nothing
}
else {
moveToCenter.reset();
}
return false;
}

@Override
public boolean keyUp(int keycode) {
return false;
}

@Override
public boolean keyTyped(char character) {
return false;
}

@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
return false;
}

@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
return false;
}

@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
return false;
}

@Override
public boolean mouseMoved(int screenX, int screenY) {
return false;
}

@Override
public boolean scrolled(int amount) {
return false;
}
}

When you run this code, the graphic will start at the center of the screen and move towards the origin, with a total duration of 2 seconds.  If you press the 2 key, it will start an action to move back to the center of the screen.  Pressing 1 will move back to the origin.  Pressing 1 while a moveToOrigin is active will cause that action to restart, basically resetting the total duration back to 2 seconds again, just from your current position.

The only things to really be aware of here are that an Actor getActions() will only return actions that are currently run.  When the action is finished, it is removed from the Actor.  The other thing of note is, although you can reuse an Action, you will have to reset() it before you can add it again, or it will already be over.  If it is currently run, calling restart() has the same effect as resetting.

Intercepting a Moving Target in 2D

October 28, 2014 11:17 AM

You often have to have an entity controlled by an AI "shoot" at something in a 2D game. By "shoot" here, I mean launch something towards another moving something in the hopes that it will intercept it. This may be a bullet, a grenade, or trying to jump to a moving platform. If the target is moving, shooting at the current position (1) will usually miss except in trivial cases and (2) make your entity look dumb. When you play hide and seek, you don't run to where the person is unless they are stopped. You run to where the (moving) thing you are chasing is going to be.

There are two cases for "shooting" at something:

1. Non-Rotating Shooter
2. Rotating Shooter

This article only covers the case of the non-rotating shooter. The second case is a bit more complicated. I'll post a separate article for that.

Your goal is to predict the future position of the target so that you can launch something at it and have them collide. It is given that you know the following:

1. The position of the shooter when the projectile will be launched: $$\vec{P_s}$$
2. The position of the target when the shooter will launch the projectile (i.e. now): $$\vec{P_T^0}$$
3. The speed at which your projectiles travel: $$S_b$$
4. The velocity of the target, $$\vec{v_T}$$

What you would like to find is $$\vec{P_T^1}$$, the final position where the projectile will intercept the target.

We are going to have to assume that the target will travel at a constant velocity while the projectile is moving. Without this, the projectile will have to adapt after it has been launched (because it cannot predict the future position of the target if it is changing velocity in an unpredictable way). It should be pointed out that this is not limiting and in fact, still works out pretty well as long as the "edges" are handled well (target right in front of you or headed straight at you).

The Problem Space

Consider the image below:

This image shows the situation for the shooter. The target is moving with some constant velocity and the intercept position for the projectile, when launched, is unknown until the calculation is done. When the projectile is launched, it will intercept the target after $$t_B$$ seconds. The projectile is launched with a constant speed. We don't know its direction yet, but we know the magnitude of its velocity, its speed will be $$S_b$$.

If the target is at position $$\vec{P_T^0}$$ now, it will be at position $$\vec{P_T^1}$$, given by:

(1) $$\vec{P_T^1} = \vec{P_T^0} + \vec{v_T} * t_B$$

Since the projectile will have traveled for the same amount of time, it will have moved from $$\vec{P_s}$$ to $$\vec{P_T^1}$$ as well. In that time, it will have moved a distance of $$S_B x t_B$$. Since we are talking about vector quantities here, we can write this as:

$$\mid\vec{P_T^1}-\vec{P_s}\mid = S_b * t_B$$

If we square both sides and break it into components to get rid of the absolute value:

(2) $$(P_{Tx}^1 - P_{Sx})^2 +(P_{Ty}^1 - P_{Sy})^2 = S_b^2 * t_B^2$$

Breaking (1) into components as well and substituting back into (2) for the value of $$P_{Tx}^1$$ and $$P_{Ty}^1$$, we get the following:

$$(P_{T0x} - P_{Sx} + v_{Tx}t_B)^2 + (P_{T0y} - P_{Sy} + v_{Ty}t_B)^2 = S_b^2 * t_B^2$$

For the sake of simplicity, we going to redefine:

$$P_T^0 - P_s = R$$(this is a constant)

After some algebra, this gives us the final equation:

$$t_B^2(v_{Tx}^2 + v_{Ty}^2-S_B^2) + t_B(2*R_x*v_{Tx} + 2*R_y*v_{Ty}) + (R_x^2 + R_y^2) = 0$$

This is a quadratic in $$t_B$$:

$$t_b = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$

where:

$$a =v_{Tx}^2 + v_y^2-S_B^2$$

$$b =2(R_x*v_{Tx} + R_y*v_{Ty})$$

$$c = R_x^2 + R_y^2$$

You can test the discriminant, $$b^2-4ac$$:

0 $$\Rightarrow$$ No Solution.

1 $$\Rightarrow$$ One solution.

2 $$\Rightarrow$$ Two solutions, pick the lowest value of $$t_B$$.

Once you have solved the quadratic for $$t_B$$, you can then substitute it back into (1) and calculate the intercept position, $$\vec{P_T^1}$$.

Article Update Log

28 Oct 2014: Initial Release