Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon

31. October 2016

 

Cocos Creator is an open source JavaScript powered game engine and editor built on top of the Cocos2d-x framework.   For more details of how Cocos Creator works, check out this hands-on video showing an earlier version in action.  Cocos Creator just released a new version, 1.3, bringing several new features including rich text support, a new audiococos engine and Dragon Bones animation file support.  On gotcha of this release however is that 32bit Windows support for the editor has been dropped.

 

From the release announcement in the Cocos2d-x forums:

 

Cocos Creator 1.3.0 released!

We are excited to release version 1.3.0 of Cocos Creator. Cocos Creator is a new, unified, development tool that handles every step in the game development process.

This version offers an incredible performance increase for both Web and native platforms. There are 6 major features and numerous small changes in this version that will help Creator meet the needs of more and more types of projects! The following is the highlight of this update:

  • Rich text support
  • Dragon Bones skeleton animation support
  • Prefab automatic synchronization
  • Automatically packaging textures to Atlas
  • Added UI controls: PageView, Toggle, ToggleGroup, Slider
  • New AudioEngine

Important upgrade instructions

  • The Windows version now uses use a 64-bit architecture, there is no longer support for 32-bit Windows systems. The advantage is that the editor can deal with a large number of image resources and improve the efficiency by at least 5 times, but also to support the emerging image format Webp.

GameDev News

31. August 2016

 

A pair of game engine from the Cocos2d-x team this week.  First off was the release of Cocos2d-x 3.1.3.  Cocos2d-x is a C++ port of the popular cross platform Cocos2D game engine.  I have a tutorial series on Cocos2d-x available here if you wish to learn more.  The also announced the release of Cocos Creator 1.2.1.  Cocos Creator is a 2D game engine and editor for building games in JavaScript and built over top of the Cocos2d-x project.  For more information on Cocos Creator check out this hands on video.

 

Details on the Cocos2d-x release:

  • added VR plugins for Gear, Deepoon, Google Cardboard and Oculus.
  • support ETC1 alpha channel
  • fix AudioEngine performance for Android 4.2+
  • improve canvas renderer performance with dirty region
  • add Android arm-64 support switch to use gcc 4.9
  • upgrade CURL to 7.50.0
  • upgrade Spine to 3.4
  • upgrade GLFW to 3.2

 

And from the Cocos Creator release:

Editor
  • [Assets] Fixed renaming asset will cause error when using filter in Assets panel.
  • [Preview] Fixed using console.log(node) in browser preview will generate a lot of error message issue.
  • [Preview] Fixed when previewing scene in browser, enter prefab editing mode will cause error issue.
  • [Editor] Fixed loading a new scene right after save previous scene in editor may cause the new scene to be overwrite by old scene issue.
  • [Dashboard] Fixed can't create a new project at root path on windows issue.
  • [Build] Fixed an error that may cause built engine size not reduced as engine module setting.
  • [Build] Fixed deleting scene when Build Setting panel is open cause built game to black screen issue.
  • [Preference] Added 'Enable Auto Compile' option in 'Data Editor' tab of Preference panel. So user can disable auto compile and only use manual compile.
  • [Code-Editor] Fixed 'tab' key not working in builtin Code Editor.
  • [Console] Fixed clicking error message in bottom status bar will not jump to Console panel correctly issue.
Engine
  • [Engine] Fixed some UI element may cause memory leak issue.
  • [Engine] Fixed an error cause 'Landscape' orientation not enforced on mobile device.
  • [Engine] Fixed Mouse hover event not cleared after scene switch issue.
  • [Engine] Fixed defining a global variable in a script with 'Import as plugin' option will cause error issue.
  • [Engine] Fixed skew render calculation not consistent between Web and native platforms issue.
  • [Render] Fixed a bug that cause BMFont not able to be batch rendered.
  • [Graphics] Fixed when drawing arc set counterclockwise will get wrong direction issue.
  • [Graphics] Fixed using some API on Windows will cause crash issue.
  • [Action] Fixed using ScaleBy, SkewBy actions will cause 'too much recursion' error
  • [JSB] Now send API of socket.io can accept object argument on native platforms
  • [JSB] Now runAction will return action instance on native platforms.
Component
  • [Component] Fixed fetching property reference failed and display as NONE issue when there's a lot of properties defined on a single component.
  • [Component] Fixed color picker cannot save color correctly issue.
  • [Button] Fixed when Transition set to Color, updating interactable to false will not get correct appearance issue.
  • [Mask] Fixed a bug that cause Mask not taking effect in event handling if register event before node is added to the node tree.
  • [Animation] Fixed Collider component size will be reset to 0 when adding key frame in animation issue.
  • [Animation] Fixed setting node active to false in another component's onEnable method will not stop animation from playing issue.
  • [Animation] Fixed compiling script in Animation editing mode will cause trajectory disappear issue.
  • [ScrollView] Fixed scrollBar not updated correctly when scrolling to the bottom and removing the last entry.
  • [ScrollView] Only allow event register when content property bound to a node.
  • [ScrollView] Added cancelInnerEvents property to control if touchmove and touchend event can penetrate to entry node.
  • [ScrollView] Fixed scrollBar will disappear when Scrollview node is activated.
  • [ScrollView] Fixed the white top margin issue on iOS platform.
  • [Label] Fixed opaque alias around Label in WebGL render mode.
  • [Label] Fixed LabelOutline component can cause infinite loop for Shrink overflow on label.
  • [Label] Fixed when loading multiple TTF assets, Label component may end up using the wrong TTF asset issue.
  • [Label] Fixed adding BitmapFont asset to the project when editor is not active may cause importing to fail issue.
  • [VideoPlayer] Added currentTime, duration and isPlaying API.
  • [Widget] Fixed Widget component may get disabled in editor after run preview.
  • [SpriteDistortion] Fixed sphere distortion component not working in refactored WebGL render system.
  • [EditBox] Fixed when input type set to Number, maxLength property had no effect issue.

GameDev News

8. August 2016

 

Cocos Creator is a JavaScript powered game engine and editor, built over top of the Cocos2d-x framework.  I did a hands on video of Cocos Creator shortly after it was released if you want to learn more.  Cocos Creator just shipped version 1.2 which includes several new features.

 

Details of the changes in 1.2 from the release notes:

    Major Changes
    • [Build] Added Lua build target for Build panel
    • [Engine] Added WebGL auto batching and culling optimization
    • [Engine] Added dirty region optimization for Web Canvas rendering mode
    • [Engine] Added AnySDK library to native build
    • [Editor] Added Async load assets option to scene asset's property, check this one will make the scene run right after finish loading scripts and node tree, and rest assets such as textures and audios will be loading on the go.
    • [Engine] Added cc.Graphics graphic drawing API
    • [Preview] Added Eruda mobile debugging library for web preview, you can open the debug panel by clicking the gear icon.
    • [Webview] Added webview component
    Editor
    • [Editor] Added Module Config tab in Project Settings panel that can customize which modules go into build.
    • [Editor] Refactored Properties panel that enables customizing property elements for user defined components.
    • [Assets] Fixed display error of folder with .. in its name in Assets panel.
    • [Assets] Fixed when updating atlas assets, the spriteFrame under atlas texture may not be updated correctly issue.
    • [Prefab] Fixed error when exiting from prefab editing mode to a scene with EditBox.
    • [Prefab] Fixed the issue that when dragging an element from Node Library to a prefab will cause the prefab to turn into normal node.
    • [Animation] Fixed deleting AnimationClip when editing it will cause display error issue.
    • [Animation] Fixed editing animation property of a Widget component may get wrong result issue.
    • [Animation] Added animation 添加了动画回调事件,包括 play, stop, pause, resume, lastframe,finished
    • [Animation] Fixed Play On Load animation will still play despite Animation component is disabled issue.
    • [Menu] Select All in Edit menu now can select all nodes or assets in Node Tree and Assets correctly.
    • [Scene] Fixed swiching on and off Particle in scene will make editor run slow issue.
    • [Scene] Fixed when undoing node's activation state will not update node tree and scene view correctly issue.
    • [Console] Refactored Console panel to make it capable of displaying unlimited amount of messages.
    • [Console] Fixed Console panel in Windows cannot show Chinese character correctly issue.
    Engine
    • [Engine] Fixed Android rendering issue, performance should be improved.
    • [Engine] Fixed child node not updating its opacity correctly when detached from a parent node.
    • [Engine] Fixed some dependent assets cannot be loaded when loading multiple prefab at the same.
    • [Render] Improved dynamic font rendering quality for WebGL
    • [Render] Fixed glitches in rendering animation or updates on latest Chrome browser issue.
    • [Render] Use libPNG library on iOS platform to fix transparent images getting dark issue.
    • [JSB] Fixed bezierTo action will not update node position correctly issue.
    • [JSB] Fixed scheduleOnce callback will be called multiple times issue.
    • [JSB] Fixed cc.game.EVENT_SHOW and cc.game.EVENT_HIDE not working in JSB.
    • [Action] Fixed on Web platforms cc.hide, cc.show, cc.toggleVisibility not working issue.
    Plugins
    • [TiledMap] Optimized tilemap rendering for WebGL with unlimited tile count.
    • [TiledMap] Fixed moving tilemap assets will cause reference lost issue.
    • [TiledMap] Fixed TiledLayer.setTileGID API doesn't support float value input issue.
    • [TiledMap] Fixed hex based map not rendered correctly issue.
    • [TiledMap] Fixed TiledLayer not able to change opacity issue.
    • [Button] Fixed setting node.active=false in onTouchEnd callback, it will not reset to normal texture when node reactivated issue.
    • [Label] Fixed changing TTF font in runtime will cause error on native platform issue.
    • [ScrollView] Auto hide ScrollBar and reset content position when Scrollview content size is smaller than Scrollview size
    • [ScrollView] Added stopAutoScroll API to manually stop scrolling.
    • [ScrollView] Fixed Touch.startPoint not convert to view coordinates that cause click events in ScrollView not working
    • [Collider] Now can track dynamic change of node.group correctly.
    • [EditBox] Fixed EditBox component will trigger TextChanged when enabled issue.
    • [EditBox] Fixed Label in EditBox has inconsistent behavior between native and web platform
    • [EditBox] More types of pop-up keyboard are supported on Web browsers.
    • [EditBox] Fixed third party IME will block input field on iOS issue.
    • [EditBox] Added editingReturn event to differ hitting 'enter key' or clicked outside of pop-up keyboard.
    • [Component] Fixed copy and paste Component will not add dependent component first issue.
    • [Component] Sort user defined components in Add Component button menu.
    Misc
    • [Build] Missing reference to assets and scripts will generate console warning when building project and saving scene.
    • [Build] Added IPC message editor:build-start when building starts
    • [Build] Do not pack assets JSON for native platform build.
    • [Build] Added Android Studio checkbox for Android building, only works for default template and needs Android SDK 22 for compilation.
    • [Build] Fixed Creator app has space in its name will cause building native with binary template issue.

You can learn more about the release here.

GameDev News

12. July 2016

 

Cocos Creator is a game engine and editor built over top of Cocos2d-x for building mobile games using JavaScript.  I created a hands-on review of an earlier version of Cocos Creator if you want to learn more information.

 

This release brings several small changes and fixes.  From the release notes:

Editor
  • [Editor] Build to Web platform will merge asset JSON files now. The requests to download asset will drop by 50% in general. Currently an asset shared among multiple scenes will be merged additively. (If assetA and assetB both referenced by sceneC and sceneD, assetA and assetB will be merged into one JSON)
  • [Editor] Disable 'Preview' button when there're compilation error for user script. Once all errors are resolved the error log will be cleared in console.
  • [Editor] Removed Squirrel.Windows installer framework, with the new installer you can specify installation location and configure check update frequency.
  • [Editor] Fixed spriteFrame atlas replacement tool can cause reference error when replacing spriteFrame in multiple scenes.
  • [Scene] Fixed multi-select some nodes and press arrow keys to move them may get the distance wrong issue.
  • [Component] The Add component menu in Properties panel now sorted alphabetically.
  • [Importer] When import Cocos Studio or Cocos Builder project, buttons without text will not create Label nodes.
  • [Importer] Fixed import Cocos Studio older version may cause animation data lost issue.
  • [Importer] Fixed imported Cocos Studio / Cocos Builder project wrong value of lineHeight for Bitmap Font component issue.
  • [Build] Fixed build native failed may cause process to freeze issue.
  • [Build] Fixed preview with Chrome browser may cause Failed to parse SourceMap error issue.
  • [Build] Fixed building an empty project will cause: Build Failed: Error: TypeError: next is not a function issue.
  • [Prefab] Add a main menu item Node Presets-> Convert to Ordinary Node to break break the link of a node to prefab asset.
  • [Prefab] Fixed in prefab editing mode click 'save' button may not work issue.
  • [Animation] Fixed setting node opacity at the last frame event callback of an animation may fail issue.
  • [Animation] Fixed deleting animation event may fail issue.
  • [Assets] Fixed atlas and TTF assets may get reimported when open project issue.
  • [Assets] Fixed sprite not rendered correctly when referenced spriteFrame asset moved issue.
  • [Assets] Fixed texture asset thumbnail not updated when texture content changed issue.
  • [Assets] Fixed an error that can cause editor to freeze when importing 10000+ assets for new project issue.
  • [Assets] Fixed assets may not be imported correctly when moved assets after close editor issue.
  • [Assets] Add a warning dialog when user moved assets without updating the corresponding meta files.
  • [Assets] Add a replace asset confirmation dialog when dragging assets with the same names from file system to editor's Assets panel.
Engine
  • [Render] Fixed an issue that when setting parent node's opacity to 0 while setting child node's active to false may cause child node to not render when reactivated.
  • [Engine] Fixed simulator cannot send http request on macOS 10.11 issue.
  • [Engine] Fixed VS Code debug native fail on Mac issue.
  • [Engine] Fixed cc.follow action result in wrong coordinates issue.
  • [Engine] Add an error message when assign a boolean type value to cc.Label.string.
  • [Engine] Fixed cc.game.addPersistRootNode API may not work correctly in native platforms issue.
  • [Engine] Fixed screen flicker when switching scenes.
  • [Engine] Fixed script initialization may fail issue when re-enter a scene.
  • [Engine] Fixed when loading a Prefab asset in scene may cause infinite asset request issue.
  • [Engine] If game is running on Android OS with virtual buttons, the virtual button will be hidden when game launches.
  • [Engine] Fixed cc.repeat action will count wrongly when repeat times is above 6.
  • [JSB] Fixed cc.follow may cause error in JSB native platforms.
  • [JSB] Fixed scheduler.isScheduled() not implemented in JSB issue.
  • [JSB] Fixed _errorHandler wasn't found error reported in console with no valid reason issue.
  • [JSB] Fixed setMargin API not implemented in JSB for LabelOutline issue.
  • [Audio] Fixed audio asset takes very long to load on iOS browser issue.
  • [Audio] Fixed rewind API not working for AudioSource component issue.
Component
  • [Label] Fixed when overflow set to Shrink font size and label text flow not calculated correctly issue.
  • [Label] For BitmapFont label, When total character width smaller than Label node's width, character wrap mode will be enabled.
  • [Label] Fixed system font overflow not calculated correctly issue.
  • [ScrollView] Fixed button in ScrollView may stay in hover state issue.
  • [ScrollView] Fixed register touchend touchcancel event on ScrollView node may not trigger correctly issue.
  • [ScrollView] Disable ScrollView node will stop scrolling now.
  • [EditBox] Add all lowercase format, fixed using TTF font asset on Android system issue.
  • [EditBox] Fixed calling setVisible will pop keyboard issue.
  • [EditBox] Fixed on mobile browser EditBox need to be clicked twice to pop keyboard issue.
  • [EditBox] Fixed EditBox not clickable in ScrollView issue.
  • [Layout] Fixed change child node's active property will not get correct bounding box size in None mode issue.
  • [Layout] Fixed issue when add a child node to Layout and then remove will not remove event listeners correctly.
  • [Button] Fixed switching interactable property for Button will not update normal and disable state spriteFrame issue.
  • [Collider] Fixed disabling collider will not clear debug draw issue.
  • [MotionStreak] Improved MotionStreak compatibility for Android browser.
  • [Tilemap] Fixed TiledMap may render with seams in WebGL platform issue.
  • [Tilemap] Fixed SGTiledLayer has inconsistent API between Web and Native implementation issue.
  • [Tilemap] Fixed issue that when tmx file is not at the same location of texture file the Tilemap may not rendered correctly issue.
  • [Spine] Fixed getCurrent() may cause infinite loop in JSB native platform issue. Please usespine.getCurrent() to fetch current playing track.
  • [Mask] Fixed masked node can still receive touch event issue.
  • [Mask] Fixed disabled Mask component can still block child node from touch event issue.

Downloads:
- Creator for Mac
- Creator for Windows

GameDev News

8. July 2016

 

Cocos2d-x is a popular open source C++ based cross platform game development library.  If you are interested in learning more about Cocos2d-x, we have a complete tutorial series available here.  The Cocos2d-x team just announced the release of Cocos2d-x 3.12.  Version 3.12 adds support for the Tizen platform, experimental support for VR, fixed some Android performance issues, add obb Android support and WebGL improvements. 

In addition to these features, there are dozens of new features and bug fixes, including:

[HIGHLIGHT] add VR support

[HIGHLIGHT] add Tizen support

[HIGHLIGHT] fix Android performance issue

[HIGHLIGHT] Web engine performance improved in WebGL mode

[HIGHLIGHT] support obb extension on Android

[NEW] Core: add `utils::findChild()`

[NEW] Core: add CSV format support to tile maps

[NEW] Core: add `FileUtils::getContents()`

[NEW] Core: cocos2d::Value supports unsigned

[NEW] Particle: add feature to pause/resume particle emitter

[NEW] Platform: support Windows 10 UWP x64

[NEW] UI: add clamp and shrunk feature for system fonts, currently only support iOS, Android and Mac

[NEW] UI: make ListView select item programmatically

[NEW] UI: add `EditBox::InputFlag::LOWERCASE_ALL_CHARACTERS` to lowercase characters

[NEW] UI: add `setBounce()` to WebView

[NEW] Web: refactor TMXLayer renderers

[NEW] Web: can force orientation in mobile browser

[NEW] Web: support high resolution TTF Label on retina display

[REFINE] Android: use clang instead of gcc to compile codes

[REFINE] Android: hide virtual button by default

[REFINE] Android: set music volume control as default

[REFINE] Android: usage clang insteand of gcc to compile codes

[REFINE] Audio: catch `IllegalStateException` exception to avoid crash when playing background music with SimpleAudioEngine on Android

[REFINE] Core: fix many warnings

[REFINE] Core: move StringUtils functions from deprecated header file to ccUTF8.h

[REFINE] Core: FontFNT will ignore chars that exceeds 65535 and print a warning information

[REFINE] Core: `Node::ignoreAnchorPointForPosition()` is deprecated and add `Node::setIgnoreAnchorPointForPosition()`

[REFINE] Core: allow inherit from platform FileUitils

[REFINE] Core: add optional alpha parameter to Color4B and Color4F

[REFINE] Core: Follow action can accept horizontal and vertical offset

[REFINE] Core: TMXXMLParse parse `id` element

[REFINE] Lua: rename all member functions named `end()` to `endLua()`

[REFINE] JSB: make selectedSprite opitional in MenuItemSprite

[REFINE] JSB: return null if read failed in `js_cocos2dx_CCFileUtils_getDataFromFile()`

[REFINE] Template: iOS tempalte is refined to make cocos2d-x game scene work better with other UIView

[REFINE] Template: remove `build_native.sh`

[REFINE] Template: ARC support on iOS and Mac OS

[REFINE] UI: TTF and BMFont label wrap mode will automanytically changed to char wrap mode when label's width is less than word's boundary

[REFINE] UI: UIWidget adds missing properties for clone

[REFINE] UI: UIScrollBar caches the texture created with base64 encoded images

[REFINE] UI: EditBox now prints lowercase letters by default

[REFINE] UI: enable WebView's local storage on Android

[REFINE] UI: improve EditBox implementation on WinRT

[REFINE] UI: make PageView indicator more tunable

[REFINE] UI: make PageView page turning event time tweak configurable

[REFINE] UI: RichText is improved: add effect of outline, shadow and glow; catch the event of open url; ability to extend tags; add anchor of image tag

[REFINE] 3D: skeleton animation is more efficient when two animations switch frequently

[REFINE] 3rd party: update webp to 0.5.0

[REFINE] Web: improve basic types to reduce memory usage

[REFINE] Web: Show line number in console statements

[REFINE] Web: Cache base64 image of PageViewIndicator and ScrollViewBar

[REFINE] Web: Pass error in cc.AsyncPool in onEnd callback

[REFINE] Web: Separate ccui.ListView event callback from ccui.ScrollView for its own events

[FIX] Android: fix compiling error if using NDK r11+

[FIX] Android: package name is `libcocos2dx` instead of application name if building with Android Studio

[FIX] Audio: AudioEngine can not work if the file path contains not ascii code on iOS

[FIX] Audio: SimpleAudioEngine::playEffect() doesn't work correctly on Linux

[FIX] AssetsManager: can not work

[FIX] AssetsManagerEx: use manifestUrl from remote version

[FIX] Core: `FileUtils::writeValueMap()` will crash on iOS if it contains `Value::Type::None` type element

[FIX] Core: `ClippgNode::setStencil()` may cause assert error if it is invoked before

[FIX] Core: `TextureCache::addImageAsync()` doesn't set pixel format corretly

[FIX] Core: `GL::SetBlending()` doesn't set dst correctly

[FIX] Core: vertex z can not work correctly if window size changed on desktop platforms

[FIX] Core: use `std::isnan()` instead of `isnan()` to fix compiling errors on some Linux platforms

[FIX] Core: crash on windows when using PolygonInfo

[FIX] Core: fix `libpng error: CgBI: unhandled critical chunk` error with Xcode 7.3

[FIX] Core: EXC_BAD_ACCESS random crash caused by reallocation of shared indices memory

[FIX] Core: memory leak of `utils::captureScreen()` on iOS and Mac OS

[FIX] Core: assert error if remove an event listener twice at the same time

[FIX] Core: FileUtils::getValueMapFromFile() returns wrong value if it is a number with scientific notation on Android

[FIX] Core: UIGrayScale shader is not reloaded when reloading shaders

[FIX] Core: `SpriteFrame::clone()` doesn't clone polygonInfo

[FIX] Core: `FileUtils::createDirectory()` fails on Mac OS with sandbox

[FIX] Core: `cocos2d::Value` operator overloading of comparison `==` returns wrong value in case Type::VECTOR

[FIX] Core: wrong content size if minisize

[FIX] Core: can not have a class named `Game` on Windows

[FIX] Core: crash if load bad image on Windows

[FIX] Core: custom shader uniforms and attributes do not have effect in DrawNode

[FIX] Core: blend mode doesn't work with animated sprite

[FIX] Core: `FileUtils::removeDirectory()` can not work correctly when the path is not end of `/` on iOS and Mac

[FIX] JSB: fix some bugs related with JSB debegger

[FIX] JSB: scheduler callback target lost

[FIX] JSB: missing scroll widgets constants

[FIX] JSB: if obj is undefined or null then attempt to access obj.__nativeObj leads to incorrect behavior

[FIX] JSB: use `require()` to require the same script twice may crash

[FIX] Lua: lua function is not invoked when error happens in websocket

[FIX] Network: HttpClient Content-type limitation on iOS

[FIX] Network: downloader crash when storage path contains spaces

[FIX] Network: SocketIO crash on reconnect

[FIX] Physics: PhysicsBody damping doesn't wrok

[FIX] UI: EditBox may cause `java.lang.IndexOutOfBoundsException` exception on Android

[FIX] UI: TextFieldTTF doesn't show password correctly

[FIX] UI: RichText crash on Windows

[FIX] UI: EditBox can not use custom font on Android

[FIX] UI: can not use TTF font on Android

[FIX] RenderTexture: `setOpacity()` has not effect

[FIX] 3D: `Sprite3D::createNode()` may not work correctly with particular model data

[FIX] Web: `getParentToNodeTransform` doesn't return result

[FIX] Web: remote image without extension in url can't be loaded as image

[FIX] Web: nested clipping nodes rendering issue in WebGL render mode

[FIX] Web: IMEDispatcher can't work in mobile Chrome

 

Cocos2d-x is available here.

GameDev News

Month List

Popular Comments

A complete PlayStation Vita game from scratch: Part One
Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon


7. September 2012

 

In this series we are going to create a complete Pong clone using the PlayStation Mobile SDK.  The main purpose is to show how all the various pieces ( GameEngine2D, Physics2D, Scenes, Audio, etc… ), fit together to create a full game, something the current documentation doesn’t really

The end results of this tutorial series ( minus sound… it has sound too )
cover.  This tutorial series is going to assume you have already gone through the other PlayStation Mobile tutorials on this site, so I may not be going in to detail on areas that have already been covered.

 

 

I am going to present in the following format.  I will specify the filename, then give the complete source code, followed by a nearly line by line explanation of what the source is doing.

 

 

To complete this tutorial, you are going to need to add references to the libraries Sce.PlayStation.HighLevel.GameEngine2D, Sce.PlayStation.HighLevel.Physics2D and Sce.PlayStation.HighLevel.UI. There is a bug in the PlayStation Mobile Studio that causes auto completion of newly added libraries to not work unless a) you reload the project b) you add ( then remove ) another library c) you exit and restart Studio.

 

Let’s jump right in.

 

AppMain.cs

 

using System;
using Sce.PlayStation.HighLevel.UI; 
using Sce.PlayStation.HighLevel.GameEngine2D;

namespace Pong
{
    public class AppMain
    {
        public static void Main (string[] args)
        {
            Director.Initialize();
            UISystem.Initialize(Director.Instance.GL.Context);
            Director.Instance.RunWithScene(new TitleScene());                
        }
    }
}

 

Every C# application has a Main, and as you can see, ours does remarkably little.  Thanks to the Scene based organization of GameEngine2D, it is fairly easy to divide out your application into logical chunks.  Here we initialize the Director and UISystem singletons, create and run a TitleScene scene, to predictably enough, display a title screen.  Let’s look at that now.

 

TitleScene.cs

 

using System;
using Sce.PlayStation.Core;
using Sce.PlayStation.Core.Graphics;
using Sce.PlayStation.Core.Audio;
using Sce.PlayStation.HighLevel.GameEngine2D;
using Sce.PlayStation.HighLevel.GameEngine2D.Base;
using Sce.PlayStation.Core.Input;
 
namespace Pong
{
    public class TitleScene : Scene
    {
        private TextureInfo _ti;
        private Texture2D _texture;
        
        private Bgm _titleSong;
        private BgmPlayer _songPlayer;
        
        public TitleScene ()
        {
            this.Camera.SetViewFromViewport();
            _texture = new Texture2D("Application/images/title.png",false);
            _ti = new TextureInfo(_texture);
            SpriteUV titleScreen = new SpriteUV(_ti);
            titleScreen.Scale = _ti.TextureSizef;
            titleScreen.Pivot = new Vector2(0.5f,0.5f);
            titleScreen.Position = new Vector2(Director.Instance.GL.Context.GetViewport().Width/2,
                                              Director.Instance.GL.Context.GetViewport().Height/2);
            this.AddChild(titleScreen);
            
            Vector4 origColor = titleScreen.Color;
            titleScreen.Color = new Vector4(0,0,0,0);
            var tintAction = new TintTo(origColor,10.0f);
            ActionManager.Instance.AddAction(tintAction,titleScreen);
            tintAction.Run();
            
            _titleSong = new Bgm("/Application/audio/titlesong.mp3");
            
            if(_songPlayer != null)
            _songPlayer.Dispose();
            _songPlayer = _titleSong.CreatePlayer();
            
            Scheduler.Instance.ScheduleUpdateForTarget(this,0,false);

            // Clear any queued clicks so we dont immediately exit if coming in from the menu
            Touch.GetData(0).Clear();
        }
        
        public override void OnEnter ()
        {
            _songPlayer.Loop = true;
            _songPlayer.Play();
        }
        public override void OnExit ()
        {
            base.OnExit ();
            _songPlayer.Stop();
            _songPlayer.Dispose();
            _songPlayer = null;
        }
        
        public override void Update (float dt)
        {
            base.Update (dt);
            var touches = Touch.GetData(0).ToArray();
            if((touches.Length >0 && touches[0].Status == TouchStatus.Down) || Input2.GamePad0.Cross.Press)
            {
                Director.Instance.ReplaceScene(new MenuScene());
            }
        }
    
        ~TitleScene()
        {
            _texture.Dispose();
            _ti.Dispose ();
        }
    }
}
 

 

This code creates a title screen, loops the background music and waits for the user to touch the screen, at which point it displays the main menu scene.  Let’s take a closer look.

 

private TextureInfo _ti;
private Texture2D _texture;
        
private Bgm _titleSong;
private BgmPlayer _songPlayer;

 

First we declare our member variables.  A TextureInfo holds a texture, and important UV information about it, especially if that texture contains multiple sprites.  Texture2D is the texture itself and holds the image pixel data.  Bgm is a class for holding a music file ( Bgm == background music ), while a BgmPlayer is predictably enough, for playing a Bgm file.  It is important to note, all 4 of these classes implement IDisposable, so you need to release them when you are done, or you will leak memory.

 

public TitleScene ()
    {
        this.Camera.SetViewFromViewport();
        _texture = new Texture2D("Application/images/title.png",false);
        _ti = new TextureInfo(_texture);
        SpriteUV titleScreen = new SpriteUV(_ti);
        titleScreen.Scale = _ti.TextureSizef;
        titleScreen.Pivot = new Vector2(0.5f,0.5f);
        titleScreen.Position = new Vector2(Director.Instance.GL.Context.GetViewport().Width/2,
                                       Director.Instance.GL.Context.GetViewport().Height/2);
        this.AddChild(titleScreen);

 

This code is the first half of our constructor, called when the class is created.  First thing we do is calibrate the scene camera ( TitleScene inherited from Scene which has a camera property ) to set it’s dimensions to match the full viewport.  Next we load the texture title.png from the images folder.  By default, all folders and files added to a project will be under the /Application folder when you run.  Note, these files are all read only!  If you need write access, you need to put them in special folders, described elsewhere in the tutorials.  The false in Texture2D’s constructor is to indicate we do not want to generate a mipmap.  ( A mip map is a special multi resolution version of a texture, used for variable levels of detail, and is not applicable to this application ).

 

One we have loaded our texture, we pass it to the constructor TextureInfo.  Again, TextureInfo simply holds a texture and UV information to go with that texture.  We then use the TextureInfo in our constructor to SpriteUV, which is the actual graphic we are going to display on screen.  All of the graphics in our game are going to be SpriteUVs, and our title screen is no exception.  Now that we have created our title screen graphic, we set it’s size equal to the pixel size of the source image, set it’s pivot to it’s middle point, and it’s position to the center of the screen. 

 

Two important concepts here are the Pivot point and Positioning. The pivot is the location your sprite is going to be transformed relative to, by setting it to the middle of the sprite, this makes rotating a heck of a lot easier, but you now have to remember, when your objet is at say (0,0), only a quarter of it will be visible on screen.  So when checking boundaries, you will have to add half the width and/or height to the equation.  Pivot is represented as a pair of x,y coordinates going from 0 to 1.  (0,0) is the bottom left corner of the sprite, while (1,1) would be the top right.  Obviously then, (0.5,0.5) is the middle.

 

The positioning in GameEngine2D starts at the bottom left corner of the screen.  This is taken from Cocos2D, which GameEngine2D is modeled on, which in turn takes it from OpenGL.  If you are used to the origin being at the top left, this can take a bit of getting used to. Director.Instance.GL.Context allows you some access to the underlying OpenGL context, and will be used quite often throughout the application.  The Director singleton does take care of most of the gritty rendering details, so we wont have to get too low level.  Finally AddChild() adds the child to the scene for displaying and updating.

 

 

    Vector4 origColor = titleScreen.Color;
    titleScreen.Color = new Vector4(0,0,0,0);
    var tintAction = new TintTo(origColor,10.0f);
    ActionManager.Instance.AddAction(tintAction,titleScreen);
    tintAction.Run();
        
    _titleSong = new Bgm("/Application/audio/titlesong.mp3");

    if(_songPlayer != null)
        _songPlayer.Dispose();
    _songPlayer = _titleSong.CreatePlayer();
            
    Scheduler.Instance.ScheduleUpdateForTarget(this,0,false);
            
    // Clear any queued clicks so we dont immediately exit if coming in from the menu
    Touch.GetData(0).Clear();
    }

 

This is the second half of our constructor and most of it revolves around an easy special effect.  First we are caching a copy of the titleScreen’s current color value.  We then set the color to black and completely transparent ( color is made up of four numbers, the Red, Green, Blue as well as Alpha ( transparency ) values, ranging from 0 (none) to 255(full)).  Next we create an Action of type TintTo and over a period of 10 seconds, revert our color back to normal.  Finally we register our action using the ActionManager singleton’s AddAction() method, passing in the action to run, as well as the target node to perform the action on.  Think of actions as reusable “threads” of activity to perform various tasks on Nodes.  If you look at the class hierarchy of GameEngine2D, you will discover most of the class are inherited from Node and can thus have actions performed on them.  ( Scene and SpriteUV are both derived from Node ).  Now that our action is created and registered, we simply run it.  The end result of all of this is the title screen graphic will fade from black to full color over a period of 10 seconds.

 

Next up we load our title song from disk in the folder audioAgain, all folders by default are added under the Application folder and are read only.  Bgm files only support the mp3 format.  The only method of importance for a Bgm file is CreatePlayer() which creates a BgmPlayer instance.  A warning up front, the lifecycle of BgmPlayer is extremely odd, there is something going on behind the scenes with these classes that makes dealing with them extremely irritating, which is why you see a Dispose() call on a class that shouldn’t possibly exist.  Next we register our Scene class with the Scheduler singleton.  This singleton is responsible for calling Update each frame.  The end result is that our Update() method will get called each frame ( ideally 60 times a second ).  The second parameter ( 0 ) is used to set the priority that Scheduler should give your classes Update() calls, but it is currently ignored.  The final parameter to ScheduleUpdateForTarget is simply telling Scheduler if we want to start with our updating paused, which we don’t.  The last line is a bit of a hack, but a required one.  Later on, we will return to the TitleScreen from a different direction, and it is possible that if the user double tapped the screen that a tap is queued up to be processed, which would result in the title screen immediately going away.  This line simply clears out all outstanding touch events to prevent this possibility.

 

public override void OnEnter ()
    {
        _songPlayer.Loop = true;
        _songPlayer.Play(); 
    }
    public override void OnExit ()
    {
        base.OnExit ();
        _songPlayer.Stop();
        _songPlayer.Dispose();
        _songPlayer = null;
    }

OnEnter() is called when your Scene is actually displayed.  It is called after the constructor and it is possible for your Scene to potentially be shown and hidden multiple times.  OnExit() is called when your scene is replaced.  We our scene is first displayed, we start our background music playing and we want it to loop.  On exit, we stop and dispose of the sound and _songPlayer.  Again, managing the memory on these classes is tricky, there is something odd behind the scenes.

 

public override void Update (float dt)
{
    base.Update (dt);
    var touches = Touch.GetData(0).ToArray();
    if((touches.Length >0 && touches[0].Status == TouchStatus.Down) || Input2.GamePad0.Cross.Press)
    {
        Director.Instance.ReplaceScene(new MenuScene());
    }
}

 

This is the method that the Scheduler will call every frame.  It is called before rendering occurs.  Dt represents the elapsed time, in seconds, since Update was last called.  All we are doing here is checking to see if any touches have occurred, or if the user pressed the Cross ( X ) gamepad button, in which case we replace the scene with our MenuScene, which we will create shortly.  Basically, update sits around waiting for the user to tap the screen or hit X, in which case it loads and displays the menu.

 

 

~TitleScene()
    {
        _texture.Dispose();
        _ti.Dispose ();
    }

 

Finally out destructor that, which simply disposes of the title screen Texture2D and TextureInfo objects.  We dispose of the BGMPlayer when the scene changes.  The Bgm file is apparently leaked, but really isn’t.  As I said, something odd is going on.  Play around with the lifecycle of BgmPlayer and Bgm and you will see what I mean!

 

 

 

The resources

 

Our game requires a number of media files, the following is a description of each.  You can use mine or create your own, I release all files ( I own ) to the public domain free of constraints.  You need to create a pair of folders in your project ( within PlayStation Mobile Studio ), audio and images.  For each file, be sure to add it the the appropriate sub folder, then right click it in the Solution panel, and set it’s build action to content!  This step is very important, or you may receive errors when you try to run your application.

 

In the end, your project should look like this:

 

image

 

Now the files.  In the final part of this tutorial, I will make the entire project available as a zip file, but you can grab individual resources below.

ball.png

ball

paddle.png

Paddle

 

title.png

title

 

winner.png

winner

 

loser.png

loser

 

 

In the next part we will create the menu scene, making use of the UI library.

 

Programming , ,

blog comments powered by Disqus

Month List

Popular Comments