Subclass CCSprite vs Model Class. Best Practice?

Forums Programming cocos2d support (graphics engine) Subclass CCSprite vs Model Class. Best Practice?

This topic contains 34 replies, has 10 voices, and was last updated by  andrewpey 2 years, 6 months ago.

Viewing 25 posts - 1 through 25 (of 35 total)
Author Posts
Author Posts
May 24, 2010 at 6:59 pm #221957

Adam Allen
@swelltown

When you create NPCs or enemies, do you subclass CCSprite to hold their game related data? Or do you make a separate model class for that data and reference the sprite object only when you need to move it?

I believe that the the latter is the proper way to adhere to the model-view-controller paradigm, although it means more code.

I would love to hear your theories of code organization.

May 24, 2010 at 8:40 pm #283871

gaminghorror
Participant
@gaminghorror

I practically never subclass CCSprite. I’ve tried two times maybe just because it seemed like a good idea and i wanted to experience the difference. The problems already began with initialization, if you override CCSprite what’s stopping you from using a spriteWith… method that you didn’t override? I’m not sure if the parameterless init will always be called or not but even if it is, it just isn’t the right way to do it. You’re not extending cocos2d, the game engine, you’re making game objects which use CCSprite as a visual representation – so subclassing CCSprite is just wrong if you intend to use it as a game object.

I prefer composition over subclassing. Most of my classes are derived from CCNode. Some are NSObject and i prefer to use NSObject until i know i need to use the class in some way that requires it to be a subclass of CCNode.

I add to these classes what i need to make the class work as member variables. If the member is a purely visual thing that i just need to attach via addChild, i don’t even keep it as member variable because [self child] will contain (retain) it. Otherwise i prefer member variables over getByTag methods, not just to avoid the lookup but also to make debugging easier: you can inspect the self member variables more easily than trying to find the same object deep down in the children collection.

I must admit: i have never thought about or really grasped the MVC concept. I know what it’s about in principle since MFC from the late 90s. I always found it awkward, unnatural. I do not think of my code as MVC or me as implementing some form of MVC or not. I just code how i think it makes sense and try to avoid any pitfalls that i’ve learned over the years. Most of them are indeed ways to decouple logic from input and output. And i’m going to read up on MVC now, i wouldn’t be surprised to learn that how i structure my code is probably like MVC but not strictly.

Let me think about that … my typical game structure looks like this:

- GameScene (Layer, does all the input/touch handling, passes it on to specialized subclasses)

- GameScene member class (an NSObject derived class that implements global game logic, like spawning, collecting touch points for a path, or checking for collisions)

- Game Object class (does per-object game logic, like AI decisions, taking damage, dying … is composed of CCSprite or similar for display. Can also be a HUD/UI class that displays buttons, labels with score, etc.)

In a way this is my way of doing MVC with cocos2d.

One good reason when to subclass CCSprite:

If your intention is to make a specialized sprite for use in several games. What comes to mind would be a Sprite that would be able to draw itself on both sides of the screen if its position is close to a screen border and the intention is to wrap the sprite as it goes around the screen but you want to be able to display the Sprite partially on both sides.

May 24, 2010 at 9:20 pm #283872

Adam Allen
@swelltown

Thanks for that detailed reply. I’d say you are already close to following MVC.

I’m intrigued about your technique using member variables. Do you mean that instead of using addChild to attach a sprite to the layer, you add a member variable to the layer to hold the sprite? I like that a lot better than messing around with tags, but isn’t addChild a requirement to get it on screen?

Here’s how I’ve attempted to implement MVC in Cocos2d:

GameObjects <–> GameLayer –> Sprites

–GameObjects (Model)–

  • tagUniqueInt
  • delegateLayer
  • game data (hit points, etc)

–GameLayer (Controller)–

  • Array of GameObjects
  • children sprites

–Sprites (View)–

  • tagUniqueId
  • position & other display data

The game controller initializes the necessary game objects for the level and stores them in an array. The tagUniqueID is a static class variable to insure that is unique for each game object. More on that later.

The game objects use a delegate protocol so that they can call methods inside the layer. For example

Layer says to game object: enemy, what do you want to do?

[[ArrayOfGameObjects objectWithID: uniqueID] whatDoYouWantToDo]

Game Object Enemy replies: find the nearest player to eat

(void) whatDoYouWantToDo {
... code to think about what to do
nearestPlayer = [self.layerDelegate findPlayerNearestTo: self];
... do something with that knowledge, like
[self.layerDelegate move: self Towards: nearestPlayer];
}

Now that the game has figured out how to be played, it needs to update the view. The layer creates sprites and tags them with the uniqueID of the game object that the sprite is related to.

Game Layer

(void) move: gameObject Towards: nearestPlayer {
... some code
//create our enemy sprite that is connected to the game object that called this method
CCSprite *enemy = [CCSprite spriteWithFile:@"enemy.png" rect:CGRectMake(0, 0, 20, 20)];
enemy.position = ccp(5,5)
[self addChild: enemy z:1 [gameObject uniqueID]];
... more code
}

The uniqueID provides the glue that allows the layer to work with data in the GameObjects and update the display with the sprites.

May 24, 2010 at 9:21 pm #283873

drPedro
Participant
@drpedro

Aha!!! MVC or MVP (P for Presenter) or Passive View and supervising controller (check http://martinfowler.com/eaaDev/SupervisingPresenter.html for more fun)

In my current development, I’ve come again with this eternal question. To MVC or not MVC ?

In this game, my controller and view are rather merged but I keep my model clean – but not all my model. I mean , in my game I can move a sprite: in a pure MVC the position of the sprite should always be updated in the model and the view should always refers to the model to set the position of the sprite. But it would be very complex , so that’s just my view that is handling the moving of the sprite, and when the position of the sprite meets som criterias I modify the model (which lead to update the view) .Eventually, I keep all the things in my model that I may need to save the state of the game, not the little things that are not usefull .But in another application, I will do it differently because I have others needs.

Be pragmatic, I think that the architecture changes according to your needs (do you need to save the state of your game? do you have two views that deals with same information so that you need a common model ? do you need to do unit test your whole game to test quality ? Do you want to present a paper at a conference to show how nice is your architecture ?). There is no single answer,there are some design patterns, best practices but it is only advices for you to build your own architecture that stick to your needs.

I’ve seen so complex architecture in the enterprise development that were difficult to maintain and understand, now I tried to keep it simple and minimum to reach my goals.

May 24, 2010 at 9:59 pm #283874

gaminghorror
Participant
@gaminghorror

@drPedro:

>> I’ve seen so complex architecture in the enterprise development that were difficult to maintain and understand, now I tried to keep it simple and minimum to reach my goals. <<

Exactly. We’re not writing AAA titles here which juggle thousands of assets all the while frantically trying to achieve the game logic the designers have planned but not breaking on every edge case they will naturally not have considered.

We’re making mostly small and simple games so i, too, like to keep things small and simple. And short, classes that run for more than 1000 lines are probably good candidates to refactor or at least to be split into categories for easier navigation.

@Adam:

>>I’m intrigued about your technique using member variables. Do you mean that instead of using addChild to attach a sprite to the layer, you add a member variable to the layer to hold the sprite? I like that a lot better than messing around with tags, but isn’t addChild a requirement to get it on screen?<<

Typical implementation:

@interface bla
{
CCSprite* mySprite;
}

@implementation

-(void) initStuff
{
mySprite = [CCSprite spriteWith ...];
[self addChild:mySprite];
}

Since the sprite is my visual representation it will stick around for as long as the object is alive. It is simply stored in a member variable which i don’t retain – the addChild method does that for me. Additional memory use is negligible (4 bytes) so i often do it that way even if i don’t need that sprite later on.

Sometimes even a sharedManager is kept as member variable, in those cases where i use it very often:

@interface
{
CCDirector* theDirector;
}

@implementation
-(void) initStuff
{
theDirector = [CCDirector sharedDirector];
}

-(void) ticktock
{
while (alotoftimes)
{
// do something that involves theDirector
}
}

-(void) tocktock
{
while (alotoftimes)
{
// do something that involves theDirector
}
}

-(void) ticktick
{
while (alotoftimes)
{
// do something that involves theDirector
}
}

May 24, 2010 at 10:33 pm #283875

Adam Allen
@swelltown

@gaminghorror

Is bla a CCNode? And when you create a bla object, do you add it as a child of your main layer?

May 24, 2010 at 11:00 pm #283876

gaminghorror
Participant
@gaminghorror

Err, yes, it’s a CCNode or derived from it and added to the parent as child.

NSObject derived classes i keep in the parent as member and retain them properly.

May 25, 2010 at 2:08 pm #283877

riq
Keymaster
@admin

@Adam Allen

I guess it depends on your specific needs but subclassing CCSprite seems to be the easier way to go.

In case you are interested in subclassing it, please, take a look at the programing guide:

http://www.cocos2d-iphone.org/wiki/doku.php/prog_guide:sprites

May 25, 2010 at 2:50 pm #283878

robodude666
@robodude666

Hey,

It’s really a personal preference at this point. Like others said, we’re not developing extremely complex applications that manage thousands of objects at a time whilst barely passing under minimum playing performance like big games. If you are, then the “Best” practice available would probably be applicable. Otherwise, it’s honestly up to you in my opinion.

My personal preference is to use composition whenever possible. I rarely ever extend/inherit from classes that I personally didn’t write. Like Java, and many other languages, Objective-C is best used with composition over inheritance.

With that said, here’s my solution (note: it’s not really original but it works) to using Cocos2D’s graphics ontop of Box2D:

Actor Class:

- Has a Sprite member

- Has a Body member

- Update Method moves the sprite to the body’s location

- Generic empty “Child’s Game Logic” method that gets overridden by Child.

- childsGameLogic is called at the end of the Update method

HeroActor Class:

- Extends from Actor

- Hero’s position is updated via the super’s Update method

- Game Logic in the childsGameLogic method

MissileActor Class

- Extends from Actor

- child’s Game Logic may include out of bounds checks

- etc.

GameLayer:

- Instances of my Actor’s child classes are stored in a NSMutableArray

- Every Tick, the array is looped through and the Update method is called on every object

- Collision detection handled

A couple notes:

Game Logic that is SPECIFIC to a particular item on the screen goes into its respective class. For example, within my MissileActor class I would check to see if the missle left the bounds of my world. If it has, it triggers a NSNotificationCenter which is picked up by my GameLayer class. The GameLayer then puts it into a special array that is looked through after the world has stepped. The GameLayer then removes the object from the valid actors array and releases the missile. The missle itself will release the sprite, etc when dealloc’d.

Overall Game logic like the creation/destruction, movement controls, etc. is controlled within the GameLayer class.

Again, this is my personal preference. I’ve seen many people use this type of an approach before. I’ve also seen people do “SuperSprites” that inherit from a Sprite. It’s whatever works within your brain. Afterall, if you don’t understand what’s going on in your world… how can you manage it? ;)

Cheers,

-robodude666

May 25, 2010 at 4:10 pm #283879

riq
Keymaster
@admin

Again, this is my personal preference. I’ve seen many people use this type of an approach before. I’ve also seen people do “SuperSprites” that inherit from a Sprite. It’s whatever works within your brain.

Yes, I agree with that.

In LevelSVG I took the subclassing approach. This is more or less what I’m doing:

BodyNode: subclass of CCSprite

Hero: Subclass of BodyNode

KinematicNode: subclass of BodyNode

MovingPlatform: subclass of KinematicNode

BonusNode: subclass of BodyNode

etc…

Any of these nodes can be added an SpriteSheet. The logic of each Node is implemented in its own classes.

May 25, 2010 at 4:53 pm #283880

invulse
@invulse

Can anyone explain further why they would or do use MVC in a game?

I am a web designer/programmer by trade and when I use MVC for a site its for the specific reason of decoupling views from models and controllers, allowing me to possibly reuse the same view in multiple areas, make all of my queries in the model and have the controller fit all of these together. However in a game I can’t really understand splitting up the model from the view, then needing a controller to put these together.

Do you really need a separate model from the view, for me the view and the model are almost always coupled together very tightly in a game.

The game I am working on right now is structure like this:

CCSprite -> GameObject -> GameCharacter – > Enemy – > Specific Enemy

If I were to do the same thing with MVC I would think it would be like this

GameObjectModel->Enemy Model->Specific Enemy Model

GameObjectView->Specific Enemy View

GameObjectController->Enemy Controller->Specific Enemy Controller

But maybe I’m thinking about this incorrectly.

May 25, 2010 at 5:14 pm #283881

robodude666
@robodude666

As a Web Developer myself, so I find it natural to carry over MVC design into most programming I do. It’s what I’ve been using for years, and my brain works well with this type of a design. Here’s a little article that describes MVC in Game Development.

With Cocos2D, I think, you can consider the View the same as the Controller. The Scene is technically your view, which contains Layers that are controllers. The Views are your CCSprites, SuperSprites, and classes that are composted of CCSprites, etc. On the other hand, Models in Cocos2D can also be considered as the Views as well depending on how you implement it. In my case, with the Actor example above, my Actors are Models as they contain specifics to objects in my world. At the same time, they are also Views as they contain the Sprites that are being displayed.

There are of course other design patterns, and like before.. whichever you are most comfortable with should be implemented. If you are creating a design that you yourself do not understand, you’ll spend a lot of time being confused. If you know MVC, use MVC. Overtime, eventually, you may be swayed to a different type of a design pattern for whatever reason… then, simply use that new design pattern.

Personally, I find overthinking early pointless. Do something, and when you find that you can’t continue with your current design rethink and refactor. I know some people like to think of the entire picture at once, but I prefer to think of things steps at a time.

-robodude666

May 25, 2010 at 6:03 pm #283882

Adam Allen
@swelltown

@invulse

Can anyone explain further why they would or do use MVC in a game?

The link that robodude666 posted is a good explanation of MVC in gaming. Also, Apple’s framework is MVC, which promotes reusability and customization. Since we are playing in their sandbox, we should at least consider their concepts before deciding to follow a different path.

As I’m sure you know, an important part of programming is separating your logic from your display. This is helpful if you are working in a team where, for example, a designer is working on the user interface, a programmer is working on the AI, and you are working on game logic.

The consensus here appears to be that if you are working alone, abstracting out objects might not be as important if you have found an organization system that works better for you (@drPedro).

@robodude666

The Scene is technically your view, which contains Layers that are controllers. The Views are your CCSprites, SuperSprites, and classes that are composted of CCSprites, etc.

I think you meant to say the scene is your model. Which I agree with.

If your game has multiple scenes with similar play, you can skip doing your model in the scene and use a shared singleton class instead.

The layer is the controller because of touch handling and scheduling. Without that, it would just be considered another view.

So the layer receives touches and interprets how to work with the model. The model sends back data to the controller, which then moves views around.

To summarize what we’ve discussed regarding MVC in Cocos2d:

Model – Game logic, hit points, score, etc. Can be your scene, or in a shared singleton, or some of it can be combined with the view in a single file

View – CCSprites, maps, menus, etc

Controller – Handles touches, schedules updates, timing.

Most Common Practice

It seems that the prevailing theory is to put the model and view in the same file. Either by subclassing CCSprite and adding game logic (@riq), or by writing a logic class and adding CCSprite as a member variable (@gaminghorror).

In my opinion, just because these are in the same file, it doesn’t break MVC, and both are good solutions. CCSprite’s drawing is still safely tucked away from the model and the layer is still holding these objects in an array, passing touches, and moving things around.

Good discussion guys. I feel like I’m back in college. :)

May 25, 2010 at 6:26 pm #283883

robodude666
@robodude666

By Adam Allen:

I think you meant to say the scene is your model. Which I agree with.

If your game has multiple scenes with similar play, you can skip doing your model in the scene and use a shared singleton class instead.

I don’t see how they could be your models as they don’t actually contain anything. For me, at least… all the Scene does is “Hook” my Layer into the Director. For menu screens it adds a background, but that’s really it. Maybe I’m using them incorrectly or not to their full potential.

This is how I view it (no pun intended), simply put: The View (Scene) has a controller (Layer) that manages Models and Views (“Actors”).

It might be kind of trippy to think about it that way, but it makes sense to me… Kind of like how Java has the main function within a class, yet that class may have nothing to do with main other than giving main the ability to exist.

I am actually using a Singleton which holds information regarding my b2World, current Layer, and some other things related to my game but they hold no logic. Just proporties for setter/getters.

I’m also actually in class right now, and to be honest it’s not all that fun.

-robodude666

May 25, 2010 at 8:31 pm #283884

Adam Allen
@swelltown

@robodude666

The scene is a good candidate to be your model because it is already wired in as a parent of the layers. You can store and access global data there.

But with that frame of thinking, so is the app delegate. Of course it is poor practice to pollute the app delegate with logic unrelated to its main tasks.

IMO, a shared singleton is a good place for top level global info and logic related to top level tasks, like saving a game.

Some reading that led me to this conclusion:

Singletons, AppDelegates and top-level data.

This organization style is more relevant when working with Apple’s Interface Builder, which creates views for you inside of untouchable .nib files. Thankfully, Cocos2d gives us more control to organize code as we like. :)

May 25, 2010 at 9:52 pm #283885

gaminghorror
Participant
@gaminghorror

The view is indeed tucked away. I have very few cases where i need to override draw. In that case it’s still seperated because draw is just supposed to draw stuff based on the current state but not to run any logic or change object states.

@invulse:

I personally avoid this many levels of inheritance like your example:

CCSprite -> GameObject -> GameCharacter – > Enemy – > Specific Enemy

The full inheritance tree makes my brain ouchy-ouchy:

NSObject -> CCNode -> CCSprite -> GameObject -> GameCharacter – > Enemy – > Specific Enemy

You take all the baggage down to the lowest level and you tend to bloat the classes at the higher levels (GameObject, GameCharacter). Do they really need everything from CCNode and CCSprite? Hardly so. Is an enemy a Sprite, or has it a Sprite as its visual representation? The answer is clearly the latter.

I mean it works, ok. I’m ok with that. I do other gruesome things to the text i write on my screen, too. ;)

But i’d like to explain why i would never go this deep in class inheritance. For example, what if you have code in Enemy that suddenly you find you need to use with Player, too? And StaticObject? So you move it up to GameCharacter. And then up one more to GameObject so StaticObject can use it too. In the end you have one or two superclasses that do everything (at least a lot of critical stuff) at the top, a deeply nested hierarchy and objects that do only very little at the bottom. Since most of the code is now in GameObject or GameCharacter, that’s where you do most of the work. And that’s where things break badly because changes made that should only affect enemy behavior suddenly changes how the character behaves. In level 23 where he gets the rocket launcher for the first time but finds he can’t fire it reliably because the line of sight code the aiming code uses was written with Enemies in mind. Those bugs can drive you crazy, and they are hard to fix without adding special cases. And so the story goes on. This is the bane of inheritance overuse.

As an example, i worked with a codebase of somewhere between 500K to 1 Mio lines of code. The deepest level of inheritance for game objects was probably 3-4 levels deep. Most were just 2-3 levels. We had Entity at the top level – then Positioned Entity – then Building, Player, Figure, WallSegment, Terrain and tons of others at this level. Specialized game logic was implemented via Game Components that you could add to each object. This made them cast spells, resist more damage, allowed them to fly, and so on. If you wanted to you could have flying buildings that shoot enemies. The animation system (MVC, there we are again!) didn’t really know how to animate this but game-logic wise it worked. It made for some hilarious bugs too but they were very obvious to fix.

In other words: an OOP codebase should grow in width (more classes that work side by side and are used as components for other classes), not depth (deep inheritance levels with bulk, generic objects at the top).

Btw, i think you can subclass Actions to implement your own game-components, at least to some extend. I’ll have to have a closer look at that but what’s stopping us from creating an Action that handles, let’s say, firing a rocket launcher when it finds a suitable target? Add the action to a random game object and it’ll be able to fire and forget.

May 25, 2010 at 11:10 pm #283886

invulse
@invulse

@gaminghorror

I actually like that line of thinking more than when I am doing now. I have run into the problems you say can happen with deep inheritance. I guess my game right now is a combination of deeper inheritance and modules.

CCNode(not CCSprite) -> Object -> Character

Then characters can have things like AI, input controls, moves, etc… which are character dependent not dependent on if they are Enemies or not. However since I started programming in Flash AS3 I noticed all of the native API had inheritance like this:

Object->EventDispatcher->DisplayObject->DisplayObjectContainer->InteractiveObject->Sprite

so I always assumed that I should just do better early planning to create generic objects then extend from those.

May 25, 2010 at 11:40 pm #283887

robodude666
@robodude666

This is Apple’s Objective-C, not Adobe’s ActionScript. Leave Actionscript concepts to Flash, and Objective-C concepts to Apple’s products. Hell, that might be one of the reasons why Flash crashes so often ;).

Though, honestly.. Avoid inheritance when possible, and use Composition. Objective-C is meant to be used with composition. If your class doesn’t need most of the abilities of CCNode, etc. don’t inherit from it. Use NSObject, and only when absolutely needed inherit from something else.

I currently haven Actor class that inherits from NSObject. The Actor class is composed of a CCSprite and a b2Body. Nice and Simple.

May 26, 2010 at 8:45 am #283888

riq
Keymaster
@admin

Here is an article that explains the benefits of a flat hierarchy:

http://scottbilas.com/files/2002/gdc_san_jose/game_objects_slides.ppt

May 26, 2010 at 10:10 am #283889

gaminghorror
Participant
@gaminghorror

Upps, i should eat my own dog food. I just came across a class of mine which inherits from CCSprite. I think i did that to see if that makes more sense. Have to refactor that now. How embarrassing if someone would find out about this now. :)

May 26, 2010 at 10:19 am #283890

riq
Keymaster
@admin

@gaminghorror: You shoudn’t be ashamed :)

IMHO there is no magical recipe for everything. There are cases where subclassing makes sense. I agree with you and @robodude regarding a flat hierarchy, but it is important to be evaluate case by case.

For example, the following code could be re-written using composition, but I find easier to write it using subclassing:

// pseudo code
// Class that updates the physics body. Useful to move kinematic or static bodies using cocos2d actions.
//
class SpriteThatUpdatesPhysicBody ( CCSprite ):
def setPosition:(CGPoint)point
[super setPosition:point]
body->setPosition( point/PTM_RATIO )

May 26, 2010 at 2:08 pm #283891

robodude666
@robodude666

We’re doing Python in Objective-C now riq? :P

I’m often tempted to go by the easiest route when it comes to doing something the easy way, or the right way. In this case, I know I will have a lot of things in my world so by creating a generic Actor class early on, I can save from having to redo work later down the road when I change the way a sprite is placed for a body, or if something else changes.. Plus, it’s stupid fast to simply inherit from Actor when creating a new child class and be up and running with that new class in seconds.

I’ve also learned many times that doing things the easy way may lead to it biting you in the arse. When I was around 14ish and much younger I was getting into PHP. I often created by queries and classes in the simplest way possible. Years later I learned that it wasn’t the smartest idea at the time and the unoptimized queries were causing unneeded MySQL server load. So, I later spent countless hours plugging security holes, preventing SQL injections, and many other bugs which could have easily been prevented if I spent the time beforehand to do it the right way and prevent them altogether…

But, this is just a silly game :) So, I guess it doesn’t matter as much.

EDIT:

Create PPT riq! Dungeon Siege is actually one of my favorite RPGs ever made, right behind Diablo II! Dungeon Siege II’s Pet system was absolutely amazing. Spent countless hours feeding my pet random items to see what would happen to her stats.

Also agree with the PPT. It’s really nice to have some sort of a template language that can be parsed. Creating an XML or plist file that represents something is a very nice way of handling the addition of a ton of objects into the world. If you had to write C++ for every single one of those items, you’d have a lot of ugly and unorganized code.. plus a hell of a long compile time.

-robodude666

May 26, 2010 at 3:18 pm #283892

invulse
@invulse

:( now I want to rewrite how my game works. Next time I guess…

Does anyone use scripting languages for smaller games on here? I use plist files to create my maps and animations, but everything else is pretty much hardcoded.

May 26, 2010 at 3:20 pm #283893

drPedro
Participant
@drpedro

nice discussion!

my 2cents about the model:

If we consider the model in the MVC sense, it gathers all the data that is needed to build another view of your game (let’s say I have a game with ninjas in the forest and I want to xhange it to play with dogs in a town, Model must contains all the information -states,position,…- so that I can create another view – with dogs in a town – )

But actually we don’t need to save the complete state of the game because usually our games do not need it (we don’t need to create others views). So what we are doing most of the times is keeping some data that we need to save or use in another scene in a Model Object (most of people use a Singleton if I understand well). e.g the score, the level, the completion of something, … We usually don’t need to save the position of all sprites in this model and update the view object (mainly CCSprites) based on the model…

But again everyhting depends on your game and your needs (I imagine it’s a different story if you have a multiplayer online game or a game where you play on two iphones)

et like somebody said: Use the pattern you’re most confortable with, and if it’s not enough do some refactoring and find new solutions!

May 26, 2010 at 3:50 pm #283894

robodude666
@robodude666

@invulse

While not all scripting languages, I’ve previously used XML, LUA, and yaml as additional languages in a project.

LUA is a very fantastic small language that only takes fits into into ~40kB of C, and super easy to add to any C/C++ project. You can then “link” C/C++ functions to LUA functions and do some really quick scripting. Many AAA games use it, including World of Warcraft, Crysis, Crackdown, Fable, and a dozens more! I’m not entirely sure if LUA is allowed with the new iPhone developer EULA. It is based on C, and it can be used with an Objective-C wrapper called LuaForge, but the language itself is LUA.

yaml is a great language that can be used to describe data. It’s very nice for config files, though plists are very easy to use also with the GUI editor. yaml is similar to XML, but it’s designed to be readable by a human which makes editing very easy. It’s definitely possible to implement a class that reads a yaml file and renders the level based on that.

Squirrel is another fantastic little language. It’s meant to have a very small footprint, and is essentially LUA with a C syntax instead of a BASIC one. I’ve never used it in any application other than playing around with it, but it also is very ideal for event driven applications like games.

There really are dozens of great languages to pick from, which is a shame as there are soo many good ones.

For my project, I know I will use plist/XML files to describe each level. They will be passed into a levelParser which renders the level. I am considering using LUA/Squirrel to script events or do rapid prototyping, though I’m not entirely sure how I would use them to their best.

Being this is my first time working with the iPhone for more than a few hours to toy around, and me never working with Cocos2D previously, or ever working on a Game (beyond 10% completion at least) I don’t know what to expect when it comes to managing lots of items on the screen and rendering multiple levels, so I can’t really say what I might end up needing in the future. So, for the time being I suppose, I’ll do everything in Objective-C. If I see I’m doing one particular thing very often I may break it out into another language that is quicker to work with.

@drPedro:

Interesting. I’ve never really viewed Models in that way. Being a Web Developer primarily, I consider Models to be something that is based on data from the MySQL Database. My class that grabs the models is the controller, and the View is my templating engine.

I have a singleton called SingletonGameState which contains information about my Box2D world, and my Cocos2D world (active scene, layer, etc.) as well as some commonly used pieces of info (screen size, though that’s easily obtainable from the Director but calling the shareDirector is annoying if you do it often). This singleton would be considered a Model then?

What about a Layer? Even though it’s technically the Controller, couldn’t it also be the Model? I mean, my Layer contains arrays on what are the currently living Actors in it, as well as what Actors I plan to delete on the next frame. Yet the Layer is also a View as it is the parent to the Sprites currently visible in that Layer.

Sorry if I’ve gone in circles with my definitions. It is rather confusing and I’m trying to sort it out. I’ve never really explicitly defined what my Model, View and Controller were in any of my projects. I just sort of went for it.

-robodude666

Viewing 25 posts - 1 through 25 (of 35 total)

You must be logged in to reply to this topic.