Planet Gamedev

Game AI for Developers

BROADCAST: The AI in 1849 (November 6th)

by Alex J. Champandard at October 31, 2014 03:00 PM

BROADCAST: The AI in 1849 (November 6th)

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.

iPhone Development Tutorials and Programming Tips

Open Source iOS Framework For Easily Creating Node Based Visual Editors

by Johann at October 31, 2014 06:30 AM

Post Category    Featured iPhone Development Resources,iOS Development Libraries,Objective-C,Open Source iOS Libraries And Tools

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...

Related Posts:

FacebookTwitterDiggStumbleUponGoogle Plus

Original article: Open Source iOS Framework For Easily Creating Node Based Visual Editors

©2014 iOS App Dev Libraries, Controls, Tutorials, Examples and Tools. All Rights Reserved.

iPhone Development Tutorials and Programming Tips

Swift Based ActiveRecord/MagicalRecord Helpers For Working With Core Data

by Johann at October 30, 2014 07:50 PM

Post Category    Featured iPhone Development Resources,iOS Development Libraries,Open Source iOS Libraries And Tools,Swift

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...

Related Posts:

FacebookTwitterDiggStumbleUponGoogle Plus

Original article: Swift Based ActiveRecord/MagicalRecord Helpers For Working With Core Data

©2014 iOS App Dev Libraries, Controls, Tutorials, Examples and Tools. All Rights Reserved.



OpenGL

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.

iPhone Development Tutorials and Programming Tips

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

by Johann at October 30, 2014 06:25 AM

Post Category    Featured iPhone Development Resources,iOS Development Libraries,Objective-C,Open Source iOS Libraries And Tools

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...

Related Posts:

FacebookTwitterDiggStumbleUponGoogle Plus

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

©2014 iOS App Dev Libraries, Controls, Tutorials, Examples and Tools. All Rights Reserved.

GPGPU.org

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.

More info at: www.journals.elsevier.com/computers-and-electrical-engineering/call-for-papers/cfp-optimization-of-parallel-scientific-applications-with-ac



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).

Game From Scratch

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 onidraw_large_icon 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!

iPhone Development Tutorials and Programming Tips

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

by Johann at October 29, 2014 07:47 PM

Post Category    Featured iPhone Development Resources,iOS UI Controls,iPad,iPhone,Swift

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:

KYCircularProgress

You can find KYCircularProgress on Github here.

A nice component for creating customizable progress indicators.


Be the first to comment...

Related Posts:

FacebookTwitterDiggStumbleUponGoogle Plus

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

©2014 iOS App Dev Libraries, Controls, Tutorials, Examples and Tools. All Rights Reserved.



Physics-Based Animation

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

Game Design Aspect of the Month

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.

Game From Scratch

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?

 

Layers

 

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:

 

 

Layers2

 

 

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', {
            create: this.create, preload:
            this.preload, render: this.render
        });
    }
    preload() {
        this.game.load.tilemap("ItsTheMap", "map.json", null, Phaser.Tilemap.TILED_JSON);
        this.game.load.image("Tiles", "castle_0.png");
        this.game.load.image("Decepticon", "decepticonLarge.png");
    }
    render() {

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

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

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

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

 

And when we run it:

image

 

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.game.physics.startSystem(Phaser.Physics.ARCADE);
        this.map = this.game.add.tilemap("ItsTheMap", 32, 32, 50, 20);
        this.map.addTilesetImage("castle_0", "Tiles");

        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
        this.game.physics.enable(this.player, Phaser.Physics.ARCADE);
        // Turn on gravity.  10pixels / second along the y axis
        this.player.body.gravity.y = 10;

        this.game.world.addAt(this.player, 3);
    }

 

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:

 

image

 

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

 

image

 

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

 

image

 

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', {
            create: this.create, preload:
            this.preload,update:this.update, render: this.render
        });
    }
    preload() {
        this.game.load.tilemap("ItsTheMap", "map.json", null, Phaser.Tilemap.TILED_JSON);
        this.game.load.image("Tiles", "castle_0.png");
        this.game.load.image("Decepticon", "decepticonLarge.png");
    }
    update() {
        // You actually need to perform the collision test between the map and player sprite
        this.game.physics.arcade.collide(this.player, this.layer);
    }
    render() {
        // Display the outline of the physics body
        this.game.debug.body(this.player);
    }
    create() {
        // Enable the physics system in Phaser
        this.game.physics.startSystem(Phaser.Physics.ARCADE);
        this.map = this.game.add.tilemap("ItsTheMap", 32, 32, 50, 20);
        this.map.addTilesetImage("castle_0", "Tiles");

        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
        this.game.physics.enable(this.player, Phaser.Physics.ARCADE);
        // 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);
        

        this.game.world.addAt(this.player, 2);

        // Add a keyboard handler on 'R' pressed the resets the sprite to it's starting position
        this.game.input.keyboard.addKey(Phaser.Keyboard.R).onUp.add(() => {
            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:

 

image

 

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.

 



iPhone Development Tutorials and Programming Tips

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

by Johann at October 29, 2014 06:19 AM

Post Category    Featured iPhone Development Resources,iOS Development Source Code Examples,Objective-C

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...

Related Posts:

FacebookTwitterDiggStumbleUponGoogle Plus

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

©2014 iOS App Dev Libraries, Controls, Tutorials, Examples and Tools. All Rights Reserved.

iPhone Development Tutorials and Programming Tips

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

by Johann at October 28, 2014 07:18 PM

Post Category    Featured iPhone Development Resources,iOS Development Libraries,Objective-C,Open Source iOS Libraries And Tools

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:
VENTouchLock

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...

Related Posts:

FacebookTwitterDiggStumbleUponGoogle Plus

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

©2014 iOS App Dev Libraries, Controls, Tutorials, Examples and Tools. All Rights Reserved.

Game From Scratch

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;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.actions.MoveToAction;


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);

      myActor.addAction(moveToOrigin);
      stage.addActor(myActor);
      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();
            myActor.addAction(moveToOrigin);
         }
      if(keycode == Input.Keys.NUM_2)
         if(myActor.getActions().contains(moveToCenter,true)) {
            // this is "A" currently running action so do nothing
         }
         else {
            moveToCenter.reset();
            myActor.addAction(moveToCenter);
         }
      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.



iPhone Development Tutorials and Programming Tips

Open Source Swift Library Providing Easy JSON Deserialization Into Classes, Primitives And More

by Johann at October 28, 2014 06:17 AM

Post Category    Featured iPhone Development Resources,iOS Development Libraries,Open Source iOS Libraries And Tools,Swift

Earlier this year I mentioned the SwiftyJSON library providing an alternative syntax for parsing JSON as using NSJSON can become overly verbose with Swift’s strict data typing.

Here’s another library for parsing JSON in Swift that takes things a step further providing many functions for turning JSON data into primitive types, class types NSDate, and NSURL called JSONHelper from Baris Sencan.

Specificially the readme states JSONHelper includes operators for:

  • Deserializing JSON data into primitive types, NSData, and NSURL
  • Deserializing data into an array of primitive types NSDate, or NSURL
  • Deserializing data or JSON string into a class
  • Deserializing data or JSON string into arrays of a class

You can find JSONHelper on Github here.

You can read more about the techniques used in JSONHelper over on the Thoughtbot blog.

A nice class for working with JSON data in Swift


Be the first to comment...

Related Posts:

FacebookTwitterDiggStumbleUponGoogle Plus

Original article: Open Source Swift Library Providing Easy JSON Deserialization Into Classes, Primitives And More

©2014 iOS App Dev Libraries, Controls, Tutorials, Examples and Tools. All Rights Reserved.

iPhone Development Tutorials and Programming Tips

Open Source Swift Based Pull-To-Refresh Component That Supports Custom Animations

by Johann at October 27, 2014 06:47 PM

Post Category    Featured iPhone Development Resources,iOS Development Libraries,Open Source iOS Libraries And Tools,Swift

I’ve mentioned a number of custom pull to refresh components, most recently a pull-to-refresh component that combines pull-to-refresh and gesture based selection.

Here’s a nice open source component called Refresher for easily adding pull-to-refresh to a UIScrollView with added support for custom animations from Josip ?avar created in Swift.

The custom animation support allows you to specify start, stop, and progress animations to be used for your UIScrollView, and includes a number of interesting examples to work from.

Here’s an example from the readme showing an example progress indicator created with Refresher:

Refresher

You can find Refresher on Github here.

A nice Swift based library for creating pull-to-refresh controls with custom animations.


Be the first to comment...

Related Posts:

FacebookTwitterDiggStumbleUponGoogle Plus

Original article: Open Source Swift Based Pull-To-Refresh Component That Supports Custom Animations

©2014 iOS App Dev Libraries, Controls, Tutorials, Examples and Tools. All Rights Reserved.