Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon

20. June 2012

 

This tutorial is going to cover creating transition effects between your GameEngine2D scenes.  It is actually going to be rather short and mostly code, as the subject is actually quite simple and consistent between different effects.

 

All right, lets just right in.  First of all, when need our main application.  This is going to perhaps be the simplest one we have created to date, and all of the code should be familiar to you by now.  Create a new file named AppMain.cs as follows:

 

using System; using System.Collections.Generic; using Sce.Pss.Core; using Sce.Pss.Core.Environment; using Sce.Pss.Core.Graphics; using Sce.Pss.Core.Input; using Sce.Pss.HighLevel.GameEngine2D; using Sce.Pss.HighLevel.GameEngine2D.Base; namespace SceneTransitions { public class AppMain { public static void Main (string[] args) { Director.Initialize(); Scene1 scene1 = new Scene1(); Director.Instance.RunWithScene(scene1); } } }

 

All we are doing is Initializing the Director object, creating our custom scene of type Scene1 and telling it to run.  This literally is about the shortest PlayStation Mobile application you can create.

 

Now lets take a look at Scene1.cs

using System; using Sce.Pss.Core.Graphics; using Sce.Pss.HighLevel.GameEngine2D; using Sce.Pss.HighLevel.GameEngine2D.Base; namespace SceneTransitions { public class Scene1 : Scene { Texture2D texture; TextureInfo ti; public Scene1 () { this.Camera.SetViewFromViewport(); texture = new Texture2D("/Application/pic1.png",false); ti = new TextureInfo(texture); SpriteUV sprite = new SpriteUV(ti); sprite.Quad.S = ti.TextureSizef; sprite.Position = new Sce.Pss.Core.Vector2(0,0); this.AddChild(sprite); this.ScheduleUpdate(1); this.RegisterDisposeOnExitRecursive(); } ~Scene1 () { ti.Dispose(); texture.Dispose(); } public override void Update (float dt) { if((Sce.Pss.Core.Input.GamePad.GetData(0).ButtonsDown & Sce.Pss.Core.Input.GamePadButtons.Cross) == Sce.Pss.Core.Input.GamePadButtons.Cross) { if(Director.Instance.CurrentScene.IsRunning) Director.Instance.ReplaceScene(new Scene2()); } } } }

 

We are declaring a new class Scene1, which is derived from GameEngine2D.Scene. In this scene, in the constructor we are setting the camera to be sized to the viewport, creating a texture from our image pic1.png ( oh yeah, you need to add 3 images to your project, I picked three PS Vita wallpapers I downloaded off the net, you can use whatever files you want, but I assume you name them pic1.png pic2.png and pic3.png ) then create a sprite out of it.  This is all stuff we have done in prior tutorials.  We now add the sprite to our scene, and schedule this scene to receive updates.  Finally we call this.RegisterDisposeOnExitRecursive().  This function call is key, as it tells the Director to dispose of this scene when it is replaced.  If you do not call this, we will quickly run out of memory.

 

Next up is our destructor.  TextureInfo and Texture are both classes that you are expected to manage destruction of yourself ( they implement IDisposable ).  So in the destructor, which is called when our scene is replaced, we need to dispose of both of these items.  ( Actually I believe TextureInfo will take care of Texture2D, but don’t quote me on that ).

 

Next up is our Update() method.  As we have seen in the past, this method is called once every frame and is where your scene’s logic should be located.  In this case, we are waiting on the user hitting the Cross button ( or S key if using the simulator ), in which case we tell the Director to Replace the scene with a new created Scene2, which we will now create.

 

Create a file named Scene2.cs with the following code ( which is going to look extremely familiar… )

 

using System; using Sce.Pss.Core.Graphics; using Sce.Pss.HighLevel.GameEngine2D; using Sce.Pss.HighLevel.GameEngine2D.Base; namespace SceneTransitions { public class Scene2 : Scene { Texture2D texture; TextureInfo ti; public Scene2 () { this.Camera.SetViewFromViewport(); texture = new Texture2D("/Application/pic2.png",false); ti = new TextureInfo(texture); SpriteUV sprite = new SpriteUV(ti); sprite.Quad.S = ti.TextureSizef; sprite.Position = new Sce.Pss.Core.Vector2(0,0); this.AddChild(sprite); this.ScheduleUpdate(1); this.RegisterDisposeOnExitRecursive(); } ~Scene2() { ti.Dispose(); texture.Dispose(); } public override void Update (float dt) { if((Sce.Pss.Core.Input.GamePad.GetData(0).ButtonsDown & Sce.Pss.Core.Input.GamePadButtons.Cross) == Sce.Pss.Core.Input.GamePadButtons.Cross) { if(Director.Instance.CurrentScene.IsRunning) { Director.Instance.ReplaceScene( new TransitionCrossFade( new Scene3() ) { Duration = 4.0f, Tween = (x) => Sce.Pss.HighLevel.GameEngine2D.Base.Math.PowEaseOut( x, 3.0f )} ); } } } } }

 

So, basically it’s a cut and paste job of Scene1, just with a different texture file, and a different looking replace scene call.  I will look closer at that in a second.  Notice too that here we are creating a Scene3 in our Update() call, lets go ahead and create it next.

 

Create Scene3.cs

 

using System; using Sce.Pss.Core.Graphics; using Sce.Pss.HighLevel.GameEngine2D; using Sce.Pss.HighLevel.GameEngine2D.Base; namespace SceneTransitions { public class Scene3 : Scene { Texture2D texture; TextureInfo ti; public Scene3 () { this.Camera.SetViewFromViewport(); texture = new Texture2D("/Application/pic3.png",false); ti = new TextureInfo(texture); SpriteUV sprite = new SpriteUV(ti); sprite.Quad.S = ti.TextureSizef; sprite.Position = new Sce.Pss.Core.Vector2(0,0); this.AddChild(sprite); this.ScheduleUpdate(1); this.RegisterDisposeOnExitRecursive(); } ~Scene3() { ti.Dispose(); texture.Dispose(); } public override void Update (float dt) { if((Sce.Pss.Core.Input.GamePad.GetData(0).ButtonsDown & Sce.Pss.Core.Input.GamePadButtons.Cross) == Sce.Pss.Core.Input.GamePadButtons.Cross) { if(Director.Instance.CurrentScene.IsRunning) { Director.Instance.ReplaceScene( new TransitionSolidFade( new Scene1() ) { Duration = 1.0f, Tween = (x) => Sce.Pss.HighLevel.GameEngine2D.Base.Math.PowEaseOut( x, 3.0f )} ); } } } } }

Again, another cut and paste job, with just the texture file name changed, and a different ReplaceScene() call, this time creating a Scene1, basically creating an infinite application that shows Scene1, then button press, shows Scene2, button press, shows Scene3, button press, shows Scene1, repeat over an over.

 

Now lets look at the key differences between how the transitions work:

 

Scene1:

Director.Instance.ReplaceScene(new Scene2());

Scene2:

Director.Instance.ReplaceScene( new TransitionCrossFade( new Scene3() ) { Duration = 4.0f, Tween = (x) => Sce.Pss.HighLevel.GameEngine2D.Base.Math.PowEaseOut( x, 3.0f )} );

Scene3:

Director.Instance.ReplaceScene( new TransitionSolidFade( new Scene1() ) { Duration = 1.0f, Tween = (x) => Sce.Pss.HighLevel.GameEngine2D.Base.Math.PowEaseOut( x, 3.0f )} );

 

The transition from the first screen, does nothing, it simply transition to the next scene with no visual effect.  Your first image will simply be replaced with your second image.

 

Scene2 however, transitions by creating a new temporary scene, a TransitionCrossFade, which is essential a short lived scene that goes between Scene2 and Scene3 and causes a cross fade effect.  As you can see, we provide a Tween method which controls the rate at which the fade will occur.  A tween are not simply the people responsible for the bizarre success of the Twilight franchise, its actually short had for inbetween, which is essentially just a function that is going to be called over and over during a transition until it is completed.  Tweens are quite common in the animation world. 

 

Scene3 works almost identically to Scene2, but instead of a cross fade, it’s a solid fade.  You can see the difference in the video of this application in action.  There is one very important thing to be aware of here… these temporary scenes, TransitionCrossFade and TransitionSolidFade, if you try to replace them before they have completed running, your application will crash!  Truth is, in real life you won’t be switching scenes this quickly, so it should be a non-issue, but it is something you should be aware of.  If you want to witness this first hand, load this code up in the simulator and just repeatedly hit S, you will crash soon enough.

 

Now, let’s take a look at our code in action:

 

Transition between scenes on the PlayStation Vita Simulator

 

As always, you can download the full sources here.

Programming , , ,

19. June 2012

 

A couple months back took a long look at Appcelerator and initially I loved what I saw.  For those of you unaware, Appcelerator allows you to develop “native” applications for Android and iOS in JavaScript that execute in a special version of the V8 JavaScript Engine. I started developing a prototype app of a simple Android game for my daughter and got surprisingly good results quickly.  It was a very encouraging start, but then the wheels fell off.  I notice a number of people end up on this site from search engines looking for an Appcelerator review ( for some reason? ) so I thought I would share my experiences.

 

For whatever reason, I got distracted and put it down for a while, I came back to it recently and intended to finish off that prototype.  Here is the kicker, the exact same code from a couple months ago, unchanged, no longer works on my Transformer tablet.

 

I will say, this is frustrating to say the least.  Now, since the code didn’t change it was obviously an update to Android that broke things, I can’t exactly blame that on Appcelerator Titanium ( oh the joys of Android device compatibility… ) but I can blame them for what came next…

 

You can’t debug on device.  At all.  With the exception of printing comments to logcat, you are basically blind.  This obviously leads to a problem, as here is what happens when I run the app.  ( Which by the way, still runs perfectly fine on my Galaxy Note running Android 2.3.x, its just on my Asus Transformer that it breaks ):

 

appcell

 

Since I can’t debug on device, this is the results I get from connecting with the Delvik Debug Monitor:

 

06-19 09:56:51.090: I/TiApplication(1823): (main) [0,0] checkpoint, app created.
06-19 09:56:51.130: I/TiApplication(1823): (main) [46,46] Titanium 2.0.2 (2012/05/30 10:21 2ff31a3)
06-19 09:56:51.170: D/dalvikvm(1823): GC_CONCURRENT freed 268K, 5% free 6703K/7047K, paused 2ms+2ms
06-19 09:56:51.380: D/dalvikvm(1823): GC_CONCURRENT freed 314K, 6% free 6898K/7303K, paused 2ms+2ms
06-19 09:56:51.450: E/TiApplication(1823): (KrollRuntimeThread) [318,364] APP PROXY: ti.modules.titanium.app.AppModule@4112e910

 

 

And, that is it.  Since I can’t debug on the device, I am pretty much DOA here.  The forums answer nothing ( although I did find other people having similar problems ).  I of course could debug in the emulator with two exceptions.  a) the error only occurs on the actual device b) the debugging experience on Android is still awful.

 

This is another area with Appcelerator Titanium I always found infuriating… the emulator.  Getting it to actually run with your running emulator was a nightmare, you had to match up the Android build version and run configuration exactly with the version of the running emulator, then it was still a 50/50 chance that it would actually use your emulator, or start a new one.  If you’ve worked with Android before, you know how fun waiting for the emulator is!  There is light and the end of the tunnel with the recently release Intel emulator running a heck of a lot quicker, but unfortunately the JavaScript V8 virtual machine Appcelerator relies on doesn’t work with it.

 

It’s a shame to be tripped up on such a thing, but actually being able to debug on your device is an absolute requirement, as is demonstrated by this situation.  There are other annoyances with using Appcelerator certainly…  the binaries it generates are “large” to be extremely kind, performance can be a bit spotty at times and you virtually have to write two applications if you want to support iOS and Android, but none of these was enough to make me give up. 

 

Not being able to debug on device, coupled with some remarkably meh support.. that is.  Combined with the fact my application was broken by an Android update… if I can’t get my code working with my three devices reliably, what happens when I release to the masses with their millions of different devices?

 

Which is disappointing, as I really liked working with Appcelerator.  I even liked Appcelerator Titanium as an IDE, which is shocking as I hate Eclipse, which it is based on. 

 

There is potentially light at the end of the tunnel, as there is an open ticket for debugging on device.  Unfortunately, its been assigned medium priority and has already been open for almost a year.

 

Appcelerator Titanium is an interesting and encouraging product, but for the above reasons, I just can’t commit to using it.  Add native debugging support, and I will certainly reconsider.

General , , ,

18. June 2012

 

unity

By way of this reddit posting, some interesting news about Unity 4 was posted and then removed.

 

 

So what can we expect in Unity 4, according to this article?

  • DirectX 11 support
  • Improved Flash exporting
  • External forces, bent normals and automatic culling of particles
  • dynamic obstacles and avoidance navigation
  • optimized UnityGUI performance and memory usage
  • dynamic fonts across all platform using HTMLesque markup
  • remoute Unity web player debugging
  • new project window workflow
  • iterative lightmap backing
  • refined component based workflows
  • extensible inspectors for custom classes
  • improved cube map importing
  • geometry data improvements for huge memory and performance savings
  • non triangle meshes, render points and lines.
  • search, live preview and asset store directly from project window

 

And perhaps most interesting of all, a preview of deploying to Linux.

 

They also promise a faster turn around development cycle on version 4 than they had on version 3.

Personally I am kind of underwhelmed.  With Flash/Nacl support, is Linux support really a big deal?  Otherwise its nowhere near as big of a release as the prior 3.x releases.  The DirectX 11 support should help PC versions of Unity games get closer to CryEngine and UDK in graphical fidelity.

 

I do wonder if they will offer upgrade pricing for the version they gave away earlier this year?

 

What do you think, if this is real are you excited by the new features?

News ,

17. June 2012

 

In this tutorial we are going to look at adding keyboard and mouse support to your cocos2D application.  cocos2D was traditionally used on the iPhone, so keyboard and mouse support is very touch centric, so if you are used to desktop development and things seem a bit strange, this is why.

Alright, let’s jump right in.  We are going to create a simple game with our jet sprite from tutorial 3.  The big difference is it will respond to your mouse and keyboard activity.  Clone your previous project, this time I am calling it MyThirdApp.  Yeah, tons of thought went into these names! 

 

Now create a new file in the Classes directory named JetSprite.js. Inside, write the following code:

 

var JetSprite = cc.Sprite.extend({
    _currentRotation:0,
    ctor:function(){
        this.initWithFile("images/jet.png");
    },
    update:function(dt){
        this.setRotation(this._currentRotation);
    },
    handleKey:function(e)
    {
        if(e === cc.KEY.left)
        {
            this._currentRotation--;

        }
        else if(e === cc.KEY.right)
            this._currentRotation++;

        if(this._currentRotation < 0) this._currentRotation = 360;
        if(this._currentRotation > 360) this._currentRotation = 0;
    },
    handleTouch:function(touchLocation)
    {
        if(touchLocation.x < 300)
            this._currentRotation = 0;
        else
            this._currentRotation = 180;
    },
    handleTouchMove:function(touchLocation){
        // Gross use of hardcoded width,height params.
        var angle = Math.atan2(touchLocation.x-300,touchLocation.y-300);

        angle = angle * (180/Math.PI);
        this._currentRotation = angle;

    }
});

 

Here we are deriving our new class JetSprite from cc.Sprite using the extend() function.  During the constructor, we first call back to cc.Sprite’s constructor, then load our sprite from the file jet.png located in the images folder.  ( If you like me started your project by cloning MySecondApp, it should already be there, otherwise make sure you have an image there ).

 

The update() function is going to be called once every frame, this will make sense later.  Essentially this is where you put your object’s logic.  In this case we are simply rotating our sprite to the value in _currentRotationhandleKey(), handleTouch() and handleTouchMove() are three user defined functions that are going to be used to pass I/O events into our JetSprite object.

 

handleKey() is passed the key value ( it’s a number ) of the currently pressed key.  cocos2D defines a number of key values to represent each key in the cc.KEY value.  If you want more details check out CCKeyboardDispatcher.js in the cocos2D directory for more details.  In the event the left arrow key is held down, we decrement our rotation value, if the right arrow key is down we increment the rotation value.  Finally, if we roll over 360 or under 0 degrees, we update accordingly.  Effectively this rotates our sprite left and right on arrow key press.

 

handleTouch() is very simple.  It is passed in the touchLocation, which is an x,y value representing where on screen was touched ( or in our case, clicked ).  If its on the left half the screen, we point up ( 0 degrees ), if the touch occurred on the right half of the screen, we rotate to straight down ( 180 degrees ).  One limitation of cocos2D seems to be the lack of ability to handle right clicks, but this may just be an oversight on my behalf.  Right now, a “touch” is any mouse button click.

 

handleTouchMove() is passed in the x,y coordinates of the mouse’s currently location.  As you can tell by the comment, I rather crudely used a hardcoded value for representing half the screen width ( 300 ), obviously in non-demo code you wouldn’t do this!  What we want to do here is figure out the angle of the mouse relative to the center of our sprite ( which is located at 300,300 ).  This is done by taking the atan2 of the distance of the mouse’s coordinate from sprite’s center.  We then convert that value ( atan2 returns a value in radians ) to degrees.  Finally, we take our calculated angle and apply it as our rotation.  Essentially this will cause our sprite to rotate relative to the mouse location.

 

Now lets take a look at the heart of our application.  Create a new script file ( or rename MySecondApp.js ) called MyThirdApp.js and enter the following code:

 

var MyThirdApp = cc.LayerColor.extend(
{   _jetSprite:null,
    init:function(){
        this._super();
        this.initWithColor(new cc.Color4B(0,0,0,255));
        var size = cc.Director.getInstance().getWinSize();

        this._jetSprite = new JetSprite();
        this.setTouchEnabled(true);
        this.setKeyboardEnabled(true);

        this.setPosition(new cc.Point(0,0));

        this.addChild(this._jetSprite);
        this._jetSprite.setPosition(new cc.Point(size.width/2,size.height/2));
        this._jetSprite.scheduleUpdate();
        this.schedule(this.update);

        return true;
    },
    onEnter:function(){
        this._super();
    },
    update:function(dt){
    },
    onTouchesEnded:function (pTouch,pEvent){
        this._jetSprite.handleTouch(pTouch[0].getLocation());
    },
    onTouchesMoved:function(pTouch,pEvent){
        this._jetSprite.handleTouchMove(pTouch[0].getLocation());
    },
    onKeyUp:function(e){

    },
    onKeyDown:function(e){
        this._jetSprite.handleKey(e);
    }
});



MyThirdAppScene = cc.Scene.extend({
    onEnter:function(){
        this._super();
        var layer = new MyThirdApp();
        layer.init();
        this.addChild(layer);
    }
})

 

The bulk of this code is very similar to previous code with one major difference.  In previous examples, we created a layer, then added a color layer to it.  In this case, we simply extend from LayerColor and add our children directly to ourselves.  There is very little functional differences between the two approaches, except this one is a bit more concise.  Now let’s take a closer look at our code.

 

In our init() method, we init with a black background colour.  We then create our JetSprite object and tell cocos2D that our layer handles touch and keypad events.  In cocos2D, input is handled at the layer level, and setting these two values will result in touch and keyboard delegates being added to our object so we can handle IO events.  We then position our layer, add our _jetSprite as a child positioned in the center of our layer.  The scheduleUpdate() call is very important.  This will result in our JetSprite’s update() function getting called every frame.  If you don’t call this method, or sprite wont do anything!

 

Next up is onEnter() which is what is called when a layer becomes the active layer.  In our case, this call is very important, as it ( in cc.Layer.onEnter ) is where the touch and keyboard delegates are actually attached to our layer!  If you remove the call to this._super(), you will not receive any keyboard and mouse events!

 

Now that we are wired up to receive touch and keyboard events, we need a couple methods that will be called when they occur.  In our case we are going to use ccTouchesEnded, ccTouchesMoved, keyUp and keyDown.  When an event occurs, these methods will be called, which in turn simply call the appropriate method on our JetSprite.

 

There are two things to be aware of here.  There are ccTouch____ and ccTouches____ versions of events; to my experience, the ccTouch____ version will never be called!  If you want to handle touch/mouse events, use the ccTouches version.  The next is the way we are handling key presses,  right now since we used keyDown, holding down the key will result in it being called over and over.  If however you want to respond only once per key hit ( regardless to if it is held down or not ), use keyUp instead.

 

We also need to make sure our new classes are included in our project.  Just like the last tutorial, make the following changes to the bottom of cocos2d.js

appFiles:['MyThirdApp.js','JetSprite.js']

 

We also need to update the Scene name in main.js

var myApp = new cocos2dApp(MyThirdAppScene);

Here is the end result of all of our code.  Mouse over the canvas and the mouse will follow you.  Left and right arrow will rotate the sprite, while clicking (either button) on the left half of the screen will point the jet up, while clicking the right half will point the sprite down.

 

 


 

If you are running Chrome be aware the clicking doesn’t appear to work.  It is actually working, the sprite is being rotated.  However it is also triggering a mouse move event, immediately snapping the sprite back to where you mouse pointer is! Smile

 

As always, you can download the whole project right here.  It includes a zip of the cocos2D version I used, in case you have trouble working with the current release.

 

 

Read Tutorial 5

Programming , ,

15. June 2012

 

I have recently become more and more interesting in HTML5 game development.  However,HTML5_Logo_256 upon initial investigation I realized there are an absolute ton of libraries and tools out there.  Some of them are amazing, others… not so much.  During my research I put together notes on the key libraries, tools, books, frameworks and IDEs used for HTML5 development.  This is the results of that research.

 

So, if you are looking to get into HTML5 game development, this page could be a very good place to start.

 

This list is by no means complete, it just represents the best of what I have found so far.  If you have recommendations for inclusion ( especially for the links section! ), please let me have them!  There are links as well to non-game related frameworks like Backbone.js, YUI, Mustache, etc. I am intending to do some game tool development in JavaScript for an upcoming RPG project, so those are there as much for my use as anything.

 

I hope you find it handy.

 

Links of interest for HTML5 game developers.

Programming ,

Month List

Popular Comments