IwGame Engine Tutorial – Actors

CIwGameActor Object – Sprites With Brains

Introduction

Whilst our title comparison suggests that actors are simply sprites with brains they have the potential to be much more.

Going back to comparison in the scene introduction section, actors play a pivotal role in our scenes, each actor having its own unique role and visual appearance. Actors are the building block of the game, they provide the actual unique functionality and visuals that make up the game as a whole. They can provide any type of functionality from a simple bullet fleeting across the screen to something as complex as a dynamic machine that modifies its behaviour and appearance based upon data streamed from a web server.

A CIwGameActor is a very generic object that provides quite a lot of functionality out of the box. The idea is for developers to create their own actor types from the base CIwGameActor class then implement their own custom functionality within its Update() method. The basic functionality provided by CIwGameActor includes:

  • Support for actor pooling to help reduce memory fragmentation
  • Unique names so they can be searched
  • Actor types
  • Position, Depth, Origin, velocity and velocity damping
  • Angle, angular velocity and angular velocity damping
  • Scale and Colour
  • Layers
  • Active and visible states
  • A visual that represents it on screen
  • Animation timeline that can be attached to the visual
  • Collision size / rectangle
  • Wrapping at scenes extents
  • Instantiation itself from XOML
  • Animation timline update
  • Other actor linkage (used to connect actors in a child / parent style system)
  • A Box2D physical body consisting of a material and shape
  • Box2D collision category, mask and group

Note that any changes made to the actor will automatically be applied to the actors visual.

As IwGame progresses more actor types with additional functionality will be created to create more out of the box style game objects (plug-in actors if you will). For the moment the following actors have been created for you:

CIwGameActorImage – This object represents a basic image based actor which has an associated image and animation.
CIwGameActorText – This object represents a basic text based actor which has an associated font and animation.
CIwGameActorParticles – This object represents a complex particle based actor system consists of manypatricles that move independently and have varying life spans.

A word of warning, do not forget to call the based classes Init(), Reset(), Update(), UpdateVisual() methods from your own derived classes or the underlying functionality will not be provided.

Creating Actors

Creating an actor is very simple as the following code shows:

	// Create player actor
	MyActor* actor = new MyActor();
	if (actor == NULL)
		return NULL;

	actor->Init();
	actor->setName("Player1");
	actor->setPosition(x, y);

	// Add player actor to the scene
	scene->addActor(actor);

In the above code we create a a basic MyActor object, which is a class that I created derived from CIwGameActor giving us the base CIwGameActor functionality. However, adding this code into a game wouldn’t actually see anything as we have not assigned a visual element to the actor. CIwGameActor does not handle the creation of a visual for you, instead it handles the rendering and update of a visual and its animations.

To get developers started with actors we included the CIwGameActorImage that will create a basic image based actor that supports animation.

If you require your actor to support Box2D physics then you should either define the Box2DMaterial and Shape in XOML or if creating manually then call:

	InitBody(Scene, shape, material, &Position, Angle, com.x, com.y);

This can be called before or after CIwGameActor::Init()

Creating a CIwGameActorImage

Creating an image based actor is a little more complicated, lets take a look at some example code:

	// Create a new instance
	ActorPlayer* actor = new ActorPlayer();
	if (actor == NULL)
		return NULL;

	// Create player actor
	actor->setScene(scene);
	actor->Init(image, 36, 40);
	actor->setPosition(x, y);

	// Add player actor to the scene
	scene->addActor(actor);

Creation is very similar to creating a basic CIwGameActor with the additional complication of having to pass an image to the actors Init() method.

Looking at the above code we create an ActorPlayer, which is a class that I created derived from CIwGameActorImage as we want some basic image functionality.

We then call the actors its Init() method to set up actor internals. We give the actor a name so that we can find it later then set its world position to the centre of the scene. Finally we add the actor to the scene.

You will notice that ActorPlayer’s Init() method has quite a a few parameters. When we call Init(….) we are actually calling CIwGameActorImage::Init(….) and passing along all the details shown in the code above which includes an image that will represent our actor (or more usually an image atlas), and the width and height of the visual on screen (in virtual canvas coordinates). Internally CIwGameActorImage will create a sprite to display our actor.

The end product of the above code is an actor that can be seen, moved around, scaled, rotated etc..

Now lets take a look at a slightly more complicated ezmple that creates an image based actor that uses an animation time line (more details on time line’s later):

	// Create a new instance
	ActorPlayer* actor = new ActorPlayer();
	if (actor == NULL)
		return NULL;

	// Create an animation timeline to hold our image animation
	CIwGameAnimTimeline* timeline = new CIwGameAnimTimeline();

	// Create and set up our face animation
	CIwGameAnimInstance* face_anim = new CIwGameAnimInstance();
	face_anim->setAnimation(anim);
	face_anim->setTarget(actor, "SrcRect");
	timeline->addAnimation(face_anim);
	timeline->play();

	// Create player actor
	actor->setScene(scene);
	actor->Init(image, 36, 40);
	actor->setTimeline(timeline);
	actor->setPosition(x, y);

	// Add player actor to the scene
	scene->addActor(actor);

I have marked the changes from the previous example.

The first set of changes deals with creating a time line object then creating the instance of an animation and adding that to the time line. This process allows the actor to track and update its own animations

In the last change we simply assign the time line to the actor, the actor will now take care of playing the animation and updating the actors visual with animation changes.

Text Based Actors

Text based actors enable you to instantiate text into the scene with very little effort from code or more easily from XOML. Thse text objects can be use very much in the same way as image based actors in that they can be moved around, scaled, rotated, hit tested or even have physics and collision applied to them.

Lets firstly take a look at creating a text based actor in code:

	// Find our preloaded font
	CIwGameFont* font = (CIwGameFont*)IW_GAME_GLOBAL_RESOURCES->getResourceManager()->findResource("font1", CIwGameXomlNames::Font_Hash);

	// Create a text actor
	CIwGameActorText* text_actor = new CIwGameActorText();
	text_actor->Init(font);
	text_actor->setText("Hello World!");
	text_actor->setRect(CIwRect(-100, -100, 200, 200));
	text_actor->setColour(0, 0, 0, 255);
	text_actor->setPosition(0, 0);
	text_actor->setAngle(45);

	// Add to the scene
	CIwGameScene* scene = findScene("Scene1");
	scene->addActor(text_actor);

In the above code we firstly locate our font (which we have already preloaded into the resource system) then we create a text based actor from CIwGameActorText initialising it with the font. We then set the text, rect and some other parameters.

We now search for the scene we want to place the actor in and it to the scene.

Now lets take a look at how to instantiate a text based actor in XOML:

<ActorText Position=”0, 0″ Rect=”-100, -100, 200, 200″ Angle=”45″ Font=”font1″ Text=”Hello World!” Colour=”0, 0, 0, 255″ />

As you can see the XOML definition is much more compact and readable.

Particle System Actors

From v.030 of IwGame the new particle system based actor is available. This actor is special in that it is optimised for creating, displaying and updating a complete system of sprites (kind of like its own sprite manager). The advantage of this actor is that it does not have to deal with each particle as a separate actor object. The CIwGameActorParticles actor supports both manual and auto generation of particles. Auto generation can be controlled using a number of a control parameters.

Particles have a number of properties that can be adjusted:

  • Visual
  • Position
  • Velocity
  • Velocity Damping
  • Gravity
  • Scale
  • Scale Velocity
  • Scale Velocity Damping
  • Angle
  • Angle Velocity
  • Angle Velocity Damping
  • Colour
  • Colour Velocity
  • Colour Velocity Damping
  • Depth
  • Depth Velocity
  • Depth Velocity Damping
  • Active state
  • Visible state
  • Lifespan – Duration of particle in seconds
  • SpawnDelay – The amount of time to wait before spawning for the first time
  • Lives – Number of times the particle will re-spawn (-1 for infinite)

The CIwGameActorParticles class contains two methods for generating random particles:

void GenerateRandomParticles(int count, CIwRect& src_rect, CIwFVec4& colour, CIwFVec4& colour_velocity, float duration, int repeat_count, float spawn_delay_change, float gravity)
void GenerateRandomParticles(int count, CIwGameActorParticle* particle, CIwRect& src_rect, float duration, int repeat_count, float spawn_delay_change)

Both of these methods will generate a number of particles based on a set of limits.

To determine which particle parameters are generated randomly the CIwGameActorParticles class supports the following methods:

void	setPositionMode(eParticleMode mode)
void	setAngleMode(eParticleMode mode)
void	setScaleMode(eParticleMode mode)
void	setVelocityMode(eParticleMode mode)
void	setAngVelocityMode(eParticleMode mode)
void	setScaleVelocityMode(eParticleMode mode)
void	setDepthMode(eParticleMode mode)
void	setDepthVelocityMode(eParticleMode mode)

By setting the mode to PAM_Random the specified parameters will be generated randomly.

When parameters are generated the following methods specify limits to the random formulas used to generate the parameters:

void	setPositionRange(CIwFVec2& range)
void	setAngleRange(CIwFVec2& range)
void	setScaleRange(CIwFVec2& range)
void	setDepthRange(CIwFVec2& range)
void	setVelocityRange(CIwFVec4& range)
void	setAngVelocityRange(CIwFVec2& range)
void	setScaleVelocityRange(CIwFVec2& range)
void	setDepthVelocityRange(CIwFVec2& range)

Lets take a look at some code that generates an explosion type particle system:

CIwGameActorParticles* GameScene::AddExplosion(int num_particles, float x, float y, float scale, float depth, int layer, float gravity)
{
	// Create explosion particle actor
	CIwGameActorParticles* actor = new CIwGameActorParticles();
	addActor(actor);
	actor->Init(num_particles);
	actor->setImage((CIwGameImage*)ResourceManager->findResource("sprites1", CIwGameXomlNames::Image_Hash));
	actor->setPosition(x, y);

	// Set random parameters
	actor->setScaleMode(CIwGameActorParticles::PAM_Random);
	actor->setAngVelocityMode(CIwGameActorParticles::PAM_Random);
	actor->setVelocityMode(CIwGameActorParticles::PAM_Random);

	// Set paramater limits
	CIwFVec2 scale_range(scale, scale + scale / 2);
	actor->setScaleRange(scale_range);
	CIwFVec2 angle_range(-5, 5);
	actor->setAngleRange(angle_range);
	CIwFVec4 vel_range(-5, 5, -5, 5);
	actor->setVelocityRange(vel_range);
	CIwRect src_rect(908, 440, 100, 100);
	CIwFVec4 colour(255, 255, 255, 255);
	CIwFVec4 colour_vel(0, 0, 0, -5);

	// Generate the particles
	actor->GenerateRandomParticles(num_particles, src_rect, colour, colour_vel, 2, 1, 0, gravity);

	return actor;
}

Here we create a particle actor, set up the which parameters should be randomised then set the random limits. Finally we tell the actor to generate random particles

Now lets take a quick look at generating particles manually in code:

CIwGameActorParticles* GameScene::AddStream(int num_particles, float x, float y, float scale, float depth, int layer, float gravity)
{
	// Create stream particle actor
	CIwGameActorParticles* actor = new CIwGameActorParticles();
	addActor(actor);
	actor->Init(num_particles);
	actor->setImage((CIwGameImage*)ResourceManager->findResource("sprites1", CIwGameXomlNames::Image_Hash));
	actor->setPosition(x, y);
	CIwRect src_rect(800, 291, 68, 65);
	CIwFVec4 colour(255, 255, 255, 128);
	CIwFVec4 colour_vel(0, 0, 0, -3);

	// Create and add particles
	float spawn_delay = 0;
	for (int t = 0; t < num_particles; t++)
	{
		CIwGameActorParticle* p = new CIwGameActorParticle();
		p->LifeSpan = 1;
		p->Lives = -1;
		p->SpawnDelay = spawn_delay;
		p->Gravity = gravity;
		p->Colour = colour;
		p->ColourVelocity = colour_vel;
		p->DepthVelocity = -0.01f;

		actor->addParticle(p, src_rect);
		spawn_delay += (float)1.0f / num_particles;
	}

	return actor;
}

This method creates a particle actor then manually creates a stream of particles that spawn at slightly different times to create a stream type particle system.

Particle actors can also be created in XOML. Lets take a quick look at an example:

    <ActorParticles Name="StreamParticles" Image="sprites1" Position="0, 0" Scale="1.0" Depth="1.0" Layer="1" VelAngMode="random" VelMode="random" AngMode="random" ScaleMode="random" PositionRange="100, 100" AngleRange="0, 360" AngVelRange="-5, 5" ScaleRange="0.25, 0.5" DepthRange="0.5, 1.0" VelRange="-2, 2, -2, 2" ScaleVelRange="0, -0.1" DepthVelRange="0, 0">
        <Particle Count="10" Position="0, 0" VelocityDamping="0.95, 0.95"
		SrcRect="908, 440, 100, 100" ColourVelocity="0, 0, 0, -4" Duration="2"
		Repeat="-1" SpawnDelay="0" />
        <Particle Position="0, 0" VelocityDamping="0.95, 0.95" SrcRect="908, 440, 100, 100"
		ColourVelocity="0, 0, 0, -4" Duration="2" Repeat="-1" SpawnDelay="0" />
        <Particle Position="0, 0" VelocityDamping="0.95, 0.95" SrcRect="908, 440, 100, 100"
		ColourVelocity="0, 0, 0, -4" Duration="2" Repeat="-1" SpawnDelay="0.4" />
        <Particle Position="0, 0" VelocityDamping="0.95, 0.95" SrcRect="908, 440, 100, 100"
		ColourVelocity="0, 0, 0, -4" Duration="2" Repeat="-1" SpawnDelay="0.8" />
        <Particle Position="0, 0" VelocityDamping="0.95, 0.95" SrcRect="908, 440, 100, 100"
		ColourVelocity="0, 0, 0, -4" Duration="2" Repeat="-1" SpawnDelay="1.2" />
        <Particle Position="0, 0" VelocityDamping="0.95, 0.95" SrcRect="908, 440, 100, 100"
		ColourVelocity="0, 0, 0, -4" Duration="2" Repeat="-1" SpawnDelay="1.6" />
    </ActorParticles>

The above XOML firstly generates 10 random particles at time 0, followed by 4 additional particles at times 0.4, 0.8, 1.2 and 1.6 seconds.

If you would like finer grained control over particle actors then you can simply derive your own version from CIwGameActorParticles

Actor Lifetimes

Actors will persist within the scene until a) the scene is deleted b) you explicitly remove them or the recommended method c) they remove themselves. An actor can easily remove and delete itself from the scene by returning false from its Update() method. Here’s an example:

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 no need to be removed
	}

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

Actor Naming and Finding Actors

As mention previously for scenes, actors also named objects, each instance of an object that you wish to query should have its own unique name (per scene) so that it can be located and modified at a later date.

You can find an actor in a particular scene using:

	CIwGameActor* actor = scene->findActor(“Player1”);
	if (actor != NULL)
	{
		// Do somethinig with the actor
	}

There are three ways to locate actors within a scene:

	CIwGameActor*		findActor(const char* name);
	CIwGameActor*		findActor(unsigned int name_hash);
	CIwGameActor*		findActor(int type);

These allow you to search for actor by string, hash or type. Note that searching by type will return the first and only the first instance of that particular actor type. This is very useful if you want to find a unique actor type, for example the player.

Actor Types

When developing games I find it incredibly useful to assign different types of actors different type ID’s, this allows me to optimise many area of my code such as collision checks. Carrying a type ID for each actor also comes in handy when you want to know the types of actor that you are interacting with.

You can set and get the actors type ID using:

	void		setType(int type)
	int		getType() const

Moving, Rotating and Spinning Actors

Actors come with a very basic physics system that allows movement via velocity and angular velocity, actors can also be scaled. CIwGameActor provides the following basic functionality to handle these features:

	void				setPosition(float x, float y)
	CIwFVec2			getPosition()
	void				setAngle(float angle)
	float				getAngle()
	void				setVelocity(float x, float y)
	CIwFVec2			getVelocity()
 	void				setVelocityDamping(float x, float y)
	void				setAngularVelocity(float velocity)
	float				getAngularVelocity() const
	void				setAngularVelocityDamping(float damping)
	void				setScale(float scale)
	float				getScale() const

Note that velocity and angular velocity damping is a reduction factor that is applied each game frame to slow down objects linear and angular velocities. Their default values are 1.0f which provides no damping, setting this value to less than 1.0f will dampen velocity whilst setting it to a value greater than 1.0f will enhance velocity.

Also note that changing position or angle will not effect velocity.

If the actor was created with Box2D physics enabled then you can also use the supplied force application methods.

Attaching a Visual and an Animation Timeline

For our actor to become visible on screen we need to assign it a visual component. If you are rolling your own actor and don’t go the CIwGameActorImage route then you will need to create and assign your own visual component to the actor.

To assign a visual to an actor you would call:

	void		setVisual(CIwGameSprite* visual)

Now when the scene renders the actor it will attenot to render the visual. I want to mention at this pont that as far as IwGame is concerned a visual is an object type that derived from a CIwGameSprite (we will cover this later), but for now we will just say that a sprite as far as IwGame is concerned is anything that can be displayed, be it a simple image or a complex piece of SVG.

And where you find visuals you will usually find some kind of animation. The actor class supports attachment of CIwGameAnimTimeline which is basically a collection of animations (we will cover this in more depth later). To assign a time line we call:

	void		setTimeline(CIwGameAnimTimeline* timeline) { Timeline = timeline; }

Changing an Actors Colour

Each actor has its own independent colour (including opacity). All actors are set to a default colour of white and full opacity. To change the colour of an actor you can call:

	void		setColour(CIwColour& colour)

Note that an actors colour will be combined with its parents base colour.

Obeying Scene Extents

By default an actor would merrily travel across the game scene and beyond its extents into oblivion and out of range coordinates, this can cause a bit of a mess for the underlying math and rendering routines. To prevent actors from going off into oblivion we can tell them to wrap around to the other side of the scene if they hit its extents boundary. To force actors to wrap around at the boundaries of the scene we call setWrapPosition(true):

	void		setWrapPosition(bool enable)
	bool		getWrapPosition() const					{

Actor Layering

We touched on layering earlier when we talking about layering in scenes. All actors within a scene exist (visually) on a layer. The layer determines the order in which the actors are rendered with lower layers appearing below higher layers. The maximum layer that an actor can exist on is determined by the scene that it lives in. To change the layer that an actor appears on and to retrieve its current layer we use:

	void		setLayer(int layer)
	int		getLayer() const

Scene Visibility and Active State

You can query an actors visibility state and set its visibility state using:

	void		setVisible(bool visible)
	bool		isVisible() const

You can query an actors active state and set its active state using:

	void		setActive(bool active)
	bool		isActive() const

Note that when an actor is made inactive it will also become invisible. However making an actor invisible will not make it inactive.

Resetting Actors

Because actors can be part of an object pooling system and may not get re-initialised when re-used, we provide the functionality to reset them to a default state. This allows developers to re-use objects and not worry about the previous state of the object. Just remember to call the underlying CIwGameActor::Reset() method from your own Reset() method to ensure that the actor is completely reset.

Collision Checking

Right now IwGame does not carry out collision checks for you, instead it calls back each actor in the scene after the scene has been updated to give each possible colliding object a chance to check and respond to collisions. To take advantage of this functionality you need to implement the following handler in your derived actor class:

	virtual void	ResolveCollisions() = 0;

A basic actor to actor collision method is included in CIwGameActor to allow actors to test for overlap based on the size set by setCollisionRect();

When a collision does take place, actors can notify each other by calling:

	virtual void	NotifyCollision(CIwGameActor* other) = 0;

Here’s a quick example showing how to use the system:

void ActorPlayer::ResolveCollisions()
{
	// Walk the scenes actors
	for (CIwGameScene::_Iterator it = Scene->begin(); it != Scene->end(); ++it)
	{
		// Only test collision against ball type actors
		if ((*it)->getType() == ActorType_Ball)
		{
			// Check for physical collision
			if (CheckCollision(*it))
			{
				// Notify ourselves that we collided with ball actor
				NotifyCollision(*it);
				// Notify ball actor that we collided with it
				(*it)->NotifyCollision(this);
			}
		}
	}
}
Note that if you are using integrated Box2D then you safely bypass this collision check system.

Creating an Actor from XOML

Actors can be created declaratively using XOML mark-up, making actor creation much easier and more intuitive. Below shows an example of an actor declared using XOML:

        <MyActor Name="Player1" Position="0, 0" Size="100, 100" Angle="45" SrcRect="0, 0, 36, 40" Image="Sprites" Timeline="Player1Intro2" />

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

  • Name – Name of the scene (string)
  • Style – Style that should be applied to this actor. If a properties that exists in the style is added to the definition then it replaces the property found in the style
  • Type – A numerical type that can be used to identify the type of this actor (integer)
  • Position– Position in the scene (x, y 2d vector)
  • Origin– Origin in the scene, moves the point around which the actor will rotate and scale (x, y 2d vector)
  • Depth – Depth of the actor in 3D (float – larger values move the sprite further away)
  • Velocity – Initial velocity of the actor (x, y 2d vector)
  • VelocityDamping – The amount to dampen velocity each frame (x, y 2d vector)
  • Angle – The orientation of the actor (float)
  • AngularVelocity – The rate at which the orientation of the actor changes (float)
  • AngularVelocityDamping – The amount of rotational velocity damping to apply each frame (float)
  • Scale, ScaleX, ScaleY – The scale of the actor (float)
  • Colour – The initial colour of the actor (r, g, b, a colour)
  • Layer – The scenes visible layer that the actor should appear on (integer)
  • Active – Initial actor active state (boolean)
  • Visible – Initial actor visible state (boolean)
  • HitTest – If true then this actor will receive touch events
  • Collidable – Collidable state of actor (boolean)
  • CollisionSize – The circular size of the actor (float)
  • CollisionRect – The rectangular collision area that the actor covers (x, y, w, h rect)
  • WrapPosition – If true then the actor will wrap at the edges of the canvas (boolean)
  • Timeline – The time line that should be used to animate the actor
  • Box2dMaterial – Sets the physical material type used by the Box2D actor
  • Shape – Box2D fixture shape for the Box2D actor
  • COM – Centre of mass of Box2D body (x, y 2d vector)
  • Sensor – Can be used to set the Box2D actor as a sensor (boolean)
  • CollisionFlags – The Box2D body collision flags (category, mask and group)
  • OnTapped – Tapped event handler
  • OnBeginTouch – Event handler that specifies an actions list to call when the user begins to touch the actor
  • OnEndTouch – Event handler that specifies an actions list to call when the user stops to touching the actor
  • OnTapped – Event handler that specifies an actions list to call when the user taps the actor
  • OnCreate – Event handler that specifies an actions list to call when this actor is created
  • OnDestroy – Event handler that specifies an actions list to call when this actor is destroyed
  • LinkedTo – Name of actor that this actor links to (string)

For actors that are derived from CIwGameActorImage we have the following additional properties:

  • Image – The image that is to be used as the actors visual (string)
  • Size – The on screen visible size of the actor (x, y 2d vector)
  • SrcRect – The position and source of the source rectangle in the image atlas (x, y, w, h rect). Used for panning the portion of a sprite atlas shown allowing frame based animation.
  • FlipX – Horizontal flipped state (boolean)
  • FlipY – Vertical flipped state (boolean)

For actors that are derived from CIwGameActorText we have the following additional properties:

  • Font – Name of font to use to draw the text (string)
  • Rect – The area thuat the text should be drawn inside of (x, y, w, h rect)
  • Text – String to display (string)
  • AlignH – Horizontal alignment (centre, left and right)
  • AlignV – Verticalalignment (middle, top and bottom)
  • Wrap – If true then text is wrapped onto next line if to long (boolean)

Note that unlike scenes you cannot create an Actor or ActorImage directly as their corresponding CIwGameActor and CIwGameActorImage classes are abstract, so you must derive your own actor class. More on this later.

In addition, actors must be declared inside a scene tag element as they must have a parent scene and cannot be declared as resources.

Animating Actor Components

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

  • Position – Actors current position
  • Depth – Actors 3D depth
  • Origin – Actors transform origin
  • Velocity – Actors current velocity
  • Angle – Actors current angle
  • AngularVelocity – Actors current angular velocity
  • Scale, ScaleX, ScaleY – Actors current scale
  • Colour / Color – Scenes current colour
  • Layer – Actors current visible layer
  • Visible – Actors current visible state
  • HitTest – Determines if the actor can be tapped
  • Timeline – The currently playing timeline

For actors that are derived from CIwGameActorImage we have the following additional properties:

  • SrcRect – Actors currebt bitmapped visual source rectangle
  • Size – Actors visible size on screen

Any of these properties can be set as an animation target

Creating a Custom Actor

Whilst CIwGameScene can be instantiated and used as-is, CIwGameActor and CIwGameActorImage are abstract and cannot. The actor system is designed this way as the developer is meant to create their own custom actor types that provide bespoke functionality that is specific to their game.

You begin the creation of a custom actor by deriving your own actor class from either CIwGameActor or CIwGameActorImage then overloading the following methods to provide implementation:

	virtual void		Init();
	virtual bool		Update(float dt);
	virtual bool		UpdateVisual();
	virtual void		ResolveCollisions() = 0;
	virtual void		NotifyCollision(CIwGameActor* other) = 0;

Here’s a quick example:

class MyActor : public CIwGameActor
{
public:
	MyActor() : CIwGameActor() {}
	~MyActor() {}

	void		Init()
	{
		CIwGameActor::Init();
	}

	bool		Update(float dt)
	{
		if (!CIwGameActor::Update(dt))
			return false;

		// Here we put our actor specific implementation

		return true;
	}

	bool		UpdateVisual()
	{
		if (!CIwGameActor::UpdateVisual())
			return false;

		// Here we put our actor specific rendering code (if any is needed)

		return true;
	}

	void		ResolveCollisions() {}
	void		NotifyCollision(CIwGameActor* other) {}
};

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

We also provide a none functional implementation of ResolveCollisions() and NotifyCollision() as these are required methods

You can take the implementation one step further by implementing both the IIwGameXomlResource and IIwGameAnimTarget interfaces to allow instantiation of your custom actor 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 actor 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 CIwGameActor 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 thiose changes:

class MyActor : public CIwGameActor
{
public:
	// Properties
protected:
	int		NumberOfEyes;
public:
	void		setNumberOfEyes(int num_eyes)	{ NumberOfEyes = num_eyes; }
	float		getNumberOfEyes() const		{ return NumberOfEyes; }
	// Properties End
public:
	MyActor() : CIwGameActor() {}
	~MyActor() {}

	void		Init()
	{
		CIwGameActor::Init();
	}

	bool		Update(float dt)
	{
		if (!CIwGameActor::Update(dt))
			return false;

		// Here we put our actor specific implementation

		return true;
	}

	bool		UpdateVisual()
	{
		if (!CIwGameActor::UpdateVisual())
			return false;

		// Here we put our actor specific rendering code (if any is needed)

		return true;
	}

	void		ResolveCollisions() {}
	void		NotifyCollision(CIwGameActor* other) {}

	// Implementation of IIwGameXomlResource interface
	bool		LoadFromXoml(IIwGameXomlResource* parent, bool load_children, CIwGameXmlNode* node)
	{
		if (!CIwGameActor::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("NumberOfEyes"))
			{
				setNumberOfEyes((*it)->GetValueAsInt());
			}
		}

		return true;
	}
};

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

    <MyActor Name="AlienCritter" Position="100, 100" Size="100, 100" NumberOfYes="3" />

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

class MyActorCreator : public IIwGameXomlClassCreator
{
public:
	MyActorCreator()
	{
		setClassName("MyActor");
	}
	IIwGameXomlResource* CreateInstance(IIwGameXomlResource* parent) { return new MyActor();	}
};

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

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

	// Add custom MyActor to XOML system
	IW_GAME_XOML->addClass(new MyActorCreator());

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 MyActor class from the CIwGameActor class which already provides this functionality.

Lets take a quick look at how we extend the animation update method to account for animating our NumberOfEyes variable.

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

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

		if (element_name == CIwGameString::CalculateHash("NumberOfEyes"))
		{
			CIwGameAnimFrameFloat* frame = (CIwGameAnimFrameFloat*)animation->getCurrentData();
			setNumberOfEyes((int)frame->data);
			return true;
		}

		return false;
	}

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

 

 

Leave a Reply