IwGame Engine Tutorial – Scenes

CIwGameScene Object – A Place for Actors to Play


Its easier to think about game development if we think in terms of the movie business, we all watch movies and programmes on the TV which makes it easy to relate to.

A movie usually consists of a number of scenes that contains the environment, actors and cameras. At the moment, IwGame only supports actors and cameras (environments may be added at a later date).

A CIwGameScene is responsible for the following functionality:

  • Setup and handling of the virtual canvas
  • Managing, updating and cleaning up actors
  • Managing, updating, rendering and cleaning up sprites
  • Managing and clean up of animation data
  • Managing and clean up of animation timelines
  • Managing and clean up of Marmalade resource groups
  • Managing and clean up of images
  • Managing and clean up of physics materials and shapes
  • Clipping sprites against the scenes visible extents
  • Updating the camera
  • Tracking actors that can potentially collide
  • Transitions between scenes
  • Updating the scenes animation timeline
  • Instantiating itself from XOML
  • Managing and clean up of XOML variables
  • Updating physics

Its also worth a major note at this point that any actors that live inside a scene will be transformed by the same transform as the scene, so if you move, scale or spin the scene then the contained actors will also move, scale and spin with it. The same can also be said about the base colour of the scene

Creating a Scene

Creating a scene is very simple, as the following code shows:

	CIwGameScene* game_scene = new CIwGameScene();
	game_scene->setVirtualTransform(VIRTUAL_SCREEN_WIDTH, VIRTUAL_SCREEN_HEIGHT, 0, true, false);

In the above code snippet we allocate a new CIwGameScene object and called its Init() method to set up scene internals. We give the scene a name so we can find it later then set the virtual transform (see next section for explanation of the virtual canvas). Finally we ask the game to change the current scene to our newly created scene (CIwGame::ChangeScene())

You can create as many scenes as you like and add them to the game, just remember only one can be the active scene, but all visible scenes will be rendered.

I would like to add some additional information regarding CIwGameScene::Init(), its prototype looks like this:

int	Init(int max_collidables = 128, int max_layers = 10);

As you can see, the method actually takes two parameters (defaults are applied so you can go with the defaults if you like). The two additional parameters are defined as:

  • max_collidables – This the maximum size of the collidable objects list and should be as large as the maximum number of objects that can possibly collide in your scene. For example, if you have 100 objects that are marked as collidable then you can set this value to 100
  • max_layers – Scenes support object layering, the default number of layers is set to 10, but you can change this value here

If you would like to prevent the internal Box2D physics engine update then set the scenes WorldScale to 0:

	game_scene->getBox2dWorld()->setWorldScale(0, 0);

This stops the internal Box2D physics update. It can be re-enabled by changing WorldScale to a valid value.

Virtual Canvas

Targeting a large selection of different phones, tablets and other devices with a variety of screen sizes and aspect ratios is a bit of a nightmare when it comes to game development. Luckily the CIwGameScene class takes care of this for us. A scene is quite a clever object in that it can render itself to any sized / configuration display using the virtual canvas concept. A virtual canvas is basically our own ideal screen size that we want to render to. The scene will scale and translate int visuals to fit our canvas onto the devices display allowing us to get on with developing our game using a static resolution. Lets take a look at the prototype for setting a scenes virtual canvas:

	void	CIwGameScene::setVirtualTransform(int required_width, int required_height, float angle, bool fix_aspect = false, bool lock_width = false);

And an explanation of its parameters:

  • required_width – The width of the virtual canvas
  • required_height – The height of the virtual canvas
  • angle – Angle of the virtual canvas
  • fix_aspect – Forces the rendered canvas to lock to the devices aspect ratio (you may see letter boxing or clipping)
  • lock_width –Calculates scale based on screen_width / required_width if set true, otherwise scale based on screen_height / required_height.
  • 3.4 Scene Object Management
  • When it comes to coding I am quite bone idle and hate having to track things such as allocating actors, images / memory for animations etc,. I want something that will let me allocate these types of objects, assign them then forget about them. CIwGameScene contains a SpriteManager, and a ResourceManager (will cover these in detail later) that takes care of the things that I don’t want bothering with during development. In addition, if I remove a scene from the game CIwGameScene will clean the lot up for me when it gets destroyed.

This automated clean-up does come at a very small price however, if you want to add a resource group to the scene then you will need to do that through the scene itself. Here’s an example:

	// Create and load a resource group
	CIwGameResourceGroup* level1_group = new CIwGameResourceGroup();
	// Add the resource group to the scenes resource manager

As you can see we need a reference to the scene so that we can get to the resource manager. Not too painful, but thought it best to make you aware of this small caveat.

Scene Extents and Clipping

Scenes have an extents area that can be defined which defines the area in which actors can be, actors that are outside of the scenes extents are wrapped around to the other side of the scene. This behaviour can be enabled / disabled on a per actor basis. You can set the scenes extents by calling:

	void CIwGameScene::setExtents(int x, int y, int w, int h);

Scenes also allow you to define a visible clipping area, pixels from the scene that fall outside that area will not be drawn. You can set the clipping area of a scene by calling:

	void CIwGameScene::setClippingArea(int x, int y, int w, int h);

The default behaviour is for the clipping area to move with the scenes camera, but this can be disabled by enabling the scenes ClipStatic state. When ClipStatic is true, the scenes clipping rectangle will remain static on screen, whilst the contents move around inside the clipping area.

Scene Camera

A scene has a camera associated with it that allows the user to pan around the scene as well as rotate and scale the view. All actors within the scene will move / rotate and scale in relation to the camera. It is possible to switch cameras within a scene, although you will need to manage the lifetime of these cameras, the scene will only manage the currently attached camera (so do not delete it a camera if it is assigned to the scene. You can assign a camera to the scene using:

	void CIwGameScene::setCamera(CIwGameCamera* camera);

Potential Colliders and Collision Handling

As a scene processes actors it will build a list of references to all actors that are marked as possibly colliders, once all actors have been processed the scene will walk the list of potential colliders and call their ResolveCollisions() method to give each actor a chance to handle its own collisions. Note that the scene does NOT handle collision detection and response, actors themselves should take care of that.

Note that actors that have a physics material attached are under the control of the Box2D physics engine and collision is handled separately (more on this in the actors section)


Current Scene Concept

Because the game consists of multiple scenes and only one scene can have the focus at any one time we use the concept of the current scene. Whilst all scenes are visible (unless made hidden) and rendered they are not all processed. By default the only scene that is processed is the current scene. It is however possible to force a scene to be processed even when it does not have the focus by calling CIwGameScene::setAllowSuspend(false). This will prevent the scene from being suspended when another scene is made the current scene.

Scenes can exist in two states, suspended or operational (resumed). Suspending scenes are not processed but are still rendered. When a new scene is switched to using CIwGame::changeScene(CIwGameScene* new_scene) the old scene will be put into a suspended state and the new scene will be resumed. IwGame will notify you when either of these events occur via the following methods:

virtual void	NotifySuspending(CIwGameScene* new_scene)    // This event is called when this scene is being suspended
virtual void	NotifyResuming(CIwGameScene* old_scene)      // This event is called when this scene is being resumed
virtual void	NotifyLostFocus(CIwGameScene* new_scene)     // This event is called when this scene has just lost focus
virtual void	NotifyGainedFocus(CIwGameScene* old_scene)   // This event is called when this scene has just gained focus

In order to receive these events you should implement them in your derived scene class, e.g.:

void	MyGameScene::NotifySuspending(CIwGameScene* new_scene)
	// Add code to handle the scene being suspended

Note that you do not need to derive your own scene class from CIwGameScene as long as you are happy with the generic functionality that it ptovides, however you will not have access to the suspend / resume functionality as C style callbacks are not used in this instance.

You can tie into these events in XOML by implementing the OnSuspend /OnResume events, e.g.:

    <Scene Name="GameScene3" OnSuspend="SuspendActions">
        <Actions Name="SuspendActions">
            <Action Method="ChangeScene" Param1="GameScene2" />
            <Action Method="PlayTimeline" Param1="GameScene3Anim" />
            <Action Method="PlaySound" Param1="Explosion" />

When the scene is suspended, the actions set SuspendedActions will be executed.

Actor Management

The main reason that scenes exist is to facilitate actors. Once an actor is created and added to a scene the scene handles their update, rendering and clean up. CIwGameScene contains the following methods for adding, removing and searching for actors within a scene:

void				addActor(CIwGameActor *actor);
void				removeActor(CIwGameActor* actor);
void				removeActor(unsigned int name_hash);
CIwGameActor*			findActor(const char* name);
CIwGameActor*			findActor(unsigned int name_hash);
CIwGameActor*			findActor(int type);
void				clearActors();


Scene Naming and Finding Scenes

IwGame is designed to prevent what I like to call “unreliable references”. To me an unreliable reference is a reference to an another object that can disappear at any moment without the object that references it knowing about it, this can lead to some pretty nasty bugs that are incredibly difficult to track down. So instead of simply keeping a reference to an object we keep a name.

IwGame uses object naming quite extensively for major system such as actors and scenes. The idea is that if we want to speak to a scene from somewhere outside that scenes instance we simply find it by name using CIwGame::findScene(). Once found we can grab a pointer to it and access it. The wonderful thing about this system is that if the scene has disappeared when we call findScene() a NULL pointer will be returned signifying that it no longer exists, allowing our calling code to determine what to do about it (as opposed to simply crashing or doing something even worse such as writing all over memory that its not supposed to).

The naming system does add a little overhead to our game but not a great deal as searches are done using string hashes instead of string comparisons. The tiny overhead is definitely worth the buckets of tears that you can potentially save from days of tracking down hard to find bugs.


Scene Layers

Actors within a scene can be depth sorted using layers. Each actor has its own layer number which decides where it will appear within the scenes depth tree. Actors on higher layers will appear over actors on lower layers. Actors on the same layer will be drawn in the order in which they were added to the layer, so later actors will be drawn on top of earlier added actors.

Note that the layering system is not strictly part of the scene engine, instead it is handled by the sprite manager contained within a scene, but for the purpose of easy access is accessible through the scene.


Scene Origin

A scenes origin is set at 0, 0, which is the centre of the virtual canvas (usually centre of screen) for the default transform.


Scene Visibility and Active State

Scenes can be made visible or invisible by calling CIwGameScene::setVisible(). You can also query the visibility of a scene using CIwGameScene::isVisible(). When a scene is invisible it is not rendered.

Scenes can also be made active or inactive by calling CIwGameScene::setActive(). You can also query the active state of a scene by calling CIwGameScene::isActive(). When a scene is active it is processed.

Note that a scenes active and visibility states are independent, an inactive scene will still be rendered and an invisible scene that is active will still be processed.


Scene Transitions

Scene transitions are taken care of by the timeline system. A quick scroll scene transition is shown below:

    <Animation Name="SceneTransition1" Type="vec2" Duration="2" >
        <Frame Value="0, 0"    Time="0.0" />
        <Frame Value="480, 0"  Time="2.0" />

    <Scene Name="GameScene" …..... OnSuspend="SuspendActions">
        <Actions Name="SuspendActions">
            <Action Method="SetTimeline" Param1="SceneTransition1" />
        <Timeline Name="SceneTransition1" AutoPlay="true">
            <Animation Anim="SceneTransition1" Target="Position" Repeat="1" StartAtTime="0"/>

In the above XOML we create a scene and attach the SuspendActions collection to the OnSuspend scene event. Note that the timeline was defined inside the scene because it is not requested until some actor actually suspends the scene. Here’s an example showing an actor that raises the scene suspended event when it is tapped:

    <TestActor Name="Player4" ...... OnTapped="SuspendScene3">
        <Actions Name="SuspendScene3">
           <Action Method="SuspendScene" Param1="GameScene3" />


Creating a Scene from XOML

Scenes can be created declaratively using XOML mark-up, making scene creation much easier and more readable. Below shows an example of a scene declared using XOML:

    <Scene Name="GameScene" CanvasSize="320, 480" FixAspect="true" LockWidth="false" Colour="0, 0, 255, 255" AllowSuspend="false">

The scene tag supports many different attributes that determine how a scene is created and how it behaves. A description of these tags are listed below:

  • Name – Name of the scene (string)
  • Type – Type of scene (integer)
  • CanvasSize – The virtual canvas size of the screen (x, y 2d vector)
  • FixAspect – Forces virtual canvas aspect ratio to be fixed (boolean)
  • LockWidth – Forces virtual canvas to lock to with if true, height if false (boolean)
  • Extents – A rectangular area that describes the extents of the scenes world (x, y, w, h rect)
  • AllowSuspend – Determines if the scene can be suspended when other scenes are activated (boolean)
  • Clipping – A rectangular area that represents the visible area of the scene (x, y, w, h rect)
  • Active – Initial scene active state (boolean)
  • Visible – Initial scene visible state (boolean)
  • Layers – The number of visible layers that the scene should use (integer)
  • Layer – The visual layer that this scene should be rendered on (integer)
  • Colliders – The maximum number of colliders that the scene should support (integer)
  • Current – If true then the scene is made the current scene (boolean)
  • Colour / Color – The initial colour of the scene (r, g, b, a colour)
  • Timeline – The time line that should be used to animate the scene
  • Camera – Current camera
  • OnSuspend – Provides an actions group that is called when the scene is suspended
  • OnResume – Provides an actions group that is called when the scene is resumed
  • OnCreate – Provides an actions group that is called when the scene is created
  • OnDestroy – Provides an actions group that is called when the scene is destroyed
  • OnKeyBack – Provides an actions group that is called when the user presses the back key
  • OnKeyMenu – Provides an actions group that is called when the user presses the menu key
  • Gravity – Box2D directional world gravity (x, y 2d vector)
  • WorldScale – Box2D world scale (x, y 2d vector)
  • Batch – Tells the system to batch sprites for optimised rendering (boolean)
  • AllowFocus – If set to true then this scene will receive input focus events that the current scene would usually receive exclusively. This is useful if you have a HUD overlay that has functionality but it cannot be the current scene as the game scene is currently the current scene1Anim
  • DoSleep – If set to true then actors that utilise physics will eb allowed to sleep when they are not moving / interacting


Animating Scene Components

Scenes allow an animation time line to be attached to them that animates various properties of the scene. The following properties are currently supported:

  • Camera Position – Cameras current position
  • Camera Angle– Cameras current angle
  • Camera Scale– Cameras current scale
  • Colour – Scenes current colour
  • Clipping – Scenes current clipping extents
  • Visible – Scenes current visible state
  • Timeline – The currently playing timeline
  • Camera – change current camera

Any of these properties can be set as an animation target


Creating a Custom Scene

Whilst CIwGameScene can suffice for most tasks, you may find that you need to create your own type of scene that has functionality specific to your game or app. You begin the creation of a custom scene by deriving your own scene class from CIwGameScene then overloading the following methods to provide implementation:

	virtual int	Init(int max_collidables = 128, int max_layers = 10);
	virtual void	Update(float dt);
	virtual void	Draw();

Here’s a quick example:

class MyGameScene : public CIwGameScene
	MyGameScene() : CIwGameScene() {}
	virtual ~MyGameScene();

	virtual int		Init(int max_collidables = 128, int max_layers = 10)
		CIwGameScene::Init(max_collidables, max_layers);
	virtual void	Update(float dt)
	virtual void	Draw()

We have provided a very basic implementation of Init(), Update() and Draw() which call the base CIwGameScene class methods so we keep its functionality in-tact.

You can take the implementation one step further (or maybe two) by implementing both the IIwGameXomlResource and IIwGameAnimTarget interfaces to allow instantiation of your custom class from XOML and to allow your class to be a target for animation time lines.

Firstly lets take a look at XOML enabling your custom scene class. To get IwGame to recognise your class whilst parsing XOML files you need to do a few things:

Derive your class from IiwGameXomlResource and implement the LoadFromXoml method
Create a class creator that creates an instance of your class then add this to the XOML engine

Lets start by taking a look at step 1.

Because we have derived our class from CIwGameScene we already have the support for step 1. However we would like to insert our own custom attribute tags so we need to make a few changes.

Lets take a look at our new class with those changes:

class MyGameScene : public CIwGameScene
	// Properties
	float		Gravity;
	void		setGravity(float gravity)	{ Gravity = gravity; }
	float		getGravity() const		{ return Gravity; }
	// Properties End
	MyGameScene() : CIwGameScene(), Gravity(10.0f) {}
	virtual ~MyGameScene();

	virtual int		Init(int max_collidables = 128, int max_layers = 10)
		CIwGameScene::Init(max_collidables, max_layers);
	virtual void	Update(float dt)
	virtual void	Draw()

	// Implementation of IIwGameXomlResource interface
	bool	LoadFromXoml(IIwGameXomlResource* parent, bool load_children, CIwGameXmlNode* node)
		if (!CIwGameScene::LoadFromXoml(parent, load_children, node))
			return false;

		// Add our own custom attribute parsing
		for (CIwGameXmlNode::_AttribIterator it = node->attribs_begin(); it != node->attribs_end(); it++)
			unsigned int name_hash = (*it)->getName().getHash();

			if (name_hash == CIwGameString::CalculateHash("Gravity"))

		return true;

Our new class now basically supports a Gravity attribute that we will eventually be able to set in XOML using something like:

    <MyGameScene Name="GameScene" Gravity="9.8">

However, before we can do that we need to let the XOML system know about our new type of class (MyGameScene), so it can be instantiated when the XOM parser comes across it. To do this we need to create a creator:

class MyGameSceneCreator : public IIwGameXomlClassCreator
	IIwGameXomlResource* CreateInstance(IIwGameXomlResource* parent) { return new MyGameScene(); }

The creator basically defines the tag name “MyGameScene” and returns an instance of the MyGameScene class when CreateInstance() is called.

To get the XOML system to recognise our creator we need to add it to the XOML parsing system using:

	// Add custom MyGameScene to XOML system
	IW_GAME_XOML->addClass(new MyGameSceneCreator());

Now XOML integration is out of the way, lets take a quick look at enabling our class as an animation target.

To enable a class as an animation target we derive it from IIwGameAnimTarget and implement the UpdateFromAnimation() method. Luckily we derived our MyGameScene class from the CIwGameScene class which already provides this functionality. Lets take a quick look at how we extend the animation update method to account for animating our gravity variable.

	bool	UpdateFromAnimation(CIwGameAnimInstance *animation)
		if (CIwGameScene::UpdateFromAnimation(animation))
			return true;

		// Add our own custom animating property
		unsigned int element_name = animation->getTargetPropertyHash();

		if (element_name == CIwGameString::CalculateHash("Gravity"))
			CIwGameAnimFrameFloat* frame = (CIwGameAnimFrameFloat*)animation->getCurrentData();
			return true;

		return false;

We added the above code to our MyGameScene class definition. We begin by calling the base UpdateFromAnimation() method so we can keep the existing animation properties of the scene. We then add our own custom check for the Gravity variable. If the animation property matches Gravity then we set the gravity to the provided interpolated value.


Creating Custom Actions

XOML’s event / action system is very powerful, allowing you to tie certain events to collections of actions without writing any code. Lets take a quick look at an example:

        <!-- Create back button -->
        <InertActor Name="Back" Position="-120, 10" Size="200, 90" SrcRect="600, 333, 200, 90" Image="sprites2" OnTapped="BackAction" OnBeginTouch="BackBeginTouch" OnEndTouch="BackEndTouch">
            <Actions Name="BackAction">
                <Action Method="SetTimeline" Param1="fly_out_back" Param2="PauseMenu" />
            <Actions Name="BackBeginTouch">
                <Action Method="SetTimeline" Param1="buttonin_anim1" />
                <Action Method="PlaySound" Param1="ui_tap" />
            <Actions Name="BackEndTouch">
                <Action Method="SetTimeline" Param1="buttonout_anim1" />

In the above XOML our actor handles the events OnEndTouch, OnTapped and OnBeginTouch. Each of these events calls an actions list when the event occurs on that object. Below the actor definition we have three action lists defined that correspond to the actions that are specified in our events:

            <Actions Name="BackAction">
                <Action Method="SetTimeline" Param1="fly_out_back" Param2="PauseMenu" />

            <Actions Name="BackBeginTouch">
                <Action Method="SetTimeline" Param1="buttonin_anim1" />
                <Action Method="PlaySound" Param1="ui_tap" />

            <Actions Name="BackEndTouch">
                <Action Method="SetTimeline" Param1="buttonout_anim1" />

The first action collection “BackAction” is called when a user performs a tap action on “Back” actor. This collection contains a single action which contains a method called “SetTimeline” and two parameters “fly_out_back” and “PauseMenu”.

This action actually changes the time line of the PauseMenu object to the fly_out_back animation time line (defined elsewhere in XOML). However, how does the system know how to do this and more importantly how do we define our own actions that we can call from XOML events?

Well firstly it depends on where the action is being called as certain object types have their own list of actions. In addition, there is also a global list of actions carried by the global resource manager.

Here we will take a look at adding our own custom action to the global resource manager.

The first thing we need to do is derive a class from IIwGameXomlAction and implement the Execute() method like this:

class CustomXomlAction_Global : public IIwGameXomlAction
	CustomXomlAction_Global() {}
		// Set out action name
	void Execute(IIwGameXomlResource* source, CIwGameAction* action)
		CIwGame* game = NULL;
		CIwGameScene* scene = NULL;
		CIwGameActor* actor = NULL;

		// Determine the scene, game and possibly actor that called the action
		if (source->getClassTypeHash() == CIwGameXomlNames::Scene_Hash)
			scene = (CIwGameScene*)source;
			game = scene->getParent();
		if (source->getClassTypeHash() == CIwGameXomlNames::Actor_Hash)
			actor = (CIwGameActor*)source;
			scene = actor->getScene();
			game = scene->getParent();

		// TODO: Do something with the action here (Param1 and Param2 contain parameters


Now that we have an action object we need to tell the XOML system that its available using:

IW_GAME_XOML->addAction(new CustomXomlAction_Global());

We would place this call somewhere in our main boot up so it gets called before any XOML parsing that contains this action begins.

Now lets take a look at a bit of XOML that shows the use of our new action:

    <Actions Name="BackAction">
        <Action Method="CustomeAction1" Param1="Hello World!" Param2="Im an action!" />


Augmenting Scenes

A scene once declared in XOML can later be updated / augmented with additional XOML code elsewhere. For example, lets say that you declare some common scene that contai9ns a basic background and some other elements that are common across a number of screens. You can later load the scene and then augment it by declaring the scene again then supplying the additional elements inside the newly declared scene:

    <Scene Name="CommonScene" ............ >
        <Original_Element1 />
        <Original_Element2 />
        <Original_Element3 />

Now declare a 2nd scene with the same name:

    <Scene Name="CommonScene">
        <Extra_Element1 />
        <Extra_Element2 />
        <Extra_Element3 />

In memory the scene now looks like this:

    <Scene Name="CommonScene" ............ >
        <Original_Element1 />
        <Original_Element2 />
        <Original_Element3 />
        <Extra_Element1 />
        <Extra_Element2 />
        <Extra_Element3 />

Marmalade SDK Tutorial – Actors, Scenes and Cameras Make the World Go Round

This tutorial is part of the Marmalade SDK tutorials collection. To see the tutorials index click here

In our previous tutorial we created an extensible animation system that allowed us to create discrete frame based image animation as well as other types of animations. This week we will continue on our quest to create an easy to use, extensible cross platform 2D game engine. In order to do this effectively we need to get organised and organised we will be. If you just want the code to this tutorial then download it from here.

Ok, so how do we organise things in a 2D engine? What sort of things do we want our 2D engine to do? Here’s a brief list:

  • We want sprites and animations obviously, these we already covered in previous tutorials
  • We want sprite creation / handling to be automated so that we do not have to worry about creating, updating and destroying sprites
  • We want to define specific types of game objects (players, bombs, aliens, pickups etc..) modelled on a single game object type
  • We want scenes that contain our game objects, managing their life times and updates
  • We want cameras that we can move around in our scene to view different parts of the scene.
  • We want our game objects to recognise when they collide with each other and react to each other

To manage all of the above we are going to create a Camera, Actor, Scene (CAS) system.

Cameras, Actors and Scenes

The camera, actor and scene system (CAS) constitutes the logical implementation of our game engine. The scene represents our finite gaming world, whilst actors represent our individual game objects that live within our gaming world. The scene manages all of our actors for us, taking care of updating them and deleting them when they are no longer needed. The camera represents a view into the gaming world that can be moved around, rotated and scaled to view different parts of the world.

CIwGameActor – Our game objects are really just actors on a stage

Ok, we will begin by taking a look at the CIwGameActor class:

class CIwGameActor { protected: // Properties CIwGameScene* Scene; // Scene that actor lives in bool Used; // Used is used when actors pooled to reduce memory fragmentation bool Managed; // Marks this actor as being managed by another object so we do not delete it unsigned int NameHash; // Name of Actor (stored as an hash for speed) int Type; // Type of Actor (use to distinguish beteeen different actor types) CIwFVec2 OriginalPosition; // Original position of actor in the scene (when actor was first spawned) CIwFVec2 Position; // Current position of actor in the scene CIwFVec2 Velocity; // Current velocity of actor CIwFVec2 VelocityDamping; // Dampens the velocity float OriginalAngle; // Original angle in scene (when first spawned) float Angle; // Orientation in scene (degrees) float AngularVelocity; // Angular velocity float AngularVelocityDamping; // Angular velocity damping float Scale; // Scale CIwColour Colour; // Colour bool IsActive; // Active state of actor bool IsVisible; // Visible state of actor bool IsCollidable; // Collidable state of actor CIwGameSprite* Visual; // Visual element that represents the actor CIwGameAnimManager* VisualAnimManager; // Visuals animation manager, used to control the actors visual componen animations int CollisionSize; // Size of collision area CIwRect CollisionRect; // Spherical collision size float PreviousAngle; // Previous updates angle CIwFVec2 PreviousPosition; // Previous updates position public: void setUsed(bool in_use) { Used = in_use; } bool isUsed() const { return Used; } void setManaged(bool managed) { Managed = managed; } bool isManaged() const { return Managed; } void setScene(CIwGameScene* scene) { Scene = scene; } CIwGameScene* getScene() { return Scene; } void setName(const char* name) { NameHash = IwHashString(name); } unsigned int getNameHash() { return NameHash; } void setType(int type) { Type = type; } int getType() const { return Type; } void setOriginalPosition(float x, float y) { OriginalPosition.x = x; OriginalPosition.y = y; } CIwFVec2 getOriginalPosition() { return OriginalPosition; } void setPosition(float x, float y) { Position.x = x; Position.y = y; } CIwFVec2 getPosition() { return Position; } void setOriginalAngle(float angle) { OriginalAngle = angle; } float getOriginalAngle() { return OriginalAngle; } void setAngle(float angle) { Angle = angle; } float getAngle() { return Angle; } void setVelocity(float x, float y) { Velocity.x = x; Velocity.y = y; } CIwFVec2 getVelocity() { return Velocity; } void setVelocityDamping(float x, float y) { VelocityDamping.x = x; VelocityDamping.y = y; } void setAngularVelocity(float velocity) { AngularVelocity = velocity; } float getAngularVelocity() const { return AngularVelocity; } void setAngularVelocityDamping(float damping) { AngularVelocityDamping = damping; } void setScale(float scale) { Scale = scale; } float getScale() const { return Scale; } void setColour(CIwColour& colour) { Colour = colour; } CIwColour getColour() const { return Colour; } void setActive(bool active) { IsActive = active; } bool isActive() const { return IsActive; } void setVisible(bool visible) { IsVisible = visible; } bool isVisible() const { return IsVisible; } void setCollidable(bool collidable) { IsCollidable = collidable; } bool isCollidable() const { return IsCollidable; } void getVisual(CIwGameSprite* visual) { Visual = visual; } CIwGameSprite* getVisual() { return Visual; } void setVisualAnimManager(CIwGameAnimManager* anim_manager) { VisualAnimManager = anim_manager; } CIwGameAnimManager* getVisualAnimManager() { return VisualAnimManager; } void setCollisionRect(CIwRect& rect); CIwRect getCollisionRect() const { return CollisionRect; } int getCollisionSize() const { return CollisionSize; } void setPreviousPosition(float x, float y) { PreviousPosition.x = x; PreviousPosition.y = y; } CIwFVec2 getPreviousPosition() const { return PreviousPosition; } void setPreviousAngle(float angle) { PreviousAngle = angle; } float getPreviousAngle() const { return PreviousAngle; } // Properties end CIwGameActor() : Used(false), Managed(false), Scene(NULL) { Reset(); } virtual ~CIwGameActor(); // Reset the actor (used by memory pooling systems to save actor re-allocation, usually called after re-allocation to reset the object to a default state) virtual void Reset(); // Update the actor (called by the scene every frame) virtual bool Update(float dt); // Update the visual that represents this actor on screen virtual bool UpdateVisual(); // Actors are responsible for carrying out there own collision checks. Called after all actor updates to check and resolve any collisions virtual void ResolveCollisions() = 0; // NotifyCollision is called by another actor when it collides with this actor virtual void NotifyCollision(CIwGameActor* other) = 0; // Call to see if this actor was tapped by the user virtual bool CheckIfTapped(); // Checks to see if another actor is colliding with this actor bool CheckCollision(CIwGameActor* other); };

Hmm, I agree, its a bit on the BIG side, but if you look carefully our CIwGameActor class provides a lot of functionality built in, which in the long run will save us lots of coding time. Again, you never create a direct instance of this class as it is abstract, you dervice your own different actor types from CIwGameActor.

We handle a lot of functionality with this base class including:

  • Position, orientation, scale, angular velocity, velocity damping and angular velocity damping – Physical attributes of our actor
  • Visibility state, active state, collide-able state – Used to hide, disable and mark as collide-able objects
  • Object type identifier, object name (used to search for specific types of objects or named objects). These are very useful as they allow you to create actors and forget about them, no need to store a pointer to them to reference them later, you simply ask the scene to find the object by name or type to access it again.
  • Visual, colour and animation manager – We will use these variables to give our object a visual representation in our world
  • Collision size and collision rectangle are used for collision detection

Note that eventually we will be replacing the physical components in this class with the Box2D physics engine.

I would like to point out a few important methods in this class:

  • Update() – When you implement your own actor types you override this method to provide the implementation of your game object specific behaviour. For example, if you create a player actor then you may check and move the player, maybe fire of different animations / sound effects. The default implementation of Update() will update the basic physics for the actor, any attached playing animations as well as add the actor to the collision check list if it is collision enabled. You should call CIwGameActor::Update() in your own Update() implementation, if you want to keep this functionality.
  • UpdateVisual() – You do not generally need to override and provide your own implementation of this method as this method will automatically update the actors associated visual for you.
  • ResolveCollisions() – When the scene has finished calling all of its actor updates it will then call ResolveCollisions() on each of the actors. You provide the implementation of this method to check for collisions with other actors. We implement collision checking this way as it allows us to optimise which collision checks to make. For example, lets say we are creating the old game Asteroids. The scene consists of 10 asteroids, 10 bullets and our ship. Our ship actor only needs to check for collisions with the asteroids and not the bullets or the ship.
  • NotifyCollision() – When an actor collides with another actor we need some mechanism for letting the other actor know that we have collided with them. When an actor collides with this actor it will call its NotifyCollision() method to let it know, this gives the actor a chance to respond to the collision event
  • CheckIfTapped() – Whilst this method is not currently implemented it will eventually allow us to check and see if the actor was tapped by the user. This is good for allowing the user to interact with our actors
  • CheckCollision() – Helper method for checking if two actors bounding circles overlap

One important note about Actors is there coordinate system. As far as our scene is concerned, the worlds centre is the the middle of the scene (0, 0), which corresponds to the centre of the screen for a scene that has not been moved.

CIwGameActorImage – An image based actor helper class

I suspect that many of you will want to simply get up and running quickly with your game and not have to worry about deriving your own actor class. With that in mind I created an image based actor that allows you to quickly set up a basic image based actor, complete with a sprite atlas, a base animation and a size. Lets take a quick look at the code in that class as I thin it will prove helpful when it comes to you designing your own actors:

bool CIwGameActorImage::Init(CIwGameScene* scene, CIw2DImage* image, CIwGameAnimImage* anim, int width, int height) { // Reset the actor CIwGameActor::Reset(); // Set the scene Scene = scene; // Create sprite if (image != NULL) { CIwGameBitmapSprite* sprite = new CIwGameBitmapSprite(); if (sprite == NULL) return false; // Set sprite image sprite->setImage(image); sprite->setDestSize(width, height); // Set sprite as visual Visual = sprite; // Add sprite to the sprite manager so it can be managed and drawn Scene->getSpriteManager()->addSprite(sprite); } // Create an animation manager and add the animation to it if (anim != NULL) { VisualAnimManager = new CIwGameAnimManager(); VisualAnimManager->setUpdateAll(false); if (VisualAnimManager == NULL) return false; VisualAnimManager->addAnimation(anim); // Set the first animation in the animation manager as the current animation VisualAnimManager->setCurrentAnimation(0); } return true; }

Our Init() method is pretty simple, it resets the actors internal data to default, creates a bitmapped sprite visual from the image and actor size then creates an animation manager and adds our default animation to it.

bool CIwGameActorImage::UpdateVisual() { if (CIwGameActor::UpdateVisual()) { // Update the sprite if (VisualAnimManager != NULL) { // Get the animations current image frame data and copy it to the bitmapped sprite CIwGameAnimImage* anim = (CIwGameAnimImage*)VisualAnimManager->getAnimation(0); if (Visual != NULL) ((CIwGameBitmapSprite*)Visual)->setSrcRect(anim->getCurrentFrameData()); } return true; } return false; }

Our UpdateVisual() method simply moves the image animation frame data to our sprite to update its image.

Unfortunately you will still need to derive your own actor from CIwGameActorImage() in order to create an actor object

CIwGameScene – A place for actors to play

The scene is the place where we put actors. When you add an actor to a scene the scene will take care of calling game logic update and visual update methods and building a list of potential colliding actors, as well as cleaning up the actors when the game is finished.
The scene also takes care of updating the camera and fitting our game across different sized screens with different aspect ratios. Look as the scene as the driving force that manages much of our game processes for us, so we can get on with coding up cool actors and other game logic.Lets take a quick look at the CIwGameScene class:

class CIwGameScene { public: // Public access to actor iteration typedef CIwList::iterator _Iterator; _Iterator begin() { return Actors.begin(); } _Iterator end() { return Actors.end(); } // Properties protected: CIwGameSpriteManager* SpriteManager; // Manages sprites for the whole scene CIwGameAnimFrameManager* AnimFrameManager; // Manages the allocation and clean up of animation frames unsigned int NameHash; // Hashed name of this scene CIwVec2 ScreenSize; // Native screen size CIwVec2 VirtualSize; // The virtual size is not the actual size of the scene. but a static pretend size that we can use to render to without having to cater for different sized displays CIwMat2D VirtualTransform; // Virtual transform is used to scale, translate and rotate scene to fit different display sizes and orientations CIwMat2D Transform; // Scene transform CIwList Actors; // Collection of scene actors CIwRect Extents; // Extents of scenes world CIwGameCamera* Camera; // Current camera CIwGameActor** Collidables; // List of collidable objects built this frame int MaxCollidables; // Maximum allowed collidables int NextFreeCollidable; // Points to next free slot in sollidables list pool public: CIwGameSpriteManager* getSpriteManager() { return SpriteManager; } // Manages sprites for the whole scene CIwGameAnimFrameManager* getAnimFrameManager() { return AnimFrameManager; } // Manages the creation and clean up of animation frames void setName(const char* name) { NameHash = IwHashString(name); } unsigned int getNameHash() { return NameHash; } CIwVec2 getScreenSize() const { return ScreenSize; } CIwVec2 getVirtualSize() const { return VirtualSize; } void setVirtualTransform(int required_width, int required_height, float angle, bool fix_aspect = false, bool lock_width = false); CIwMat2D& getVirtualTransform() { return VirtualTransform; } CIwMat2D& getTransform() { return Transform; } void addActor(CIwGameActor *actor); void removeActor(CIwGameActor* actor); void removeActor(unsigned int name_hash); CIwGameActor* findActor(unsigned int name_hash); CIwGameActor* findActor(int type); void clearActors(); void setExtents(int x, int y, int w, int h) { Extents.x = x; Extents.y = y; Extents.w = w; Extents.h = h; } CIwRect getExtents() const { return Extents; } void setCamera(CIwGameCamera* camera) { Camera = camera; } CIwGameCamera* getCamera() { return Camera; } bool addCollideable(CIwGameActor* actor); CIwGameActor** getCollidables() { return Collidables; } int getTotalCollidables() const { return NextFreeCollidable; } // Properties end private: public: CIwGameScene() : Collidables(NULL), SpriteManager(NULL), AnimFrameManager(NULL), NextFreeCollidable(0), Camera(NULL), MaxCollidables(0) {} virtual ~CIwGameScene(); // After creating the scene, call Init() to initialise it, passing the maximum number of actors that you expect can collide virtual int Init(int max_collidables = 128); // Update() will update the scene and all of its contained actors virtual void Update(float dt); // Draw() will draw all of the scenes actors virtual void Draw(); // Event handlers };

Yep, I know, its another biggy, but again it supports lots of cool functionality such as:

  • Handles all of our actors
  • Handles our camera
  • Fits our game to any sized screen / any aspect ratio using a virtual size display
  • Tracks potential colliders
  • Manages sprites and animation frames

You will be happy to know that you do not need to derive you own scene from CIwGameScene() and you will generally instantiate and work with a version of this class directly. Our scene class does not however need a little setting up initially. Heres asome basic code on how to set up a scene:

CIwGameScene* game_scene = new CIwGameScene(); game_scene->Init(); game_scene->setVirtualTransform(VIRTUAL_SCREEN_WIDTH, VIRTUAL_SCREEN_HEIGHT, 0, true, false);

I think at this point I need to explain something about the virtual screen system that I use to ease the pain of cross platform development

Using a Virtual Screen Size to Target Any Sized Screen

There are quite a few different solutions knocking around that solve the problem of targeting our game at a variety of different screen resolutions, including:

  • Scale to fit – This is a very simple scaling of the scene to match the display resolution. This is quick and simple but your game can appear stretched or squashed on displays that have a different aspect ratio to your game aspect ratio
  • Bordered – Another simple system that displays your game at its native resolution but with a border around it to fill the space that your game doesn’t cover. I don’t like this method as you are giving up too much screen real-estate
  • Unlimited screen size – This method is quite complex and involves rendering enough stuff on screen at a 1:1 pixel resolution to cover the entire screen. This disadvantage (and advantage, depends how much time you have on your hands) of using this method is that you would need to display a much larger area of the gaming world on a higher resolution display than on a lower resolution display.
  • Virtual screen – This method uses a pretend screen size that best fits many resolutions (800 x 512 / 512 x 800 is a good choice). Your game renders everything as though it is rendering to the virtual size and not the actual phones / tablets native screen size. You later scale and translate the virtual canvas to fit onto the native phones screen resolution.

We could use any of these methods in our game, but I am going to use a virtual canvas because it is the most convenient. Our CIwGameScene class has a method called setVirtualTransform() which will set this up for us, so that all of our actors will render to the virtual screen size. Heres how to use the method:

void CIwGameScene::setVirtualTransform(int required_width, int required_height, float angle, bool fix_aspect, bool lock_width)

  • required_width, required_height – This is the width and height we would like to use for our virtual screen
  • fix_aspect – Tells the scene to fix the aspect ratio of the scene to match the native screen aspect ratio
  • lock_width – Tells the scene to fix eth aspect ratio based on the width of the display instead of the height

CIwGameCamera – Our View Into the Gaming World

Many games can get away with simply one visible screen of information (such as Asteroids, Space Invaders, Pac-man etc..), but other types of games such as platformers, sports games, strategy games etc.. require the ability to move around the gaming world in some fashion. This is usually accomplished by using a camera that can move our point of view within the world. CIwGameScene supports the attachment of a camera to allow us to move our view around a larger virtual world. Lets take a quick look at the CIwGameCamera class:

class CIwGameCamera { public: // Properties protected: unsigned int NameHash; // Hashed name of this camera CIwMat2D Transform; // The combined camera transform CIwFVec2 Position; // Position of view within scene float Scale; // Cameras scale float Angle; // Cameras angle bool TransformDirty; // Marks camera transform needs rebuilding public: void setName(const char* name) { NameHash = IwHashString(name); } unsigned int getNameHash() { return NameHash; } CIwMat2D& getTransform() { return Transform; } void setPosition(float x, float y) { Position.x = x; Position.y = y; TransformDirty = true; } CIwFVec2 getPosition() const { return Position; } void setScale(float scale) { Scale = scale; TransformDirty = true; } float getScale() const { return Scale; } void setAngle(float angle) { Angle = angle; TransformDirty = true; } float getAngle() const { return Angle; } void forceTransformDirty() { TransformDirty = true; } bool isTransformDirty() const { return TransformDirty; } // Properties end private: public: CIwGameCamera() : Position(0, 0), Scale(1.0f), Angle(0), TransformDirty(true) {} virtual ~CIwGameCamera() {} // Updates the camera virtual void Update(); // Event handlers };

Ah much better, nice and short. As you can see the camera class is quite simple, supporting position, rotation and scaling of the view. To use a camera we simply create one and attach it to the Scene, the scene will then follow the camera around. To see different areas of the game world we simply move the camera around and all of our actors will move along with it.

Cool, I’m now done with explaining the new classes. I’ve been battling with trying to keep this article short and to the point, but alas I don’t think its quite happening for me.

What’s changed in IwGame Code

Marmalade SDK - Actor, Scene Camera Example

Marmalade SDK - Actor, Scene Camera Example

I will be honest, A LOT has changed since the previous article and I will try my best to walk through most of it; this is the main problem with an engine that’s  in-development.

Firstly I have had to make quite a few changes to our previous classes including:

  • CIwGameAnim – CIwGameAnimFrameManager now handles the life time of animation frames and not the separate animation classes themselves
  • CIwGameAnimFrameManager – Added the ability to retrieve allocated animation frames
  • CIwGameAnimManager – setCurrentAnimation() never actually set the current animation (oops, fixed)
  • CIwGameBitmapSprite – Source rectangle can now be set from a CIwGameAnimImageFrame (helper method just saves some typing)
  • CInput – This class has been renamed to CIwGameInput to fit in with the frameworks naming conventions. CIwGameInput is now a singleton and not declared as a global variable (I’m not generally a fan of global variables and prefer to use singletons for systems that there will only ever be one instance of). If you do not know what a singleton is then think of it as a global instance of a class.

Now onto the changes to Main.cpp. Note that I won’t be going into minor details such as “Oh I included these header files”.

We now accesss input using a singleton, here we have to create the IwGameInput singleton and then initialise it:

// Initialise the input system CIwGameInput::Create(); IW_GAME_INPUT->Init();

Note that IW_GAME_INPUT is just a macro that calls CIwGameInput::getInstance() (I find it more readable to use the macro)

Next, we create and initialise a scene then create a camera and attach that to the scene

// Create a scene CIwGameScene* game_scene = new CIwGameScene(); game_scene->Init(); game_scene->setVirtualTransform(VIRTUAL_SCREEN_WIDTH, VIRTUAL_SCREEN_HEIGHT, 0, true, false); // Create a camera and attach it to the scene CIwGameCamera* game_camera = new CIwGameCamera(); game_scene->setCamera(game_camera);

Next, we allocate a bunch of image animation frames for our manic face animation. Take note that we now allocate them through the game scenes animation manager. This ensures that the game scene later cleans them up for us.

// Allocate animation frames for our player CIwGameAnimImageFrame* anim_frames = game_scene->getAnimFrameManager()->allocImageFrames(8, 36, 40, 0, 0, 512, 40, 512);

Within our main loop we check for the player tapping the screen and if they do we explode 10 sprites into the scene at the tapped position:

if (IW_GAME_INPUT->getTouchCount() > 0) { if (!PrevTouched) { // Get tapped position in our virtual screen space CIwFVec2 pos = game_scene->ScreenToVirtual(IW_GAME_INPUT->getTouch(0)->x, IW_GAME_INPUT->getTouch(0)->y); // Create 10 player actors for (int t = 0; t < 10; t++) { // Create and set up our face animation CIwGameAnimImage* face_anim = new CIwGameAnimImage(); face_anim->setFrameData(anim_frames, 8); face_anim->setLooped(-1); face_anim->setPlaybackSpeed(0.2f); face_anim->Start(); // Create player actor ActorPlayer* player = new ActorPlayer(); player->Init(game_scene, sprites_image, face_anim, 36, 40); player->setName("Player"); player->setPosition(pos.x, pos.y); // Add player actor to the scene game_scene->addActor(player); } } PrevTouched = true; } else PrevTouched = false;

Note that because we are now dealing with a virtual screen resolution and not the actual native screen resolution, our tap coordinates need converting to virtual screen coordinates. We achieve that using the ScreenToVirtual() method of the CIwGameScene class.

Also note that we still have to create our face_anim animation, but this time we pass it to the ActorPlayer Init() method, so that the actor / scene can take of its management.

Next we update and draw the scene:

// Update the scene game_scene->Update(1.0f); // Draw the scene game_scene->Draw();

Lastly we clean-up the camera, scene and input system:

// Safely clean up the camera if (game_camera != NULL) delete game_camera; // Safely cleanup game scene if (game_scene != NULL) delete game_scene; // Shut down the input system IW_GAME_INPUT->Release(); CIwGameInput::Destroy();

ActorPlayer our First Derived Actor

ActorPlayer is our very first user defined CIwGameActor based actor and because we derived it from CIwGameActorImage (and in turn CIwGameActor) we get all of the useful functionality defined in those classes.

The only parts of our ActorPlayer that’s worth drawing out are the Init() and Update() methods:

bool ActorPlayer::Init(CIwGameScene* scene, CIw2DImage* image, CIwGameAnimImage* anim, int width, int height) { CIwGameActorImage::Init(scene, image, anim, width, height); FadeTimer.setDuration(1000); Velocity.x = IwRandMinMax(-100, 100) / 20.0f; Velocity.y = IwRandMinMax(-100, 100) / 20.0f; AngularVelocity = IwRandMinMax(-100, 100) / 20.0f; return true; }

Our Init() method calls the base CIwGameActorImage::Init() method to initialise the base CIwGameActorImage part of the actor. We then set up a fade timer and random velocities for position and spin.

bool ActorPlayer::Update(float dt) { // If fade timer has timed out then delete this actor if (FadeTimer.HasTimedOut()) { return false; // Returning false tells the scene that we need to be removed from the scene } // Calculate our opacity from time left on fade timer int opacity = FadeTimer.GetTimeLeft() / 2; if (opacity > 255) opacity = 255; Colour.a = opacity; return CIwGameActorImage::Update(dt); }

Our Update() method is called every game loop by the scene system, so keep in mind that this code will be called every single game frame. Firstly we check to see if the fade timer has timed out and if it has then we return false to the the scene system (this causes the actor to be removed from the scene / game) after the scene has finished updating all actors.

We then calculate the opacity of our actor from the time left on the fade timer which causes the actor to fade out of existence.

And that’s about it for this article, hope that most of your managed to stay awake, long drawn out technical stuff can send the best of us to sleep, especially if read on a few hours sleep, which is usually the case for us programmer types. The source code that accompanies this article can be downloaded from here

I’m quite happy with this blog as it marks the start of a real usable cross platform game engine that we can now build upon. In our next tutorial we are going to cover upgrading the engine to include some very basic collision detection and response whilst building a small game using the engine to show working collision. We will also cover handling frame rate variations and putting some audio in there. Hopefully I will get the time to do that this weekend.

That’s it for now and don’t forget HTML 5 is evil! (Just kidding, I got a book on it the other day and it looks quite good, think that I may use it to spruce up my blog)