developing games with object composition: a case study...

4
Developing games with object composition: A case study using the Unity3D platform Marcelo B. Barbosa Andreza B. Rêgo Igor de Medeiros Federal Institute of Education, Science and Technology of Rio Grande do Norte, Brazil Abstract Unity3D is a game development framework that gathers various tools with the purpose to ease the game development process. Unity3D uses the concept of object composition applied to a component-based architecture to customize the core elements of the game: the Game Objects. Yet object inheritance remains as one of the most common techniques for code reuse, object composition offer its own advantages. This article presents a comparison between object composition and inheritance on the game development context. To observe the practical aspect of object composition, we developed a game called orBITa using the Unity3D game engine. We will present the benefits and disadvantages of using this object oriented mechanism and demonstrate how it affects the structure of the scripts components developed. Keywords: game development, object-oriented design, object composition, unity3d Authors’ contact: [email protected] [email protected] [email protected] 1. Introduction The object-oriented paradigm is often used on game programming. Game object elements may appear as instances of a bigger Game class, to represent the entities composing a game scene, like characters, enemies, environment objects and projectiles. However, an object-oriented approach must experience difficulties if implemented with inheritance [Passos et al. 2009]. Objects that inherit from two different hierarchies may have similar functionality, leading to code redundancies. Inheritance is a powerful feature of object oriented programming which allows the definition of relationships between classes to ease code reuse and achieve a better overall design [Weisfeld 2008]. A new class can be created by inheriting methods and attributes from a class that has a similar behavior. But this often leads to an organizational issue, though it is not always plausible to have a single super-class that owns all the resources inherited by a set of subclasses. An object oriented project can become more organized using hierarchic inheritance. As noted by Horstmann [2013], while structuring a class hierarchy we can verify which resources are commonly inherited by the projected classes in order to group them on the hierarchy base levels. Consequently, the super-classes placed on the top levels possess more general properties. This tactic supports the generation of subclasses with more specific behaviors. An alternative for reusing functionality is object composition. This technique is focused on assembling smaller objects to create a more complex functionality [Gamma et al. 1995]. Despite sharing the same purpose, inheritance and object composition differs substantially. Each one of the mechanisms has its own advantages and disadvantages. The maintenance and modification of class’ implementation is easier than reusing functionality through inheritance, for instance. For our project goal, object composition appears as a more suitable choice for its inherent capabilities. We focused on working with the Unity3D platform for the development of our game. Unity3D is currently one of the most used engines available in the industry. For our purposes, the free version of the framework is sufficient. The necessary features for producing a simple 2D game are included in the free package. Unity3D utilizes up-to-date tools and holds an active community, ready to answer common questions related to the framework. Objects in Unity3D are defined by a Game Object class that inherits from a base class called MonoBehaviour. Every script automatically derives from MonoBehaviour. This super-class assures that a Game Object can handle events, has a state machine for its actions and applies physics to the object. Although, every other behavior defined for a Game Object is attributed to a compositional routine implemented by programming scripts called Components. Developing games using components can minimize development costs and reduce the development time [Folmer 2007]. Thus, a component- based architecture is perfectly satisfactory to construct our game efficiently. In this paper, we expose the contrast and correlation between object composition and class inheritance in a functional way, through the development of the 2D game orBITa. The object composition in Unity3D is displayed as a result of association between Game Objects and programming scripts called Components. The main focus is the analysis of those elements which are responsible for applying specific behaviors to the Game Objects. 2. Related Work SBC – Proceedings of SBGames 2015 | ISSN: 2179-2259 Computing Track – Short Papers XIV SBGames – Teresina – PI – Brazil, November 11th - 13th, 2015 240

Upload: others

Post on 25-Aug-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Developing games with object composition: A case study ...sbgames.org/sbgames2015/anaispdf/computacao-short/147644.pdf · 1. Introduction The object-oriented paradigm is often used

Developing games with object composition: A case study using the Unity3D platform

Marcelo B. Barbosa Andreza B. Rêgo Igor de Medeiros

Federal Institute of Education, Science and Technology of Rio Grande do Norte, Brazil

Abstract Unity3D is a game development framework that gathers various tools with the purpose to ease the game development process. Unity3D uses the concept of object composition applied to a component-based architecture to customize the core elements of the game: the Game Objects. Yet object inheritance remains as one of the most common techniques for code reuse, object composition offer its own advantages. This article presents a comparison between object composition and inheritance on the game development context. To observe the practical aspect of object composition, we developed a game called orBITa using the Unity3D game engine. We will present the benefits and disadvantages of using this object oriented mechanism and demonstrate how it affects the structure of the scripts components developed. Keywords: game development, object-oriented design, object composition, unity3d Authors’ contact: [email protected] [email protected] [email protected] 1. Introduction The object-oriented paradigm is often used on game programming. Game object elements may appear as instances of a bigger Game class, to represent the entities composing a game scene, like characters, enemies, environment objects and projectiles. However, an object-oriented approach must experience difficulties if implemented with inheritance [Passos et al. 2009]. Objects that inherit from two different hierarchies may have similar functionality, leading to code redundancies.

Inheritance is a powerful feature of object oriented programming which allows the definition of relationships between classes to ease code reuse and achieve a better overall design [Weisfeld 2008]. A new class can be created by inheriting methods and attributes from a class that has a similar behavior. But this often leads to an organizational issue, though it is not always plausible to have a single super-class that owns all the resources inherited by a set of subclasses. An object oriented project can become more organized using hierarchic inheritance. As noted by Horstmann [2013], while structuring a class hierarchy we can verify which resources are commonly inherited by the

projected classes in order to group them on the hierarchy base levels. Consequently, the super-classes placed on the top levels possess more general properties. This tactic supports the generation of subclasses with more specific behaviors.

An alternative for reusing functionality is object

composition. This technique is focused on assembling smaller objects to create a more complex functionality [Gamma et al. 1995]. Despite sharing the same purpose, inheritance and object composition differs substantially. Each one of the mechanisms has its own advantages and disadvantages. The maintenance and modification of class’ implementation is easier than reusing functionality through inheritance, for instance. For our project goal, object composition appears as a more suitable choice for its inherent capabilities.

We focused on working with the Unity3D platform

for the development of our game. Unity3D is currently one of the most used engines available in the industry. For our purposes, the free version of the framework is sufficient. The necessary features for producing a simple 2D game are included in the free package. Unity3D utilizes up-to-date tools and holds an active community, ready to answer common questions related to the framework.

Objects in Unity3D are defined by a Game Object

class that inherits from a base class called MonoBehaviour. Every script automatically derives from MonoBehaviour. This super-class assures that a Game Object can handle events, has a state machine for its actions and applies physics to the object. Although, every other behavior defined for a Game Object is attributed to a compositional routine implemented by programming scripts called Components. Developing games using components can minimize development costs and reduce the development time [Folmer 2007]. Thus, a component-based architecture is perfectly satisfactory to construct our game efficiently.

In this paper, we expose the contrast and

correlation between object composition and class inheritance in a functional way, through the development of the 2D game orBITa. The object composition in Unity3D is displayed as a result of association between Game Objects and programming scripts called Components. The main focus is the analysis of those elements which are responsible for applying specific behaviors to the Game Objects. 2. Related Work

SBC – Proceedings of SBGames 2015 | ISSN: 2179-2259 Computing Track – Short Papers

XIV SBGames – Teresina – PI – Brazil, November 11th - 13th, 2015 240

Page 2: Developing games with object composition: A case study ...sbgames.org/sbgames2015/anaispdf/computacao-short/147644.pdf · 1. Introduction The object-oriented paradigm is often used

A method proposed by Bitman [1997] aggregate various studies and shows how software reuse is affected by the structure of the code. The work proposes a model that estimates that applications built from independent composed components shall possess higher cohesion and usability than what is commonly experienced when using inheritance. The model can be used as a basis to ensure the applicability of the object composition technique is desirable for improving quality for the proposed scripting process. Nevertheless, the platform has to allow the usage of a compositional structure. The Unity3D manual explains that the preferred configuration for working with Game Objects relates to the component-based architecture [UnityTechnologies 2015]. Object composition is not referenced in the documentation, but it stands as the conventional way to work with those types of elements in a lower level programming perspective.

A Game Entity represents a generalization of the

Unity3D Game Object concept, as different game platforms and frameworks may embrace different environments to represent objects existing within the game world. Until lately, class hierarchy game entities where represented by class hierarchy, and consequently, used the object inheritance technique to reuse functionality. West [2007] described a full refactoring process made inside a company from the game industry. The entities were refactored from a hierarchic inheritance architecture to a compositional one. A new framework was established to allow the usage of this kind of structural design with aggregation of components. After the implementation of the framework, the conversion from object inheritance to object composition went slowly, mainly because of the development team struggle to familiarize with the new context. Hence, this process produced positive results over time: codes became cleaner and easier to maintain primarily for the encapsulation of functionality in independent components.

Other frameworks and game engines have their

own style of working with game entities. The Unreal Engine, for example, acts similarly to Unity3D. On its manual, it is stated that Actors, which are subclasses of a wider Object class, are objects composed by specialized parts called Components [EpicgamesInc 2015]. Therefore, it is noted that Unreal Engine 4 uses a hybrid approach for its OO design, mixing Object Composition and Inheritance to enhance the overall structure. On the other hand, the Cocos2D-X Game Engine works differently. Game Objects are divided into Scene, Node, Sprite, Menu, and Action Objects. These objects do not have their customization as a result of smaller objects aggregation. Their properties are previously defined on the major classes from which the object behaviors are inherited [Cocos2D-X 2015].

A further study about the composition of behaviors

in a game system architecture indicates that it could bring some issues, generally related to the high

dependency between components or Game Objects instances [Passos et al. 2009]. The proposed solution is the utilization of the Dependency Injection pattern in the system architecture. This design pattern intends to provide a flexible way to manage indirect association between dependent components. It removes the responsibility for the programmer to deal with creating instances for composed objects. 3. Composition over Inheritance An object oriented design requires careful management to remain efficient. Design patterns and other techniques shall be used to achieve the necessary goals and solve problems that may show up during most of the development phases. The main idea is straightforward: favor object composition over class inheritance. This affirmative relies basically on the fact that compositional design will produce more objects and the system’s behavior will rely upon the relationships between objects instead of behaviors from a super-class [Gamma et al. 1995].

The Decorator pattern also applies as a reasonable solution for object oriented design issues. It basically promotes the attachment of similar responsibilities to an object dynamically [Freeman and Freeman 2013], similarly to what is proposed for the compositional method. A remarkable fact is that this design pattern still encourages the use of inheritance. The main difference in that case is that object inheritance does not have the intention to extend behaviors from the super-classes: It uses the inheritance in order to achieve type matching. That is only because the decorator class needs to have the same interface as the components it wraps.

In practical terms, compositional reuse techniques share, among others, the following advantages: Independent, composed components are created; Components are encapsulated; Potentially lower maintenance costs. On the other hand, it shows some disadvantages: Object composition requires greater expertise to use; It increases the development time significantly. Inheritance does not contemplate these advantages; but it has a couple of its own, including: Eliminates successfully duplication of code, shortens development time and demands less proficiency to work with. This leads to the comprehension that an efficient architecture may balance the use of both techniques to capitalize their advantages [Bitman 1997]. It happens mainly because Object Composition tends to be problematic if there are many component dependencies within its structure, which is a common situation in the game development context, and also because inheritance by itself can become troublesome if it occurs within a hierarchy that is too deep. Therefore, derived classes work more properly if the functionalities are tight coupled, while more generic behaviors can be efficiently obtained if implemented with the compositional model.

SBC – Proceedings of SBGames 2015 | ISSN: 2179-2259 Computing Track – Short Papers

XIV SBGames – Teresina – PI – Brazil, November 11th - 13th, 2015 241

Page 3: Developing games with object composition: A case study ...sbgames.org/sbgames2015/anaispdf/computacao-short/147644.pdf · 1. Introduction The object-oriented paradigm is often used

The chosen programming language may influence directly on the outcomes of an Object Composition usage in an OO based structure. Aspect-oriented languages and extensions offer native support to Object Composition, for example. By using these resources, we are able to reduce significant delays on the compositional development, and mitigate code complexity issues. 4. orBITa

orBITa is a simple 2D exploration game with an easy-to-learn gameplay system. orBITa is an exploration game that consists on controlling an astronaut that flies around planets in space (Figure 1).

Figure 1: Player standing on an explored planet.

Players explore a generated galaxy by clicking on planets in the scene. On Unity3D, a scene is composed of Game Objects and is the element responsible for displaying them in the screen [UnityTechnologies 2015]. The player and planet Game Objects have scripts to become mutually attracted in order to simulate gravity and the orbit behavior (Figure 2).

Figure 2: Player flying towards a planet with applied gravity.

Game Objects appear as the fundamental elements

of the game. Unity3D architecture is shaped upon the customization of Game Objects and the interaction between them. But an empty game object does not contemplate a functional scope, even though it inherits behavior of a MonoBehaviour major Game class. Hence, a Game Object acts mainly as a container to smaller game elements, called Components. This approach carry out the component-based system principles previously discussed in Sections 2 and 3. Components are, in essence, customizable parts. A script operates as a transformer component to add specific behaviors and cooperation between different Game Objects and Components [UnityTechnologies 2015].

Figure 3 displays the components that belong to the

player Game Object, which represent the astronaut in the scene, and the main playable character in the game.

Figure 3: The player Game Object components

Each component modifies the Game Object in a

specific way. The last two components (Attracted Body and Player Movement) are manually built scripts. Attracted Body is a component to enable the attraction between an Attractor Body and an Attracted Body: the player and planet Game Object, respectively. While Player Movement is the main controller behavior, allowing the user to be able to actually play the game and control its character around screen. 4.1 Object Composition applied in the game scripts Scripts are the instruments giving motion to every working piece in the framework. Every component has necessarily a built-in script to be active during the software execution. Components also operate over scripts available only in the framework source code. Our goal is to evaluate custom scripts created for orBITa due to the possibility of staging properly the code structure, so that we can demonstrate the intended premise. First, let’s evaluate the MakeTravel script (Figure 4). It's responsible for the behavior that allows the player to fly from one planet to another.

Figure 4: Definition of the MakeTravel class.

As shown in Figure 4, the class for our custom script inherits from MonoBehaviour, which is the base class every script derives from [UnityTechnologies 2015]. At the first lines of the code, the necessary attributes for our class are declared. Here, two different

SBC – Proceedings of SBGames 2015 | ISSN: 2179-2259 Computing Track – Short Papers

XIV SBGames – Teresina – PI – Brazil, November 11th - 13th, 2015 242

Page 4: Developing games with object composition: A case study ...sbgames.org/sbgames2015/anaispdf/computacao-short/147644.pdf · 1. Introduction The object-oriented paradigm is often used

Game Objects are set: player and planet. The last one is the Game Object that the script is attached to. Player stands for the playable character. A Planet refers to one of the planets disposed on the scene.

Figure 5: Definition of the onMouseDown method.

Colliders hold a list with all the colliders attached to the Game Object (Figure 5). It is necessary in order to get the planet orbit component, which happens to be a collider even though the component is implemented without the collision abilities.

If inheritance was used in this example, some troubles would be experienced along the way. Supposing all components CircleCollider2D, PlayerMovement and Animator functionality are implemented on MakeTravel’s super-class: the scripts would have to be inherited from MonoBehavior to be recognized by the framework. It would work, but a Player Game Object is essentially different from a Planet Game Object. That is a substantial issue for the system. We would also have a lot of unnecessary code because different kind of objects usually needs different behaviors. Also, we would deal with lots of code redundancies to properly alter those behaviors. The code structure would be compromised, along with the readability and efficiency of the architecture. 5. Conclusion Object inheritance has its own benefits. It is still necessary to analyze the problem before choosing a specific reuse technique. Object inheritance is more suitable to be applied on development contexts with a limited range of behavior mutability or smaller projects in general, for example. But Object Composition stands as a solid solution for reuse in OO architecture, and fits perfectly on the context of game development.

Every object oriented project requires special needs and countermeasures to work properly. This paper presents some design patterns intended to fix specific reuse problems: the Decorator pattern and the Dependency injection. Even though it is not trivial to integrate them or other patterns within an architecture model, they are powerful tools to be considered. This paper shows some of the profits of favoring composition over inheritance, and confirmed through a simplified but practical view how object composition eases the programming of behavior functions. The scripts used in orBITa exposes some advantages on code reuse and readability. The development of orBITa

succeeded in providing us with a practical form of the compositional system. Unity3D matched perfectly the needs of the project, both for its component-based architectural approach and for the adaptability to object composition while in the scripting process. References

BITMAN, W.R., 1997. Balancing software composition and inheritance to improve reusability, cost, and error rate. Johns Hopkins APL Technical Digest (Applied Physics Laboratory), 18(4), 485-500.

COCOS2D-X, 2015. Cocos2d-x Developers Manual. Available from: http://www.cocos2d-x.org/wiki/.

EPICGAMESINC., 2015. Unity Engine 4 Documentation. Available from: https://docs.unrealengine.com/.

FOLMER, E., 2007. Component Based Game Development – A Solution to Escalating Costs and Expanding Deadlines? In H. Schmidt et al., eds. Component-Based Software Engineering SE - 5. Lecture Notes in Computer Science. Springer Berlin Heidelberg, 66-73.

FREEMAN, E. & FREEMAN, E., 2013. Head First Design Patterns, Available from: http://www.ncbi.nlm.nih.gov/ pubmed/23386138.

GAMMA, E. ET AL., 1995. Design patterns: elements of reusable object-oriented software, Available from: http:// www.cs.up.ac.za/cs/aboake/sws780/references/patternstoarchitecture/Gamma-DesignPatternsIntro.pdf.

PASSOS, E.B. ET AL., 2009. Smart composition of game objects using dependency injection. Computers in Entertainment, 7(4), 1.

UNITYTECHNOLOGIES, 2015. Unity Documentation. Available from: http://docs.unity3d.com/.

WEISFELD, M., 2008. The Object-Oriented Thought Process 3rd ed., Addison-Wesley Professional.

WEST, M., 2007. Evolve Your Hierarchy: Refactoring Game Entities with Components.

SBC – Proceedings of SBGames 2015 | ISSN: 2179-2259 Computing Track – Short Papers

XIV SBGames – Teresina – PI – Brazil, November 11th - 13th, 2015 243