iPhone Game Programming – Tutorial 10 – Game Structure

You will be pleased to know that the first part of tutorial 10 is now available for viewing. It’s taken me much longer than I would have liked to get this ready, but I’m glad that at least part 1 is out.

This part of the tutorial covers the changes to the project structure I have made along with how I am managing different game scenes such as the main menu and core game scene. It also covers some of the changes I’ve made to the Image class etc.

The second part of this tutorial will be covering the game elements themselves, so basically how I am managing entities, moving the player using the accelerometer, scrolling the tilemap and handling the player colliding with blocked tiles on the tilemap. These subjects should allow you to come up with all kinds of cool ideas for your games.

I am aiming to have part 2 up before the end of the weekend.

It’s worth noting that the Tutorial 10 project which is up on the blog is actually ALL the code I have. So it includes everything I cover in Part 1 as well as everything I will be covering in Part 2. So for those who want to just dive into the code and start taking a look, feel free :o)

I mentioned a cool tool for feeding accelerometer data from the device into the iPhone Simulator and this can be found here.

Tutorial 10 (1:23:51)

Tutorial 10 Project

I hope you find it useful and please post comments and questions.

Mike

Discuss in our community forum.

Share:
  • Digg
  • del.icio.us
  • Facebook
  • MySpace
  • Reddit
  • StumbleUpon
  • Technorati
  • TwitThis
  • Design Float
  • DZone
  • email
  • Google Bookmarks
  • LinkedIn
  • Scoopeo
  • Tumblr

266 Comments

Wilard  on July 1st, 2009

Greate, Mike! This is the main thing you do!

Ted Moroz  on July 2nd, 2009

Thanks Mike!
I have been looking forward to this. You are an awesome teacher.

George  on July 2nd, 2009

Hi Mike:
First of all, Thanks for these tutorials, they are really great.
Question:
Ive run previous Tuts, without problems in my 2nd gen Ipod Touch,
But when i run this one, i recieve this error:

“Code Sign error: The identity ‘iPhone Developer: Michael Daley’ doesn’t match any valid certificate/private key pair in the default keychain”
(It does work fine on iphone Sim though).

Any tip, to make it work?

Regards
George

MFerron  on July 2nd, 2009

@George

You need to sign up for the Apple Developer Program at apple.com ($99). Until then, all you get is the simulator for testing. Also, you aren’t able to distribute.

If you have in fact signed up, and are a member. Try re-downloading the code-signing certificate,or creating a new one.

George  on July 2nd, 2009

@MFerron:

I am signed in the Developer program.
Also ive run sample code from ADC without problems, And..
Just downloaded Mike’s Tut 9, And it runs on my Iphone, (and have runned previous versions), so i think (although im quite a newbie in Iphone dev), It must be another issue. Maybe some config, im missing for this app

George  on July 2nd, 2009

@me
“runs on my Iphone” I meant: Runs on my IPOD :-)

George  on July 2nd, 2009

Ok: Made it work
This is how, just in case someone has same problem.
In Xcode-> Build Menu-> Clean all Targets.
Then in Targets (in Main overview pane)-> MyGame (Double Click), and info Window appears.
Go to Code Signing->Code Signing Identity, And change Mike’s Device, for your own.
The strange thing here, is that i checked this before cleaning targets, and it had my device.
Anyway now it works.
Ok now time to study this.

korki696  on July 2nd, 2009

Hey Mike,
Another great tutorial!

I do have one question and i posted it under tutorial 2 but i thought since that was quite a while a go you might not check it so ill ask it here.

im making a game that is not a scroller like yours but just a background with with moving characters. my question is how can i get the sprite animations to move? ive tried .center and .x and .y but none of those work.

Thanks
-Lars

bob  on July 2nd, 2009

@Mike
Awesome tutorial, wow! that is a lot to absorb. You definitely out did yourself on this one. Can’t wait to start playing around tomorrow…

Thanks a lot Mike.

lorenb  on July 2nd, 2009

Great tutorial Mike. It was well worth the wait.

rcapote  on July 2nd, 2009

Hey I was just watching the tutorial (great job btw) and think I may have spotted an error. In the Resource Manager where you check to see if a texture already exists in the dictionary, shouldn’t there be two equal signs(==) instead of one? One being assignment and two being comparison?

rcapote  on July 2nd, 2009

Ohhh I see now…you do want to assign the variable…not compare. I get it, nevermind. :P

Dennis  on July 2nd, 2009

I haven’t yet reached this tutorial, as I begun watching them yesterday. But so far I went through your first three videos, and all I want to say is THANK YOU! Really! This type of well though and organized material is really rare even for on line education sites that make a living on these type of videos. Now you, on the other hand, offers this knowledge for free, and I have nothing but respect. Thank you so much for this effort! I think you should make a living doing this. I would definitely buy these!

Allan  on July 2nd, 2009

thx… :) downloading now… yesterday it was already too late ;)

mike  on July 2nd, 2009

Thanks everyone for your comments. I’m really pleased that you are still finding the tutorials useful. The iPhone provides such a unique platform from which to create and share ideas through apps or content that I feel as many people as possible should be given the knowledge to use it.

I’ve benefited so much from the conversations that the blog has generated and its taking my knowledge further, so its helping me as well as others :o)

Thanks again

Mike

Eskema  on July 2nd, 2009

Excellent work Mike, now im gonna be sarcastic and I’m gonna tell you, men this is your framework or cocos2d? xDD
sarcastic mode off.

Right now I’m cleaning my framework to share it with all the people, so that way people has another messy code to play with :)

mike  on July 2nd, 2009

Hi Eskema, thanks for the comment and I don’t mind you being sarcastic at all :o)

Cocos2d has certainly been an inspiration to how I’m developing the game, but it is also so much more than what I am writing. Concept names such as scenes etc are common, but the actual implementation differs greatly from what Cocos2d has, especially when you compare how they render sprites and their tilemap class etc. Cocos2d is also way more generic. I’m writing what I need to support my game idea rather than a framework which is generic. There are of course some things which are reusable which is just good software practice, but its nothing like as complete as Cocos2d in that respect.

I’m not sure what you mean about cleaning your framework to share so there is another messy code to play with. Hopefully the code in the tutorials is not that messy, but always happy to get feedback on that.

Mike

IPhoner  on July 2nd, 2009

I am signed in the Apple Developer program and can’t still figure out how to deploy the game in Ipod touch.

I would apreciate if someone breifly tell me how to do that.

Thanks.

Eskema  on July 2nd, 2009

Sorry Mike for the misunderstood about the messy code, I’m refering to my crappy/messy code not yours :), again I’m being sarcastic about myself.
I have a different methods to animations, tilemaps, fonts, and gamescenes, so I’m cleaning the code and adding comments to share that crappy/messy code, that I’m using to make my games, maybe you can find some useful functions for your framework :)

mike  on July 2nd, 2009

No problem Eskema, anything you can share would be excellent. The more varied examples I see of doing this stuff the better, so anything you can share would be great :o)

Don’t be too harsh on your code though, you’ve not seen some of the skunk works I’ve got hidden away :o)

Mike

Lars  on July 2nd, 2009

Hey Mike,

I’m still having problems with getting the animation to move. is there a position property that you can change? i have made it so if you touch above him he faces up and animates and same with the other direction, but i can’t get them to move.

Thanks
-Lars

Greg  on July 2nd, 2009

Hey, I have a small nit to pick. Sometimes when the video is zoomed in on the code window, you go on explaining about code that’s off the screen. Does ScreenFlow automatically handle the zooming and panning or do you have to do that manually?

Greg  on July 2nd, 2009

But other than that, great tutorial!!! I can’t wait to go through my code and see what I can implement. I really like how you handle scenes!!

mike  on July 2nd, 2009

Hi Greg. Thanks for letting me know about the code being off screen. All the zooming and panning is done by my good self when editing the video after it has been recorded. The entire video is recorded full screen and I then go through the tutorial again and zoom and pan where it is needed.

I try to be really careful to make sure stuff is not pushed off the screen, but in my rush to get this one out I’ve obviously missed something. If you know the time stamp when you have seen it let me know and I’ll fix it.

I spent a while thinking about scenes. I checked out Cocos2D and other frameworks to see how they tackled it and eventually came up with what you saw. I didn’t want it too complex or fancy and I think its come out ok.

Thanks

Mike

mike  on July 2nd, 2009

@korki696 I’m not sure which of the classes you are using, but it sounds like the animation class. Check out the renderAtPoint method in that class. Changing the point in that method will change the location of the animation.

If you were to have a variable that you move slowly, say x, and use that when creating the point, the animation will move.

If you have any code you want to email for me to look at feel free, mike@71squared.co.uk

Mike

Lars  on July 2nd, 2009

@mike what im actually trying to do is that when you tap somewhere it follows your finger so like a
*touchPointer = animation
The tests ive done have all failed so far.
any ideas?
Thanks
-Lars

Chris  on July 3rd, 2009

Hey Mike I have a quick question. Would there be any way to rotate the entire view into landscape mode so that all the images are rotated as well rather than portrait mode?

Thanks

Anonymous  on July 3rd, 2009

@chris I posted code on that in either the angle code font performance post or under update 2 post

@lars the Touches has to be told to get the position of the touch touchPointer would be a UITouch you want a CGPoint it should be CGPoint point = [touchPointer locationInView:AUIView]

A Person  on July 3rd, 2009

Sorry I am anonymous (iPod screwed it up)

Lars  on July 3rd, 2009

@A Person I understand that part what im looking for is the location property of the animation. so like _anim.location.
Thanks
Lars

This Week in iPhone News - July 3/2009  on July 3rd, 2009

[...] iPhone Game Programming – Game Structure Part 10 of a great video based tutorial series on iPhone game programming. [...]

mike  on July 3rd, 2009

@Lars, I see what you mean. The animation class does not have a property which stores its location, where the animation is rendered is provided by the renderAtPoint method, so there is nothing to query to get the current location of an animation, which is really a gap.

It would be easy enough to add a location property to the class and have the renderAtPoint method set that location so that you can query it.

Mike

Lars  on July 3rd, 2009

@Mike, first congradulations on getting on that list you definetly deserve.

I didnt think i saw one but i just wanted to make sure that im not missing something.

Thanks again
-Lars

mike  on July 3rd, 2009

Thanks Lars, I’ve only just spotted the ping back, very cool :o) and thanks for your great comment.

Nope, you didn’t miss anything and it would be good to have the location stored. I’ve put that on my things to do list.

Once I’ve got the tutorials to a point where I’ve gone through the core elements of creating a game and people have all the building blocks I’m going to go back and look at optimizing what I’ve created to fix these things and also introduce the new stuff I’ve learnt, so this will certainly be one of those things which will go in.

Mike

Jake  on July 3rd, 2009

All the others build and run for me fine. But with this one I get this error:

error: can’t exec ‘/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/gcc-4.2′ (No such file or directory)

A Person  on July 3rd, 2009

@Lars mike is right add the location variable to the animation class and better yet to every class that could use it I find it very useful. The property won’t do anything if you set the location unless you change the render method to check. I’ve got that going now and I can render by method or by setting the variable.

wuzutags  on July 4th, 2009

Hi mike,
Thanks for the video. I’ve been following your tutorial for a while now and “Stealing :)” some valuable classes into my game, e.g. the image class and the Angel Code font classes.
I have a totally different method of screen management which i got from http://craiggiles.wordpress.co.....-tutorial/. So my engine is a mixture of some of your Graphics implementation and that of criag’s.
My issue is, I ran my game along side with instruments and found some leaks coming from the Image Class. I don’t know if you’ve had time to clean up all leaks yet but I think it will be good to start checking. I also got opengl “error code 500″ placing the code below in your mainview function
“//GLenum err = glGetError();
//if(err)
// NSLog(@”%x error”, err);”
I think this error is what is causing the leak.

with the frame rate, i get 60 – 70 fps in my game on simulator but 30 – 50 on device, is that a good rate? I’m rendering quite a number of objects including particles.

CraigGiles  on July 4th, 2009

@wuzutags that is very ironic that you mention that because I just sent mike an email this morning about his classes and some of the things I’ve done with them. :)

Which device are you using? if its the first gen iPhone, rendering a large number of objects and particles with 30 fps should be good.. I would imagine you would want to keep it above 30 for the actual game. The problem is the simulator uses your CPU from your computer, and does not throttle it to simulate the iPhone.. so you’ll get a much higher performance.

mike  on July 4th, 2009

@Craig, @wuzutags, thanks for the comments. I am really pleased that the code from this blog for you started in some areas. Even if the code has changed beyond recognition its great it was a help to kick things off. That is really what I wanted this blog to do for people.

I’m always happy to hear of things to share, so if you have anything you would like to share just let me know and I’ll post about it. I’ll also be checking out as well to see what I can learn :o)

@wuzutags, I’ll check out the Image class for leaks. I have been checking with each tutorial to see if there are leaks and not seen any to date, well, apart from those that are created within Apples frameworks ;o)

I’ll check again to make sure there is nothing obvious. It could also be down to how the class is being used that exposes something I’ve not seen, so if you ever track down a problem let me know and I’ll get it fixed.

Thanks again for your interest and support of the blog and I hope it continues to be of use.

Mike

mike  on July 4th, 2009

@wuzutags, I’ve just had a look at Tutorial 10 code and I think I found the gl error you were getting. Error 500 mean GL_INVALID_ENUM, so basically an enum being used is wrong in an OpenGL command. I tracked this through and it looks like it was the glTexEnvi command in the OGLGameController.

It was setting the last parameter as GL_APLHA_SRC which is invalid, it should be GL_ALPHA. If you change that I think the error should go away.

Let me know if that works or not.

Mike

VimVenture  on July 5th, 2009

If you want to get stereo panning working in the SoundManager, set the listener orientation to
ALfloat listener_ori[] = {0.0, 1.0, 0.0, 0.0, 0.0, 1.0}
in the init method!

mike  on July 5th, 2009

@VimVenture, great catch. I had been playing around with those values and didn’t place the last one back to 1.0. Thanks for pointing that out :oD

Mike

wuzutags  on July 5th, 2009

Hi @mike,
Thanks for the correction but unfortunately the las parameter in the glTexEnvi is not GL_ALPHA_SRC. its GL_BLEND_SRC
“glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_BLEND_SRC);”
I did remove the SRC from the GL_BLEND_SRC which stopped the error but had rather a ghostly photonegative rendering effect. Also GL_ALPHA seems not to be a valid param for glTexEnvi.
I’m not able to run tutorial 10 yet since i’m running on sdk 2.2.1. some references are missing in the Foundation/Foundation.h, so i’m using tutorial 9. I also realised the error has been present since tutorial 1.

@Criag, yeah its very strange we both sent mike a mail the same day. But actually, I really liked your Screen management tutorial. I’ve modified the InputManager a bit to accept accelerometer values and report whether there is a shake or a tilt. I’m being tempted to move to how mike has implemented his scene management, but I’ve reviewed both approaches and I think they are almost the same. Just that, your input happens in an InputManager which for me is a good approach. Do let me know if you feel mike’s approach is safer and faster than yours so i can switch over. I do like how my engine structure looks like though.
I’m using a 3rd gen iphone for my testing. What even happens now is that, the game crashes when I quit from the gameplay scene, back to the menu and back to gameplay scene. I’m using a very object oriented structure so i really suspect memory overheads when i pass around objects anyhow. None of this happens in the simulator.

Finally, I’d like to know the overhead in handling scenes(splash, menu screen etc) using opengl vrs screen management using UIkit and coreAnimation.

A Person  on July 5th, 2009

@mike I think it would be a good idea to port the engine to c and make a render manager to make it useable on other system.

A Person  on July 5th, 2009

I typed cplusplus but it didn’t show

mike  on July 5th, 2009

Hi A Person, that is a cool idea :o)

Behind the scenes I’m using the knowledge I’ve picked up from doing these tutorials and from the comments made and I’m making a much tighter more usable engine. This is still in Objective-C with splashes of C where necessary for performance. This is for a large project I’m going to be working on for a number of months. I’ll say more when I can ;o)

Once that is out of the way, looking to change it to C ++ could be interesting. Obviously the OpenGL side of things would need to be plug and play as its currently using GL ES 1.1 and would need to be changed for other versions.

I was never out to create a game engine as it were like Cocos2D, but rather just create what was needed to make my own game. Its certainly something I’ll have a think about once my project is out of the way :O)

Mike

mike  on July 5th, 2009

@wuzutags. Its odd that GL_ALPHA is giving you problems. That is the param I am using in another project I’m working on and its fine, hmmmmm.

As for the overhead on managing scenes. Apart from when you may need to take user input and use the keyboard etc, I’m trying to stick with GL all the time. I have read that mixing CA and GL can have real performance problems. I suppose it will depend on what you need to do that UIKit could help with.

For the moment I’m going to stick with GL as I have all the control I need and I’ll add in UIKit for textfields and keyboard etc for names on highscores etc.

Mike

Eskema  on July 6th, 2009

Hi Mike, after a weekend cleaning code and making sure that all works, here I am to show all of your readers my code, it isn’t perfect but it works.
Hope this “framework” could be useful to anyone, get it at http://www.telefonica.net/web2.....mplate.zip

Eskema,

ninjutsucoder  on July 6th, 2009

Just going through the updated project. Looks good, just wanted to say thanks, this site’s been a big help!

mike  on July 6th, 2009

@Eskema, thanks for the link. I’ll check that out. I always love looking at other peoples approach to things :o)

@ninjutscoder, thanks for the feedback and I’ glad your finding them useful :o)

Mike

Eskema  on July 6th, 2009

Mike, I hope you and other people find some ideas in my code, I made some changes to your soundmanager to gain some performance and I’m happy with the results, I put those changes in the zip above :)

zack  on July 6th, 2009

Thanks for the guides mike, there awsome so far but is there any chance of a side scroller guide like gravity with tiled maps.

mike  on July 7th, 2009

@zack, thanks for the comments and I’ll add this idea to my list of things I’d like to cover :o)

Mike

Siamak  on July 7th, 2009

Hi mike,
Thanks for the tutorials, really great.
my question was whether you had any license to your code if i would use/copy some of your code for my own game which is going to be a commercial product, the engine by itself would be only used by me though.

mike  on July 7th, 2009

Hi Siamak

I really should get a license statement set up on this and I keep meaning to do it. I will be applying the MIT license to all source code going forward so people can freely take, modify, distribute the source code from this web site. The license header is below and I will be adding it to all my source files.

Copyright (c) 2009 Michael Daley

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

I hope that helps and good luck with your project :o)

Mike

bob  on July 7th, 2009

@Mike
I ran into a problem when the screen is in Landscape the fonts that are displayed don’t rotate with the viewport. Am I doing something wrong?

A Person  on July 8th, 2009

@bob it doesn’t autorotate you have to tell it to i posted code in, i think it was video update 2 that makes it do that if you can’t find it tell me and i’ll re-post it.

bob  on July 8th, 2009

@A Person
Everything is rotated OK, I have Landscape working. its just the AngelCodeFont that’s not rotated with the screen.

Thanks

penguins  on July 8th, 2009

I have not tried this on the AngelCodeFont, but a trick that I found, was to add:

glRotatef(270.0, 0.0, 0.0, 1.0);
glOrthof( 0, screenBounds.size.height,0, screenBounds.size.width, -1, 1);

To the InitOpengl in EAGlView. This allowed me to render stuff with no modifications to the drawing code.

Hope that helps.

bob  on July 8th, 2009

@penguins
Thanks, but that code is already part of the initOpenGL. I may have to just play around with the AngelCodeFont and add a class for doing rotation.

mike  on July 8th, 2009

Hi bob, if you have something you can send me I’ll have a look. The anglecodefont stuff should just rotate along with the view as suggested above, so I’m not sure why that is not happening.

Mike

MFerron  on July 8th, 2009

Hey Mike

First off, thanks for the tutorial.

I’ve been playing around with your code and adding my personal stuff to it and I ran into a couple weird issues.

#1. I decided to comment out the portion of your code that builds the blocked tile locations to play around in your map without having to create a new one without walls. Anyways, when I do this, everything seems fine, no collisions, but after about 10 seconds the game freezes and/or crashes. Any ideas as to why this happens?

#2. I also swapped out your knight with my main character, which is a plane/ship. I took out your sprite sheets and animations for walking around since I will simply be rotating the player (100% top-down view). It shows up, looks fine, except when I test collisions. The image is smaller than a tile size (no scaling done, just actual size of image) and when it collides with a wall it acts as if it were a tile itself. Make sense? So My ship is there, and there is an invisible box around it, the size of a tile, that is doing the collisions. Also, the image appears to be drawn in the lower left corner of this invisible box. So when I collide down and/or left, there is a little image overlap on the wall. Why does this happen, and what should I do to fix it?

Was that clear? Hopefully you can picture what I’m trying to describe. If not, I could take a few screen grabs to try to show you.

Thanks for any help.

mike  on July 8th, 2009

@MFerron, that’s not a bad description and I think I get it, but if you have some screenshots you can post that would be great :o)

Mike

bob  on July 8th, 2009

@Mike
Hi Mike, I think I found my problem. I Think I may have the coordinate system messed up. When I set PORTRATE_MODE to NO, all my graphics are sideways which means I have things backwards.

mike  on July 8th, 2009

@bob, sounds like your tracking it down :o)

Mike

MFerron  on July 8th, 2009

@mike

Sure. I’ll be able to email them when I’m done with work later. Thanks for the help in advance.

MFerron

bob  on July 8th, 2009

@Mike
My coordinates are

LANDSCAPE MODE
320 ———————
|
X |
|
0 ———————-
0 Y 480

I think they are backwards

bob  on July 8th, 2009

@Mike
in the info.plist I have “UIInterfaceOrientationLandscapeRight”

I forgot to set PORTRAIT_MODE to NO, and so everything I did is now backwards. So I guess I have my work cut out for me.

Thanks

mike  on July 8th, 2009

@bob, bugger :o(

Eskema  on July 8th, 2009

bob, maybe you could take a look to my source, I don’t have any problems with landscape view, using angelcode class or my font class

A Person  on July 8th, 2009

@MFerron you need more complex collision detection that checks for vertices in tile and if you want your sprite to be rotated then you going to have to calculate vertices with rotation.

A Person  on July 8th, 2009

@anyone who can answer :0)
I can’t figure out how to convert pixel y coordinates to tile y coordinates i’ve looked at the tutorials way of doing but i still can’t quite get it.

bob  on July 9th, 2009

@Mike

Just thought I would let you know I got everything working correctly now. Whew! Took me all day to rewrite everything.

A Person  on July 9th, 2009

I got mine working correctly too so you can delete that comment if you want/can mike.

A Person  on July 9th, 2009

@anyone who can answer :0)
How would I apply a color filter to the whole screen, i’ve tried using glColor4f but it doesn’t do anything?

Kingbombs  on July 10th, 2009

Hey,
I only found your tutorials 2 days ago and have found them interesting to read.
I have already created a game in OpenGL ES originally created using the OpenGL ES template provided by Apple.
I am currently very stuck trying to create a main menu, i have looked at your tutorials but the major problem is that you have coded your game in a very different style to mine :D which makes it hard for me to try and use some of your technics.

So i was wondering if you had any experience with bassicly creating another View and getting the AppDelegate to load up that View and then when the user selects newGame it then loads the glView

I also had a question as well:
From looking at your tutorials and the code you do in them, it looks like you very much stick to the MVC architecture, quite a few people on IRC have mentioned that games generally don’t use MVC and instead combine the View and the Controller so you don’t have to make calls back and forth, (which i don’t know if that gives a performance gain? deffaintly makes code look messy) i was wondering your opinion on the subject and which you prefer to use (i don’t know if you are just doing it this way so people understand your code easier)

Thanks for the tutorials though, they are useful and very good for aspiring developers and newcomers :D

Kingbombs  on July 10th, 2009

@A Person

At a guess you could create a texture of the color that you want to use as a color filter and then apply that on top of the whole screen or the part of the screen you want and set its alpha to very low so its close to transparency

That may work :)

A Person  on July 10th, 2009

Thanks kingbombs I’ll give it a try

mike  on July 10th, 2009

@kingbombs, hi and welcome to the blog :o)

Your right in that common practice is to not use MVC for games. Using many objects and messaging between them in Objective-C does have an overhead which in very busy games can effect performance. Part of keeping the game OO based is to make it easier for people to follow. I’m not sure about others, but when I downloaded the code for Id’s Wolfestien on the iPhone the code was a complete mystery to me, all over the place.

Now for the experienced C/C ++ game programmer that may be the norm, but coming from Java and not being an experienced game programmer I still find that kind of code really hard to follow, so, I’ve stuck with using Objective-C for the most part and OO. I have some C in there as well to keep things quick such as the Particle system etc, but its mostly Objective-C.

I think that if I were going to be doing a game which really needed to squeeze out as much performance as I could from the iPhone I would certainly end up using Objective-C as a wrapper around the Cocoa side of things and use just C/C ++ for the entire game.

In my testing though its not been too bad. Even with the code in the tutorials the performance of the tilemap, particle system and images is not too bad. It does have a point where performance really dips, but that is more down to not batching up OpenGL calls i.e. the Image class calls glDrawArrays for each Image.

Alongside the tutorials I have another project I’ve started which is almost like Game code version 2. In this I’ve taken all the lessons I’ve learned as I’ve done the tutorials and from the feedback on the forum and created a new game engine. Very similar to the tutorial code but I’ve added the ability to batch Image drawing into a single OpenGL call and stuff like that. At the moment I’m really pleased with the performance. I’ll be able to share more on this later as its part of a project I’m working on.

As for your view question, sorry for the ramble, if you already have an instance of the EAGLView created called glView, then you should just be able to push that view onto the view controller stack using the code below

[self pushViewController:glView animated:YES];

If “self” is a viewController instance that it should load the glView and slide it into view and you could link the above code to a button press.

When you then want to return to the menu, you capture an event in glView which means the user wants to move back, maybe they touch a certain part of the screen etc and you use the following code to move back up the viewController stack to the view which called glView.

[self popViewControllerAnimated:YES];

I’m not sure what your setup looks like, but I hope that helps some.

Mike

P.S. Actually, rather than popViewController which will use a navigation controller and hence the nav bar at the top of the screen, use the following instead

[self presentModalViewController:glView animated:YES];

You would also need to make sure your classes are subclassing UIViewController.

LB Technology Services Blog » Blog Archive » Game Structure  on July 10th, 2009

[...] you’d like to see some code examples, see the cocos2d library or this tutorial from 71Squared. … other posts by [...]

Kingbombs  on July 11th, 2009

@mike
Thanks for the reply,
I did try to use the nib files and different views but end up getting frustrated and created the main menu in openGL and change a bool value to start drawing the game rather than the main menu.
Like you i also dislike interface builder, and i’m not a major fan of views either (much prefer to modify one view the whole time than create a few views)

I did think maybe you had used MVC for tutorial purposes, which in fact does it make it very easy to follow and as you said makes it alot more readable than trying to read someone like John Carmack’s work

Thanks for the reply though, and looking forward to reading your next tutorials (about to go back and watch your particle tutorial and hopefully pick up some useful tips) :-)

Anonymous  on July 12th, 2009

Hey Mike,

Quick question: If I wanted to access the player position in another entity, say, your ghost. How would I do that?

Thanks!

A Person  on July 13th, 2009

@Anonymous
You have to add a property and an ivar for. It’s position.

Anonymous  on July 13th, 2009

@APerson

Thanks. I tried that but I must be missing something. Some small detail. Can you elaborate?

A Person  on July 13th, 2009

@anonoymous

under the Image header make a variable CGPoint origin;. Now make it a property @property (nonatomic)CGPoint origin;. Then when this objects render method is called you can set its origin to the point specified. For example in the image class you have renderAtPoint method, in their put origin = point;. I’m not using tutorial 10′s game structure anymore so i can’t give specifics of how ghost would get this but i belive when the ghost updates you would assin the image class origin variable to the one you make for the ghost. I have a little trick for allowing the image class so you can render with the origin or the point in the renderAtPoint method.

A Person  on July 13th, 2009

Has anyone here made a render manager? I am currently rewriting my custom objective c engine in C++ and i am trying to make a render manager. I am not to sure about how to make this work, i’ve got some code now but i can’t test it because the Texture2D class and image class aren’t in C++ yet. Here is my code :
// Enable gl states
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);

// Gather data for each index of the array and push it into the stack
for(int v=1;vred, filters[v]->green, filters[v]->blue, filters[v]->alpha);
if(textureNames[v] != textureControl->getCurrentlyBoundTexture()) {
glBindTexture(GL_TEXTURE_2D, textureNames[v]);
}
glVertexPointer(2, GL_FLOAT, 0, vertices[v]);
glTexCoordPointer(2, GL_FLOAT, 0, texCoords[v]);
glPushMatrix();
}

// Draw
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

// Reset stack
for(int v=1;v<vertices.size();v++) {
glPopMatrix();
}

// Clear arrays
vertices.clear();
textureNames.clear();
texCoords.clear();
filters.clear();

// Disable gl states
glDisable(GL_BLEND);
glDisable(GL_TEXTURE_2D);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);

The arrays are sent data from other parts of the engine like the image class renderAt method, then once every object you want to draw render function has been called then you call the renderManagers render function which does the actually drawing of everything and only calls glDraw once.

This builds fine but i cant test it (yet), would this work?

bob  on July 13th, 2009

@A Person
Good Job, I’ve been wondering about the same thing. It would be nice if we could batch draw, I have about 50-70 sprites on the screen and calling gldraw each time is a killer.

A Person  on July 14th, 2009

@bob

i just finished the Image.h and i found out Texture2D cannot be rewritten in C++ because it uses UIKit. Anything that uses UIKit can either use Objective-C or Objective-C++ so i guess the image class will be mainly C++ with Objective-C. I will try this out very soon and post results.

CraigGiles  on July 14th, 2009

sure it can, i have a C++ version that i used for my old engine… i since am in the process of re-writing the engine in C++ and re-wrote the Texture2D class.

Texture2D is nothing more than a bunch of C++ calls, and the UI portions of the class can be re-written using CoreFoundation for loading the image. In fact, my current Texture2D class does just that…

http://code.google.com/p/djinn.....%20Manager

look for the Texture2D class. I can email you my old Texture2D (its basically Apples Texture2D modified for pure C++) if you wish too… but that will give you an idea on how to do it.

Navee  on July 14th, 2009

Hi, thanx for this wonderfull tutorial…. very well oop structured..
i found that tilemap class of this tutorial(10) renders currupt tiles on top of actual tiles when i was trying to render first 20 tiles for my 150 tilemap. but same was running well with earlier tilemap class of tutorial 6.
may be i m doing something wrong.

A Person  on July 14th, 2009

@CraigGiles

Thanks i had a copy of your engine and i just added the texture 2d class in and made the changes to suit my needs.

Anonymous  on July 14th, 2009

@APerson

Thanks for the info, but I think you may not be getting my question. Or maybe I’m not getting your answer…

So you have me, the player. And I’m being controlled, moving around the screen. My x and y coordinates are changing to reflect this.

Now lets say I have an enemy. Hes doing what he does, maybe wandering around. I want him to know the x and y of the player, me, in order to allow him to chase after me, look at me, etc.

The tutorial 10 setup has a director and actors, game managers and other things. So its not exactly as simple as adding another property for the ghost (I don’t think).

Mike, or anyone else, any ideas?

CraigGiles  on July 14th, 2009

@Anonymous

Not sure if this is the way you’d want to handle this problem, but why not just have the monster in question store a reference to the “character being chased” (it could be a player, or npc, or anything really) and expose the players location via properties?

mike  on July 14th, 2009

@Anonymous, so, how about this. Expose the players position via properties. They could be readonly as you only want to read them and not change them externally. Inside the GameScene you could have an object which is an instance of Player. This too could be exposed as a read only property from within GameScene.

Then, inside the bad guy class you can access the GameScene through the director as the currentScene will be referencing the game scene. This should allow you to then access the player property within GamsScene which in turn can give you access to the location property within the player.

Its a little bit long winded due to the OO approach, but hopefully that makes some sense. It’s basically what Craig has described above.

Let me know if you need more and I’ll see what I can do.

A Person  on July 15th, 2009

@Anonymous

I don’t know if you can do this in objective c but in C you could make player a friend class of ghost so it could access players private members.

CraigGiles  on July 15th, 2009

I would not suggest something like that… it defeats the purpose of data hiding in the first place. If you just expose what you want others to see, you can preserve the data and make them available for classes to use.

In this case, having it exposed isn’t bad at all since it is the position… you’ll need that for several things along the way including collision detection, rendering your character to screen, etc etc… this is also assuming that your character isn’t doing all of that in their own update function and is letting some other class control that stuff.

Goose  on July 17th, 2009

@A Person

Did you manage to get the render manager working? I’ve been trying to get something similar to work, bu tI just cant seem to get my head around it.

I’d very much appreciate if you could post your code of what u’ve done so far.

Ive got about 100 sprites on screen and the fps is rather low, hopefully a render manager which draws the sprites in batches will solve my problem!

mike  on July 17th, 2009

Hi Goose, you will certainly see huge improvements from batching up your OpenGL calls. You will also see improvements if you move to an Interleaved Vertex Array and make sure the data within that array is in the right order.

There is a good Apple tech note at http://developer.apple.com/iph.....n2230.html which goes through optimizations you should consider when using OpenGL ES on the iPhone. Its a good read although no code :o(

I am planning on doing a Tutorial on creating a render manager. I’m working on my render manager at the moment and the results have been great. Once I get the code finished and some time to get the tutorial done I’ll post it up. I want to get Part 2 of Tutorial 10 finished first as people are waiting for that and then I’ll move on.

There have already been some other good posts by people on creating a render manager on this blog so if you have not already seen those posts have a search and it may help you.

Mike

Anonymous  on July 17th, 2009

@Goose

That code that i posted I’m sure won’t work but I’m working on a new one (almost ready for testing) that will hopefully do the job i’ll post it as soon as it’s ready.

A Person  on July 17th, 2009

@Goose

That code that i posted I’m sure won’t work but I’m working on a new one (almost ready for testing) that will hopefully do the job i’ll post it as soon as it’s ready.

Goose  on July 17th, 2009

@A Person

I’ve been trying to get something working all day but still with no luck :(

So looking forward to seeing what u’ve managed to come up with :)

A Person  on July 18th, 2009

@Goose
I’ve implemented vertex and index buffers from apple and it’s almost ready to go except textures. This is because you obviously can only bind one texture at a time so you have to call glDraw for every different texture, my problem is how to i organize this because if i had two textures and i put them into the vertex array and every second one was texture B and every first one was texture A how would find this all its confusing? Sorry if i worded that funny so i’ll make a diagram

A B A B A B

I have to pull all A Textures out and find matching Texture Coordinates and Vertices, I’m gonna start trying now so hopefully it will be done for tomorrow but if anyone else has got some code to show that would be greatly appreciated.

mike  on July 18th, 2009

@A Person, one way to tackle that problem is to have a structure for each image which contains the images geometry, colour and vertex information. When you place that into the Interleaved Vertex Array get its index and using arrays hold that index against the texture name for that image. When you render you can then loop through each texture and only render images which use that texture by only using their IVA indexes inside a glDrawElements call. You would basically end up with a single glDrawElements call per texture.

I am going to do a blog post on this when I get back from holiday as it needs more explaining, but basically you use glDrawElements which allows you to specify the elements within an array using their indices, so you can have a single array which contains info for all your images to draw, but only pass in the indexes for those images which share a texture, looping through the textures used by the images that have been placed on the render queue.

I am currently have a structure for each Image I am called a TexturedColoredQuad, which contains four TexturedColoredVertexes each of which contains a Vector2f for the vertex location, Color4f for the colour info for that vertex and another Vector2f for the texture vertex. This structure is then placed inside the Interleaved Vertex Array of the render manager when the Image is asked to Render and as above I just pull out those entries in that array using their index based on texture.

Sorry for the rushed comment but I wanted to respond before I head off, so I hope it makes sense and I will explain more when I get back.

Good luck

Mike

A Person  on July 18th, 2009

@Mike thanks that gave me an idea, my old attempted way was really inefficent.

wuzutags  on July 18th, 2009

Hi mike,
I’m still battling with the idea of mixing UIKit and Opengl by using interface builder to build my settings and high score screens instead of reinventing the wheel. Do u think its a good idea?

Also, I’ve started building UI widgets in opengl though. I’m left with the slider, keyboard and text field to go. I’ve built a keyboard button class which has an image and character using the angel font class and this class knows its rectangle space so its able to detect if it has been pressed. I then generate a QWERTY keyboard using these buttons in a keyboard class. I’m now left with the general text input class which will involve the keyboard class, and a custom text field which I intend to build from an accumulated text string generated from tapping the keyboard.

But then, I’ve not seen any game yet on the appstore implementing its own text input interface so I’m scared it might be a major rejection factor from Apple.

what to you think? Should I continue with this custom text input class or I shd use the UIkit text field.

I’ll post this text input class if I’m done though.

A Person  on July 19th, 2009

I have a quick question which has been bugging me for a while now I’m new to openGL so bear with me.

What are indices?
Why do the classes calculate them with fixed numbers?
How does opengl use them?

here is what i know

I think indices are for indexing the vertex array’s

I only can guess that that *6 is because a square is made up of two triangles with each 3 vertices and thats total six.

I don’t know how opengl uses indices at all.

Hopefully this may lead me to find a way to finish my render manager, i’ve been watching some of the old tutorials but have no luck (on tutorial 6 now).

Kingbombs  on July 19th, 2009

Hey,

I was wondering if theres a way to use textures which don’t have a size that is a power of 2

I have been looking at quite a few sites, and how to ‘pad’ out an image so the original image isn’t a power of 2 but when it gets loaded into the program to become a texture it is padded out (with what i seem to be reading) with black pixels.
For starters i’m not totally sure how to do this, but from what i can see is that i have to then use that new kinda size of the image to do UV mapping.

What i assume from this is that i must set up the texture co-ordinates to be something like 0.5,0.6, 0.5, 0.8, …. etc not the standard 1,1….0,1 etc
The problem with me taking this route is that i use other textures that require the texture co-ordinates to be 1,1 0,0 0,1 1,0 etc
I would change the texture co-ordinates when i need the different ones, but that would mean switching between the the different texture co-ordinates alot rather than just using one texture co-ordinate for the whole thing. I’m not able to batch up all the drawing calls for a single texture co-ordinate and then move to the next texture co-ordinate and make all those calls. The code can’t really be changed to allow this.

So i was wondering if there is another way to go about this?

CraigGiles  on July 19th, 2009

@Kingbombs
I actually just looked into something like this myself.. since I threw out my old Texture2D class, wrote my new one… i wanted to figure it out so I could start working with Texture Atlas’s. I actually looked into the apple Texture2D file to get my ideas, and came up with the following:

First thing is first, you should REALLY read the following:
http://iphonedevelopment.blogs.....-6_25.html

Note the part where they talk about texture coords (UV and ST) I have my code fairly well commented, so it should give you at least an idea on how to do things… but now that you’ve read the above article it should be a little easier. Anyway, my texture2d class:
http://code.google.com/p/djinn.....%20Manager

You’ll find the re-sizing of the texture in the loadFile function. Should give you an idea… hope it does ;)

CraigGiles  on July 20th, 2009

I was given the following code as a quicker way to obtain the next power of two… and wow; i had forgotten about bit manipulation (since it was literally the last thing I learned in my last course and had not even had a chance to really use it)

But if you replace my code with this, it will do the same thing in a quicker way.

int nextPowerOfTwo(int v)
	{
		v--;
		v |= v >> 1;
		v |= v >> 2;
		v |= v >> 4;
		v |= v >> 8;
		v |= v >> 16;
		v++;
		return v;
	};

Kingbombs  on July 20th, 2009

sorry i should have mentioned, working out how to get to the next power of 2 is not a problem

Its how you get rid of the part that you fill it with, because i don’t want to have to define next texture co-ordinates sucha as: 1/y1*y2, 1/x1*x2
dividing the old width of the image with the new width and times it by 1 to get what that value would be in the 0-1 range

doing this means i need to create new texture co-ordinates for virtually all my images, which i don’t want to do

Need an alternative method to this

Eric  on July 20th, 2009

Depending on the art sometimes I just stretch the original image in a paint program to fill a 2^n x 2^m sized texture (e.g. I have a shadow image that was like 150 x 100, I scaled it to 128 x 128 and it looks fine). It’s easy to try and if you’re already using texture coords from 0 to 1 it should be even quicker to see if it’s okay. This especially works fine if you’re already scaling the art. If you’re shrinking the art I recommend generating mipmaps too. It doesn’t take much more texture memory and increases image quality at small sizes and performance.

wuzutags  on July 20th, 2009

hi guys,
I made a post earlier involving UIkit and OpenGL, Pls could any of u help make a decision! I’m posting it again.

“I’m still battling with the idea of mixing UIKit and Opengl by using interface builder to build my settings and high score screens instead of reinventing the wheel. Do u think its a good idea?

Also, I’ve started building UI widgets in opengl though. I’m left with the slider, keyboard and text field to go. I’ve built a keyboard button class which has an image and character using the angel font class and this class knows its rectangle space so its able to detect if it has been pressed. I then generate a QWERTY keyboard using these buttons in a keyboard class. I’m now left with the general text input class which will involve the keyboard class, and a custom text field which I intend to build from an accumulated text string generated from tapping the keyboard.

But then, I’ve not seen any game yet on the appstore implementing its own text input interface so I’m scared it might be a major rejection factor from Apple.

what to you think? Should I continue with this custom text input class or I shd use the UIkit text field.

I’ll post this text input class if I’m done though.”

Mike  on July 20th, 2009

@wuzutags, that is a good question. for anything complex like entering text with a keyboard I would UIKit as it’s so much easier. If it is just buttons etc and you want to have the look and feel of your game then some home made controls would be cool.

So basically I would stick with UIKit for complex controls to save yourself a load of work but role your own for simple things you want
to control the look of. For text entry you could also try the old arcade approach if looping through letters using butttons with fire to select for example.

Mike

jetwilson  on July 20th, 2009

Hi guys!

I know mikes on holiday at the mo but im hoping anybody else here can help me.

While digging around in the source code for tutorial 10 I found code for a basic unimplemented touch pad. (by unimplemented, the touch pad shows up and registers touches and tells the NSLog about it but doesn’t move anything)

I was trying to get the touch pad to talk to the player entity so the accelerometer wouldn’t be needed, but they just don’t seem to want to talk!

Has anyone else managed to get this to work or knows how to?

Thanks Jet

A Person  on July 21st, 2009

I am almost done my render manager now and will probably start a google code project with my C++ engine and i will continue to expand on it. One thing that may suck (i can’t see too many problems) is that i can’t think of how to batch glDraw calls while keeping the rendering order so no rendering order, however this can be really annoying on tilemaps or anglecode font so those will keep their own rendering system so they can be rendered in the correct order. Sprites don’t seem like to much of a problem to me but i would like to know what your guys would try or think. I guess you could always change the texture name or call glDraw more often but i’m not to sure yet.

A Person

A Person  on July 22nd, 2009

So i finished the render manager and i am on to the testing stage, however i have encountered a problem i can’t seem to fix so here is the function that causes the error:

void RenderManager::addTextureCoordinates(Quad2* coords) {
texCoords[currentQuad] = coords[0];
}

The error is EXC_BAD_ACCESS (which i believe is related to pointer issues).

A Person  on July 22nd, 2009

@CraigGiles

I am having problems with your texture2D class, its not loading the image at all. When print the width and height of the image to the iphone sim console i get 0. is there a special way to load textures that i am doing wrong?

CraigGiles  on July 22nd, 2009

I have my class only importing PNG files, and you pass in the ‘asset’ of the file (meaning only teh file name, not extension)

IE:
Texture2D *texture = new Texture2D(“particle”); // where particle.png is in resources.

A Person  on July 22nd, 2009

@CraigGiles

Sorry, i didn’t realize the default image is .png now it works.

CraigGiles  on July 22nd, 2009

Glad to hear it. You may need to adjust how the texture is bound by the way, currently it calls the Textures->bind .. just switch that to the glBindTexture call.

A Person  on July 24th, 2009

@CraigGiles

I got the actually image box to show now, but now the texture isn’t loading. it gets the proper image box but the texture coordinates are all zero so I’m not sure what went wrong there. I don’t know if this matters but the image is already a pair of two so it might be that the maxS and maxT are at 0.7 or something really low, would that affect this?

CraigGiles  on July 24th, 2009

@A Person
Have you stepped through the code to see what its doing? If so, whats the jist of whats going on?

MFerron  on July 30th, 2009

A question for anyone that can help!

So I’ve created a couple of helper functions in an Abstract Entity class. They are basically two math equations that assist me in the AI for the entity. They are called wrapAngle and ClampValue.

When trying to compile I get two linking errors:

_ClampValue, referenced from:
-[Missile turnToFace:faceThis:angle:speed:] in Missile.o
_wrapAngle, referenced from:
-[Missile turnToFace:faceThis:angle:speed:] in Missile.o
-[Missile turnToFace:faceThis:angle:speed:] in Missile.o
symbol(s) not found
collect2: Id returned 1 exit status

Any ideas? I’ve had no luck searching.

Thanks in advance,
-MFerron

A Person  on July 30th, 2009

@CraigGiles

sorry i took so long to respond, but it seems to be the glGenTextures is generating 0 otherwise everything is fine.

Got any ideas

MichaelJ  on July 31st, 2009

Hey Mike,

Thanks for these great tutorials!

I have a couple questions hopefully you can answer:
1) Why did you choose to move the tiles and other entities around, instead of moving the player and the view to stay focused on the player?

2) Related to above; I want to be able to give other entities the position of the player, but with the way you implement the movement, its as if the player really isn’t moving at all. I can’t get my head around how I can tell these entities the right coordinates for where the player is/appears to be.

Know what I mean?

Thanks!

A Person  on July 31st, 2009

@MichaelJ

i would try converting tile Coords to pixels coords and then depending on the direction of player movement you subtract or add the scroll value.

Hope that helps

A Person  on August 2nd, 2009

@MFerron

I had the same problem due to the fact that i had declared a function in the header file but had not actually implemented it. Once i did it was fixed.

MFerron  on August 2nd, 2009

@A Person

Really? I definitely had an implementation of it. Declared it in the header, and even tried just declaring it in the beginning of the .m file. I ended up moving the two functions into the Common.h file. Ended up fine then, not quite sure why.

I couldn’t find anything online regarding that type of error. Oh well. Hopefully it doesn’t keep turning up.

Something about Obj-C just doesn’t sit right with me. Might be the fact that it isn’t as widely used, and therefore documentation isn’t as extensive as other languages that have a larger usage base.

-MFerron

CraigGiles  on August 3rd, 2009

@A Person
I finished my render manager / batch rendering system, and would love to compare ideas with you to see how I went about doing things differently and how yours works compared to mine. Since we’re both working in C++, it would be educational for me to see how you think compared to me :) I wrote up an article at my webpage, but would love to get in contact with you via email or something.

Zoe  on August 3rd, 2009

Hello Mike.

Thank you for taking the time to do these tutorials. It’s nice to see and ‘hear’ someone going through the same process as I am. Although I’m coming from a C++ / MS background. Btw a VERY useful link for other people like me that you might like to know is this: http://ktd.club.fr/programmati.....bjc-en.pdf

It’s a C++ TO Obj-C guide.

I’ve skimmed through all of your 10 videos, and downloaded the project from this tutorial (10) and I have a quick question – if you don’t mind?

I’ve not found any reason why you have created the ‘Transform.h / Transform.m’ classes.

You seem to be replicating native OpenGL commands (LoadIdentity, Rotate, Push, Pop etc…)

And I can’t for the life of me imagine why. With all the years of work that’s gone into OpenGL, I can’t imagine that it’s THAT easy to re-write the routines and have them more optimal.

As as I’m just completing a Masters in Games Programming at the University of Hull, where for my undergrade BSc (Software Engineering and Game Programming) and now my MSc, we’ve used OpenGL extensively, the concept of re-writing these key commands has never come up.

Could you please explain?

Thanks.

Zoe

mike  on August 3rd, 2009

Hi Zoe and thanks for your comment and that really useful link. I’m going to place that link on the site for others to use as well.

As for the transforms, the Tutorial 10 code is really just the start of what I am implementing for my book. You are right that the OpenGL matrix operations are fine and can be used without any problems, but, there are some situations when you want to perform your own transforms.

For the book I have made major changes to the Image class and also created an Image Rendering manager which allows me to batch OpenGL operations. This means that for a single texture I only have to make a single call to glDrawElements, even if I’m rendering 100′s of different images to the screen using the same texture, or sub regions within the texture if its a spritesheet.

As I am only issuing one glDrawElements command there is no possibility to place OpenGL transforms in between each image that is drawn. With the code from the tutorials each image draws itself which means we can use OpenGL to perform a scale or rotate etc. When you have all your images held in an Vertex Array and use glDrawElements, you need to have transformed the actual vertices themselves of the image so that the vertex data has been scaled or rotated which means you don’t need to perform an OpenGL transforms to draw it correctly.

This is where my own transform functions come in. I can pass in the vertices of an image and scale, rotate or translate them and load the altered vertices into the vertex array. You cannot use the OpenGL transforms to do this for you, hence you need your own routines.

Batching up your calls into OpenGL and reducing the number of OpenGL calls which are needed is really important to improve performance. Having a GL call for each image on a desktop platform may not be too much of a problem given its performance, but on the iPhone, you really need to reduce the number of GL calls or you can really kill the performance. There is an amount of overhead each time you call a GL function and on the iPhone this can really chew up the CPU if you are performing say 100 glDraw calls etc.

There can still be uses for OpenGL transforms even if using your own matrix operations for images. I have played with a wobble effect which causes the entire screen to shake, like it does in some games when there is a large explosion on screen. The images on screen all use my own matrix operations to rotate, scale and translate etc, but I use the OpenGL translate function before and after I draw my elements which means I can then cause everything on the screen to move slightly. Randomly moving translating a few pixels over a defined period of time then gives me my shaking screen.

Sorry for the long response and don’t hesitate to ask more questions if I’ve not explained this very well :o)

Mike

Zoe  on August 3rd, 2009

Thank you so much for taking the time for such a thorough response!

Now that you’ve explained it, and the reasons why, I can see how useful that is.

As I’m just about to come up against that kind of ‘barrier’ and am always looking for the ‘most’ efficient way to structure my code, do you know of any online resources / tutorials / discussions on how to go about such a thing? Obviously you’ve already started work on your own, in preparedness for the forthcoming book, but what is out there to help ‘us’ now?

However, I’m really looking forward to getting your book! :) Congrats on such an undertaking.

On a somewhat related note, what is your ‘licence’ for your code both from these tutorials / project files, and from the forthcoming book?

Are members of the community allowed to say, use your Image class in it’s original state in their own games, and publish said games for revenue on the App Store? Or should the community just learn from you lesson’s and write their own?

If it’s the former case, what kind of referencing do you require? (credit’s screen etc…)

Thanks again for your time and patience.

Zoe

MFerron  on August 3rd, 2009

@Zoe

Mike posted information regarding using his code in a previous blog post. I tried finding it for you, but so far no luck. It is in the comments of one of the articles, so it is a bit hard to find.

If I remember correctly, you are free to use his code as you like, as long as you give credit where credit is due and include his legal disclaimer.

Although you should try to find Mike’s personal comments about this.

-MFerron

amirookie  on August 3rd, 2009

Dear Mike,
Wonderful to discover this website. Requesting a help…

In your tutorial 1. I learned how to draw a sprite using the texture2d files. Where I got stuck was drawing a 3D rotating cube within the same code. It just wouldnt show.

I have tried everything but can make the two work together…

Is it possible for you to show me a way to have 2D sprites and 3D rotating cube in the same view.

Please show this in the tutorial 1′s code so that I can clearly see how it was done.

Many thanks,
don, amirookie@yahoo.co.in

“looking forward for your book”

mike  on August 6th, 2009

@amirookie, It is certainly possible to mix 2D and 3D together. It usually means changing the projection matrix during the rendering process so that things that need to be drawn in 3D can do so with perspective and then 2D elements are adding on top without.

I will add your request for a tutorial on this to the list I have at the moment. Things are busy at the moment with the book etc, but I will be looking at further tutorials to record.

I cannot say when I’m going to get around to this, but it is now on the list.

Mike

Anonymous  on August 6th, 2009

QUick question … why does OGLGameController extend UIView?

mike  on August 6th, 2009

@Anonymous, good question. I’ve just checked and indeed I am inheriting from UIView. This I is just a hang over from some testing and playing I was doing before I did Tutorial 10. It can be changed to NSObject and all should be fine.

Good spot

Mike

MikeyP  on August 6th, 2009

Hi Mike,

Regarding the problem in MenuScene updateWithDelta and having to ignore the delta for the transitionIn …

Could it be because the ‘lastTime’ is being setup for the first time in the initializer of EAGLView which may be called some time before the mainLoop begins?
ie. have you tried lastTime = CFAbsoluteTimeGetCurrent(); in mainGameLoop just before heading into the while(true) loop?

Cheers,
Mike P.

mike  on August 6th, 2009

Hi Mike, thanks for the info. I’ll check that out. From what you have said it does sound like that could be the problem. I’ve not looked at the Tutorial 10 code recently as I’ve been working on the book code, but I will check that out and see if it fixes the problem. I’ll get to the same point eventually with my new code so it would be good to have sorted it.

Cheers

Mike

MikeyP  on August 6th, 2009

Also,
A small point Mike, but in the applicationDidFinishLaunching method you have:

glView = [[[EAGLView alloc] initWithFrame:[UIScreen mainScreen].bounds] retain];

Clearly, being where it is it’s not going to be causing a memory leak to be losing sleep over but it’s a good example of code that should ring alarm bells…

Doing an alloc and retain will give you an object with retain count of 2.

Cheers,
Mike P.

mike  on August 6th, 2009

Another good spot Mike, certainly not something which should be gone given alloc puts the retain count to 1 anyway. No excuses for that one really. I’ll get that bugger removed right away and upload a new project so its not in there for anyone else who down loads the project.

Mike

MikeyP  on August 6th, 2009

Hi Mike,

No worries, I only found your blog and tutorial series recently so am playing catchup a bit!
Good luck with the book …

Cheers,
Mike P.

Wuzutags  on August 8th, 2009

Hi mike,
when will this new render manager be available? I’m completing a very graphic intensive game for the App store soon. I’ve gotton everything working fine in simulator, but game crashes after I play the 1st, 2nd and 3rd stages when iphone is restarted at fresh. But crushes at the menu screen on subsequent loads after the 1st run.
I’ve checked and optimized my game code so much that, I’m suspecting the glDrawElements call in the Image Class to be causing this.
I plan to send game to apple by next week n this is really taking my time.

I’d be grateful if anyone else can help me with a render manager class. I’m trying to follow what @Criag has done in the Djinn engine but its much work for me to integrate into mike’s structure.

Incredible iPhone Game Programming Tutorials With Video | iPhone Development Tutorials and Tips  on August 11th, 2009

[...] iPhone Game Programming – Tutorial 1 iPhone Game Programming – Tutorial 2 – Image Class iPhone Game Programming – Tutorial 3 – SpriteSheet Class iPhone Game Programming – Tutorial 4 – Bitmap Font Class iPhone Game Programming – Tutorial 5 – Animation Class iPhone Game Programming – Tutorial 6 – Tiled Map Class iPhone Game Programming – Tutorial 7 – Singleton Class iPhone Game Programming – Tutorial 8 – Particle Emitter iPhone Game Programming – Tutorial 9 – Sound Manager iPhone Game Programming – Tutorial 10 – Game Structure [...]

Siamak  on August 11th, 2009

Hey, i have a small problem, when running on simulator everything works fine, but when i try to run it with performance tool(leaks) i get the following error:
Dyld Error Message:

Library not loaded: /System/Library/Frameworks/AVFoundation.framework/Versions/A/AVFoundation
Referenced from: /Users/Siamak/Library/Application Support/iPhone Simulator/User/Applications/BBCF15A5-8446-4333-9E5C-6857B611FC38/GameEngine.app/GameEngine
Reason: image not found

does anyone know why and how, i have tried both 2.2.1 and 3 but the same result.

mike  on August 11th, 2009

Hi Siamak, silly question maybe, but have you made sure that the AVFoundation framework has been added to your project and that it is the right one for the OS version you are using i.e. 2.2.1 or 3.0?

Mike

Siamak  on August 11th, 2009

@mike
Yes, and it is set to relative to the SDK.
The thing is that it just works fine, but when i run the game with the performance tool(leaks), then it crashes.
The problem started when i put the glView inside the subview of a nib file, i’m using nib files for menus and settings, I load a main window and then attach the subview of nib file to it, inside the subview i attach the glView to it. and sinds then the problem occurred.
Its really weird, Tuturial 10 works just fine, and i haven’t changed anything to the audio class.
ps. thanks for the fast response mike.

Siamak  on August 11th, 2009

Hmm, silly, silly, i have changed the Relative to current SDK option to absolute path and now it works also fine on Performance tool.
That’s why they say never assume anything in programming.
Thanks anyway

mike  on August 11th, 2009

Excellent, I’m glad its working and your right about assuming anything, as when we assume it makes an ass|u|me :o)

Mike

Early  on August 11th, 2009

I’m having a little trouble understanding what you are doing with the new Sound Manager. how do you start a sound now that the the playSoundWithKey method has changed to

- (NSUInteger)playSoundWithKey:(NSString*)aSoundKey gain:(ALfloat)aGain pitch:(ALfloat)aPitch location:(Vector2f)aLocation shouldLoop:(BOOL)aLoop sourceID:(NSUInteger)aSourceID {

Early  on August 13th, 2009

Sorry I realize that wasn’t a very well constructed question. It’s so easy, for me at least, to overlook little things. my problem here was that I wasn’t passing in -1 as the sourceID.

The sounds work now and they work directionally compared to the Player’s position which is pretty cool. but If I have a looping sound the sound always plays in the direction it started and does not account for the players movement. is it possible to update the sound location as the player moves?

Early  on August 13th, 2009

never mind. Really very cool by the way.

[_sharedSoundManager setListenerPosition:Vector2fMake((_player.tileX*50), (_player.tileY*50))];

A Person  on August 14th, 2009

@anyone

I have googled this all day but can’t seem to find a solution, it is probably something simple as i am new to C++ so here is the problem.

TextureManager.h

map textureMap;
textureMap textures;

TexutreManager.cpp

void releaseTexutre(const string& asset) {
textureMap::iterator it = textures.find(asset); /* this line give me a EXC_BAD_ACCESS that leads all the way back to std::string::compare*/
}

I’m trying not to give the whole entire file but if you need more just ask.

its quite like CraigGiles TextureController in his djinnengine

CraigGiles  on August 15th, 2009

What kind of map is it? Your file doesn’t show that. (IE: map textures)

Also, I’d have to see the code in context in order to see what its doing.

CraigGiles  on August 15th, 2009

nvm, the site doesn’t like less than / greater than symbols :)

mike  on August 15th, 2009

Hi Early

Sorry for not getting back to you sooner and I’m glad you fixed the problem. The idea of source ID is that you can use -1 which means the sound engine will just look for the next available sound source, or you can specify an actual sound source id and the sound will play in that source, stopping anything that was already playing in that source.

The reason I added this was for the walking sound in my game. I am playing the walking sound over and over again as the player moves an the sound engine was previously playing up to 32 simultaneous walking sounds, which was not so good :O)

Now I force it to play in a specific sound source and it only player when that sound source has stopped playing the previous sound which is much better.

Hope that helps.

Regards

Mike

iPhone Game Programming – Tutorial 10 – Game Structure | 71² – The … | IPhoneMate  on August 20th, 2009

[...] the rest here: iPhone Game Programming – Tutorial 10 – Game Structure | 71² – The … Share and [...]

rselig  on August 21st, 2009

Mike, great tutorials. I’m gleaning lots from them.

I wonder if you’ve found a good pattern for chaining asynchronous commands in the doWork part of a game loop? For example, when a game reaches an end game state it may call for a sound to be played first, then a visual effect to be shown, followed by some state change instructions. The sound and visual effects should complete before the game state changes execute, all whilst running inside a game loop.

It’s simple enough to block state checking by setting a mode in he doWork code. I’ve toyed with the idea of creating an array of performSelector instructions, raising notifications when each instruction completes and popping the next one off until the queue is exhausted. But that seems inelegant.

Any ideas?

Gregorski  on August 31st, 2009

Mike,

I’ve just got to the end of all 10 tutorials. Thanks for all those, I’ve learned a lot so far. I have one question for you, and this may be a basic one, but I’m new to C and OO. In your latest tutorial you have changed many variables to have _ prefixes. Can you explain the logic behind when you do and don’t use the _. I can’t spot what the pattern is. This is slightly confusing for me anyway because in the language I usually code in an _ denotes a constant, but that’s my problem, not yours :).

Thanks again,
Greg

mike  on August 31st, 2009

Hi Gregorski, glad you have liked the tutorials and great question. In preparation for the book I’ve been trying to identify the Apple preferred style for code layout, naming conventions etc. I spotted that in a number of Apple code samples they were putting _ in front of the method instance variables, i.e. ivars that were only being used internally and not exposed using getters and setters (properties).

This is the style I went with in Tutorial 10, but, since I’ve done more reading where Apple actually say that you shouldn’t prefix your variable names with anything. Its all down to your personal style to be honest, but for my latest code i’ve got rid of the _’s

Hope that helps :o)

Mike

Gregorski  on August 31st, 2009

Mike,

That’s cleared it up, many thanks, and thanks again for the tutorials, they’ve made my transition to iPhone/OO/Objective-C so much easier.

Regards,
Greg

Gregorski  on August 31st, 2009

Mike, one other question (which I’m sure I can figure out myself but I’m being lazy). If the phone is in landscape mode, does the co-ordinate system still work bottom left (relative to the new orientation) or do I need to transpose the co-ordinates accoridingly? Looking at your code it assumes X is always the smaller co-ordinate in certain places (hard coded 480′s).

Regards,
Greg

mike  on August 31st, 2009

That can be a bit of a gotcha. Putting the phone in landscape mode has no effect on OpenGL at all. Some people rotate the EAGLView but that is bad as it kills performance.

The easiest route is to set up as normal and then if you are in landscape mode rotate the GL_MODELVIEW matrix by 90 degrees left or right, depending on which way you want to rotate the phone.

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glrotate(-90.0f, 0.0f, 0.0f, 1.0f);

Then set the viewport and ortho for the new coordinates

glOrthof(0, 480, 0, 320);
glViewport(0, 0, 480, 320);

Your basically swapping the width and height in those commands. From then on everything will be the same with the origin being bottom left hand corner etc.

Mike

Cyoung_mi  on August 31st, 2009

GREAT TUTORIALS!! Just finished the last one. You are very helpful! Looking forward to part 2 of number 10, as well as any more you decide to share.

One question for everyone, Any suggestions on free to use graphics, sprite sheets, sounds, etc?

mike  on August 31st, 2009

Hi Cyoung_mi. Check out the community link at the top of the blog. This is our forum where we are starting to have these kind of discussions. In the general discussion a thread has been started on where to find graphics and sounds etc.

Check it out as it will hopefully grow over time and if you find anything useful you can add it to the discussion :o)

Mike

seqoy  on September 1st, 2009

Hi Mike, awesome tutorial as usual. You really made a brilliant solution with the menu and buttons animations.

One little detail, we encourage very much start to use the Interface Builder. For statical graphic elements it’s a very easy way to do it and set everything visually. And you have the free code for buttom states and everything.

Just our vision, your work here it’s marvelous.

mike  on September 1st, 2009

Thanks Sequoy

There are certainly times when I would use UIKit for GUI based items. For some things though, especially in games, where controlling the theme completely and making everything hang together both looking and feeling like the game can be a benefit.

I am going to hopefully be using some UIKit views in my book code which will mix UIKit and OpenGL :o)

Thanks for the feedback, it is much appreciated.

Mike

madhuk  on September 3rd, 2009

Hi mike,
I have written a small game using Quartz2D,after watching your tutorial I planned to use OpenGL ES for my game…

My problem in Quartz 2D coordinate system origin is top-left.Where as in OpenGL ES it is Bottom left.So Every thing went wrong…

Now my question is,”is there a simple way to change my coordinate system?”,instead of touching my classes.

And one more thing have planned any other tutorials???

Thanks in advance,
Madhu.

Gregorski  on September 7th, 2009

As I’m new to XCode I might be being thick here. I’m trying to step through this code to see how things get called. In previous tutorials and other examples I’ve downloaded I’ve not had any problem with this. However, I don’t seem to be able to get a breakpoint to work in the mainGameLoop. I’m wondering if this has something to do with the fact that mainGameLoop isn’t being called directly but is being called via the performSelectorOnMainThread method. This is perhaps something that I don’t fully understand with threading as well. Any ideas anyone ?

Gregorski  on September 7th, 2009

@Myself lol. I found the answer to my problem on iphonedevsdk. Running Build->Clean all targets sorted the problem out !

Gregorski  on September 7th, 2009

One more thing which would be useful to understand. In the AbstractScene class, the member variable sceneAlpha is defined as float, but the property is defined as GLfloat. Does this matter? Are the 2 synonymous? Is one type cast to another automatically ?

nmw  on September 9th, 2009

Hi Mike!

Great tutorials.. You are very detailed with your words, so its easy to go off and eat breakfast while you teach.

My question.. Tutorial 9 built fine. Now, in Tutorial 10 I get the following errors:

/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator2.2.sdk/usr/include/stdarg.h:4:25: error: stdarg.h: No such file or directory

and..

/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator2.2.sdk/usr/include/float.h:8:24: error: float.h: No such file or directory

I tried setting the Code Signing Identity to “Don’t sign” but that wasn’t it..

It cant seem to find stdarg.h or float.h.. Does this have something to do with going to iPhone SDK 3.0? I still have 2.2.1 and can’t upgrade because I have a PowerPC.

Is there some way to get this project to build on the old iPhone SDK 2.x?

Thanks,

-NMW

mike  on September 10th, 2009

@NMW, thanks for the comments. I can’t say I’ve seen the problem you are having before. Have you tried to clean the project and then compile again?

Mike

nmw  on September 10th, 2009

Hi Mike. Yes, after cleaning and rebuilding it still gives the same errors.. Any other suggestions? Thanks for your help.. Hopefully a fix for this will help lots of people.

Wuzutags  on September 10th, 2009

@nmw – the error u are experiencing is normal. I had the same error when I opened tutorial 10 with 2.2.1. The fact is, mike built the code with sdk 3.0 cos I realized his base configuration in Project settings was 3.0. Changing this to 2.x gave the same errors probably because some frameworks referenced needed 3.0. So I had no alternative than to install 3.0 sdk or to create a new project and added the files as they were from tutorial 10 since the code itself is the same for all sdks. I did install 3.0 sdk and that fixed everything. Tutorial 10 run without any errors. I reinstalled 2.2.1 to try the other option and it also compiled without errors. So I suggest u try the same if u r not ready to move to 3.0 sdk.

:)

nmw  on September 11th, 2009

@wuzutags – thank you! will try that..

Simon  on September 15th, 2009

Hi Mike,

Are there going to be any further tutorials, as I’ve found these to be very useful. Appreciate you’ve probably got other things on the go, book, your game, family oh and work lol.

Just wondered, if there were going to be more, if you had an ETA on the next one.

Thanks

Simon

Goose  on September 24th, 2009

@ A Person or Mike

Would it be possible to see a sample of your render manager code.. I’ve been tryin unsuccessfully for the last month to get something working :(

I’m rendering over 100 images and performance is really poor.. and I’m hoping a render manager that batches up calls to opengl per texture will solve my problems…

Any code would be of a great help :)

Cheers

A Person  on September 25th, 2009

@Mike

I have posted a comment but it is not showing and reposting tells me i have already said that i have got no email of the comment.

What went Wrong?

A Person  on September 25th, 2009

@Goose

Sure just a couple of things, first i use a glColorPointer instead of glColor4f so i can have each vertice with a different color. Next, in order to draw you have to add a SpriteBatch object to image class then replace the renderAt lines of code with this:

[draw addDataVertices:*qv textureCoordinates:*tc texture:[texture name] filter:colourFilter];

then after you do the normal calls to draw an image you must call [draw end] when images using the same texture have done adding data. By the way draw = [SpriteBatch getBatch]; here is an example

[anImage renderAtPoint:aCGPoint centerOfImage:YES];
[anImageUsingTheSameTexture renderAtPoint:newCGPoint centerOfImage:NO];
[aSpriteBatchObject end];

So here is the SpriteBatch.h:

#import
#import "Common.h"
#import
#import "SingletonGameState.h"

@interface SpriteBatch : NSObject {
	SingletonGameState* gameState;
	Quad2* vertices;
	Quad2* texCoords;
	GLuint texture;
	int currentQuad;
	GLubyte blend[100][4][4];
	GLushort* indices;
	GLuint vertexBuffer;
	GLuint indexBuffer;
}

+ (SpriteBatch*)getBatch;

- (void)end;
- (void)addDataVertices:(Quad2)verts textureCoordinates:(Quad2)texs texture:(GLuint)tex filter:(GLubyte[4][4])filter;

@end

So here is the SpriteBatch.m:

#import "SpriteBatch.h"

@interface SpriteBatch (Private)
- (void)draw;
@end

@implementation SpriteBatch

+ (SpriteBatch*)getBatch {
	static SpriteBatch* batcher;

	@synchronized(self) {
		if(!batcher) {
			batcher = [[SpriteBatch alloc] init];
		}
	}
	return batcher;
}

- (id)init {
	if(self = [super init]) {
		vertices = malloc( sizeof(vertices[0]));
		bzero( vertices, sizeof(vertices[0]));

		texCoords = malloc( sizeof(texCoords[0]));
		bzero( texCoords, sizeof(texCoords[0]));

		glGenBuffers(1, &vertexBuffer);
		glGenBuffers(1, &indexBuffer);
		glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
		gameState = [SingletonGameState sharedGameStateInstance];
	}
	return self;
}

- (void)end {
	[self draw];
}

- (void)addDataVertices:(Quad2)verts textureCoordinates:(Quad2)texs texture:(GLuint)tex filter:(GLubyte[4][4])filter {
	vertices[currentQuad] = verts;
	texCoords[currentQuad] = texs;
	texture = tex;
    for(int i=0;i<4;i++) {
		for(int ii=0;ii<4;ii++) {
			blend[currentQuad][i][ii] = filter[i][ii];
		}
	}
	glBufferSubData(GL_ARRAY_BUFFER, sizeof(vertices[currentQuad]) * currentQuad, sizeof(vertices[currentQuad]), &vertices[currentQuad]);
	currentQuad++;
}

- (void)draw {
	indices = malloc( sizeof(indices[0]) * currentQuad * 6);
	bzero( indices, sizeof(indices[0]) * currentQuad * 6);

	for(int i=0;i<currentQuad;i++) {
		indices[i*6+0] = i*4+0;
		indices[i*6+1] = i*4+1;
		indices[i*6+2] = i*4+2;
		indices[i*6+5] = i*4+1;
		indices[i*6+4] = i*4+2;
	    indices[i*6+3] = i*4+3;
	}
    glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, sizeof(indices[0]), indices);

	glPushMatrix();

	glEnable(GL_BLEND);
	glEnable(GL_TEXTURE_2D);
	glEnableClientState(GL_TEXTURE_COORD_ARRAY);
	glEnableClientState(GL_VERTEX_ARRAY);
	glEnableClientState(GL_COLOR_ARRAY);

	glBindTexture(GL_TEXTURE_2D, texture);

	glVertexPointer(2, GL_FLOAT, 0, vertices);
	glTexCoordPointer(2, GL_FLOAT, 0, texCoords);
	glColorPointer(4, GL_UNSIGNED_BYTE, 0, blend);

	glDrawElements(GL_TRIANGLES, currentQuad*6, GL_UNSIGNED_SHORT, indices);

	glDisable(GL_BLEND);
	glDisable(GL_TEXTURE_2D);
	glDisableClientState(GL_COLOR_ARRAY);
	glDisableClientState(GL_TEXTURE_COORD_ARRAY);
	glDisableClientState(GL_VERTEX_ARRAY);

	glPopMatrix();

	free(indices);
	currentQuad = 0;
}

- (void)dealloc {
	[super dealloc];
	free(vertices);
	free(texCoords);
	free(blend);
	glDeleteBuffers(1, &vertexBuffer);
	glDeleteBuffers(1, &indexBuffer);
}

@end

this is kinda like the xna drawing stuff i don't really know much about it i just have a friend who does xna.

I would love to see what you have come up with mike.

A Person  on September 25th, 2009

@ Goose

This the Other part.

So basically its like the xna spritebatch but not really i just got the [draw end] from xna.

I also use Color for each vertice rather than color for the whole image so in Image.m replace the code in the renderAt method with this [draw addDataVertices:*qv textureCoordinates:*tc texture:[texture name] filter:colourFilter];
then when you want to draw an image this how you do it.

[anImage renderAtPoint:aCGPoint centerOfImage:YES];
[anotherImageWiththeSameTexture renderAtPoint:newCGPoint centerOfImage:NO];
[aSpriteBatchObject end];
// more images

as long as they have the same texture you can batch draw seperated by the end method like i showed above. Max is infinite but because of the blend C array it is 100 but that can be easily changed.

Goose  on September 25th, 2009

@ A Person

Thank you this is exactly what I was looking for!

Fingers crossed that this will help with my performance issues. I’ll let you know if it works :)

A.N.Other  on September 25th, 2009

First – what a brilliant set of tutorials and get that book out..

OK. I have been ‘playing’ with the code and need to set the CGRect inside MenuControl.m in side an if statement, but the compiler complains about an unused variable (warning) and an error stating that it is undeclared a few lines down.. Why?

(As you can see I’m a bit of a noob in xcode)

A.N.Other  on September 26th, 2009

Not to worry – sorted it.

xcode does not like you defining vars inside an if statement.

Pulling the CGRECT definition outside and then assigning it inside the if works.

RisingPhoenix  on October 7th, 2009

Hey there! I’m new to the iPhone programming and have a question about when I click Build and Go. I get an Error message saying: error: There is no SDK with the name or path ‘iphoneos2.2′ Sorry, forgot to mention that this is with the downloaded Tutorial 10. (And also in XCode ;-)
I have no idea how to fix this, or if it’s even fixable. But I’m hoping you guys can help! (If this is still a frequently checked blog that is)

RisingPhoenix  on October 7th, 2009

Great tutorials bu the way! I understand everything so much better now, not that I’m on this tutorial yet but, I figured I’d post on here for higher chances of a reply ;)

mike  on October 8th, 2009

Hi RisingPhonenix, the blog is still very much alive and being checked :o)

With the error you are getting, what SDK do you have selected in the drop down menu in the top left hand corner of the Xcode GUI? It’s worth checking to make sure that the right SDK is selected. Opening that drop down and selecting the SDK you have should sort out the problem.

Also performing a clean from the build menu can sometimes get rid of those errors.

Let me know how you get on.

Mike

RisingPhoenix  on October 9th, 2009

Oh hey, yeah thanks! I’ll try that now!

RisingPhoenix  on October 9th, 2009

Umm, it says I have the Base SDK selected. The options I see there are Base SDK, iPhone Device 3.0, iPhone Device 3.1, iPhone Simulator 3.0 and iPhone Simulator 3.1
I don’t remember if I mentioned it on the above post, but I am extremely new to this program so, I don’t know (from personal experience) if or where I can find more options. Hehe, not looking at a pro here ;)

RisingPhoenix  on October 9th, 2009

Oh wow, I got it to work! I just selected the iPhone Simulator 3.1
Haha, thanks. (Who knew it was so easy?!) xD

mike  on October 9th, 2009

It’s only easy when you know how :o)

Glad you got it working.

Mike

wuzutags  on October 12th, 2009

Hi all,

I’m happy to inform you my 1st App iWarrior is on App Store and going for $2.99. Thanks to you all for making this possible.
I wish to thank CraigGiles and Mike, your tutorials have been very valuable to me and I hope to share what I’ve learnt soon.
You can download the game from

http://itunes.apple.com/WebObj.....&mt=8

Cheers

mike  on October 12th, 2009

Hi Wuzutags

I’m really pleased you have been able to get your game finished and on the App store. I’m glad that my tutorials and the support from Craig has helped you get this done and I hope it does well for you.

I’ll get your app mentioned on the blog as well :o)

Mike

jcan  on October 23rd, 2009

Mike,
Thanks for all of your tutorials. They are great! I sent you a small donation a week or so ago to show my appreciation!
My question is this: How do I incorporate viewControllers into the game engine? I want a help page that uses a UIScrollView so that you can slide back and forth between help screen images. (Also have a page controller at the bottom.) I’ve used this code before, but have spent hours and hours trying to get it to work. It’s very strange. I get the help screen, but when you swipe right or left, it doesn’t move to the next screen but stops when your finger stops. Once you touch the page controller, however, then everything works fine. I’m using Apple’s PageControl example code. It’s always worked fine for me, but I can only imaging it has something to do with the game controller constantly redering the screen. Any suggestions or different approaches that I should take? Do you have an easy way to scroll between pages?

Thanks again!
Joe

jcan  on October 23rd, 2009

Sorry, Mike. Just to clarify…I know I can simply create an oversized graphic and just render different positions. I’m really looking for a way to utilize IB and standard view controller controls in certain places. (like help screens, game settings, etc.) So I’m just not sure how the engine and rendering effect this.

Thanks, again!

Anonymous  on October 28th, 2009

Mike,
How do you obtain user input like player name so that you can build and store a high score list?

mike  on October 28th, 2009

Hi Anon

I’ve not implemented this in my game yet, but my plan is to have another UIView scroll down which provides the keyboard and textfield into which you type your name. I was not planning on doing anything more complex than that.

As EAGLView is also a UIView, you can add controls directly to that view as well if that works better for your design, just watch the performance though.

Mike

jcan  on October 29th, 2009

Thanks, Mike. I didn’t mean to be Anonymous…thought I was signed in… I took the approach of directly adding a UITextField to a view as you suggested. Simply added it as a subview and resign it once I get the player’s name. Works just fine. I had a heck of a time getting a UIScrollView with paging enabled working correctly as I mentioned above. It’s the same exact code I’ve used several times before, but it simply wouldn’t accept the scroll left or right actions until I tapped on the Page Controller. It would begin to scroll but would immediately stop right where it was when you let go. However, if you tap on the page controller once, it would work just fine…over and over again. Go figure. I thought this was due to the rendering or something with Open GL, so I didn’t even try to add other objects like a UITextField directly. It worked just fine. Also, I ended up writing my own scroll controller that works just fine, so I don’t know what the issue was with the built in one. I create x pages of help screens, have a previous and next button to page, and you can slide a page to the left or right. If you start to slide and cancel, the page pops back to where it was. Once you slide past x pixels, it continues to slide by itself. This is the same exact functionality as the built in scroll view with paging, so I can’t figure out for the life of me why it acted like that???

Anyway, thanks again for all of the tutorials…they are exceptional! You’ve saved me countless hours, so enjoy the coffee!
Joe

Ken Again..  on November 5th, 2009

I have been trying to remove a ghost (i set a timer and the timer expires) but when it comes to removing the ghost on the game scene update it crashes.

I use [_entities removeObjectAtIndex:x];
where x is the ghost number to remove – the error is an
_objc_error..

Any idea why – or could you post code that sits in gameScene updatewithdelta that does remove it..

Thanks.
A Noob,

Ken Again..  on November 5th, 2009

it appears that items created in INIT cannot be removed in the updatewithdelta…. HELP!!!!

mike  on November 6th, 2009

Hi Ken

I’ll take a look at the Tutorial 10 code later and get back to you with how to remove a ghost. I need to remind myself what the code was doing in Tutorial 10 :o)

Mike

Ken again  on November 6th, 2009

Thanks Mike..

I went back to a backup and put removal code in that – it worked. So I guess something I had done inbetween had messed up – although I cant say what.

the [_entities removeObjectAtIndex:x] does work – but i found I needed to do it outside of the for(abstractentity *entity in _entities) loop – I just set a marker.

I thought (wrongly) that you could remove an object from the set whilst processing the set. I now know differently.

Thanks for the tuts.. And I so need the book your working on.. You said Spring 2010.. Spring starts in Jan… I wish.

mike  on November 6th, 2009

Hi Ken, that’s great you got it working.

Your right that when using an NSMutableArray you cannot traverse the array and update it at the same time.

I wish it would be done by Jan 2010 but its going to be a little after than I’m afraid but as soon as possible :o)

Mike

Maurits  on November 16th, 2009

Hi Mike,

Thanks a lot for these great tutorials!

You mentioned a mysterious problem with the alpha of a scene. I bumped into it as well.
Adding [_sharedDirector setGlobalAlpha:sceneAlpha]; at the end of the updateWithDelta method of a gamescene helped for me.

In my project I added batch rendering with interleaved arrays. It works great if you repeatedly draw the same texture. If somebody is interested I can post the code.

Succes and looking forward to your next tutorial!

Maurits

mike  on November 16th, 2009

Hi Maurtis and thanks for your feedback. I’m glad you got the alpha working :o)

The code I’ve developed for the book whilst based on the tutorials is significantly different. It now batch renders images while still enabling them to be rotated, scaled and positioned independently. Particles, tile map and bitmap font have their own render routines to make them easily pluggable into other peoples projects.

Its been a while since the last tutorials because of the book, but I do have a joypad tutorial running along in the background that I hope to have finished ASAP to keep things going.

If you don’t mind posting your code, I bet it would be really useful for people. You could set up a new thread in the forum by following the Community link at the top of the page.

Regards

Mike

benoitr007  on November 23rd, 2009

Hi Mike,

Thank you infinitely for these great quality tutorials. I’ve learnt a lot through them. I have a question for you, if you don’t mind. In all these classes, where would you initialize a sprite sheet that is used for many different entities? I have tried making it an instance variable of the GameScene class and passing it in my entities init methods, but I’d like to know what’s the best practice for that.

PS: Are you still planning on making a tutorial 10, part 2?

Thank you very much.

Benoit

mike  on November 23rd, 2009

Hi Benoit and thanks for your kind comments.

There are all sorts of different ways you could provide access to a sprite sheet in your game. At the moment in SIr Lamorak’s Quest I have a simple texture manager that keeps track of all the OpenGL ES textures I create. If anything asks for a texture to be made from an image that has already been processed then they simply get a reference back to the texture that has already been created.

The same thing could easily be done for sprite sheets as well.

Having the GameScene passing a reference to a SpriteSheet to other classes is also ok. If the GameScene owns the creation and management of the SpriteSheet then you may as well just pass a reference to anything else that needs it. The thing to remember is that anything else that uses the sprite sheet should retain it to up the retain count. Not doing that could cause the sprite sheet to be released when other objects are still using it with unpredictable results :o)

Hope that helps.

Mike

Benoit  on November 23rd, 2009

Hello Mike,

Thanks for the fast response! Yes, I noticed the resource manager in the tutorial 10 project, but for some reason I don’t feel good allocating and initializing a new sprite sheet (even if they all use the same texture) for hundreds of instances… So yes, at the moment I use my main game scene as some kind of “controller” for these game objects, and I pass “self” to entities that need access to its variables. Now I’m pretty sure that’s not considered good, but I simply don’t know where else to put variables that many objects use in the same scene. That being said, I’m a bit confused on the purpose of the “GameController” object… seems to me everything in there could go in the EAGLView. I guess it’s not to break the Model-View-Controller concept, but I’m still trying to understand that. Finally in what specific conditions would the sprite sheet be released before instances of the scene are deallocated? At the moment I’m not retaining anything (as I told you I’m now passing self directly) and it seems to work fine. Perhaps another basic concept I need to search on!

Thanks a lot.

Benoit

CraigGiles  on November 23rd, 2009

The great thing about the Texture Manager is you’re not initializing X amount of textures, you’ll be given a reference to the texture that has already been created.

For example, object 1 uses a texture called “Tex” , so it asks the texture manager for it. Texture manager doesn’t find it, so it allocates memory. It then passes the reference back to the object.. “Hey, Object! This is where you can find your texture”

Object 2 also wants to use “Tex” .. lets say that “Tex” is a texture of a tree… so you’ll have 1000′s of them on screen. Obj2 asks the Texture manager for “Tex” and the texture manager says “Yup, I’ve allocated that before. You can find it here” and passes a reference to “Tex”

two objects are using “Tex” but only 1 instance of “Tex” exists.

benoitr007  on November 23rd, 2009

Hi Craig, thanks for your comment. Yes, I understand what the texture manager does, however in my case you could say some memory is still allocated for the sprite sheet instance (which has a reference to the texture)… Okay, it’s almost nothing, but still. :)

mike  on November 23rd, 2009

Using the Texture Manager as a guide, you could build a SpriteSheet manager. You pass it an image reference etc and it creates the sprite sheet using the sheet name as a key.

Then when you need the sheet you go ask for it. It just passes back a reference to it. That would work well, especially if the Texture Manager is also used to help reduce the number of textures.

I’ve also created a PackedSpriteSheet class that allows me to have a single image that contains all the sprite sheet images I need and I grab them from that packed sheet to use.

This means that I can render an entire scene with just a couple of textures :o) saves a few texture binds which is always handy.

Mike

Benoit  on November 23rd, 2009

Thanks Mike, sounds like a really good idea. What do you think about the way I told you I accessed sprite sheets, by passing ‘self’ (the scene instance) to the entities that need it as well as other non-object variables? I don’t have to retain the count then, do I? (Sorry if this is a very noobish question and thanks again!)

Benoit  on November 23rd, 2009

I have another question to anyone who may read this; I’m testing my game project in the simulator and the performance is not so good. I get many frame skips (the delta jumps too), and it happens no matter how simple the game is (less than 10 relatively small images drawn on the screen). Is it normal? What can I expect from the performance on the device? (I’m unable to test on the device at the moment because I’m waiting for my developer status.)

For the record, I’m using a MacBook Pro Core Duo 2.66 GHz.

Thank you.

benoitr007  on November 27th, 2009

Hi, if you have some time, I have another quick question for you Mike (or anyone)! As I said in my last comment I noticed the delta varies a lot because of frame skips (I think); this seems to be particularly true when touch events are being handled. I recently decided to do a timing test in my game project; a timer variable is increased of (100 * aDelta) every iteration of the loop (in the update method of the scene). Normally this should mean that during a given period of time, the variable should always have the same final value, right? Well I tested it and I got variable results: after 30 seconds, the variable was once equal to 1700, and another time it was 1500. My question to you Mike would be, did you notice these problems? Are they just bugs of the simulator, or not? Did you figure out a way to “fix” the delta issue? Thank you very much!

PS: I’m aware that I could just compare 2 times (initial and final) if I wanted something to happen after a specific amount of time; I’m just using this timer example to illustrate what I think is a problem.

Benoit

PaulC  on December 21st, 2009

Hi Mike, I have a question about the level loading in your game.

At the moment my game initialisation is very similar to yours as it is in this tutorial, and I’m wanting to implement a level select screen.

I noticed that this build loads a hardcoded tilemap from the gamescene during its launch. I was wondering, what is the best way to delay this bit until a level has been chosen?

Is it a case of implementing a loading screen, which then asks the director to load the desired level, then switch to the gamescene when it’s done?

Also, do you have saving and loading player progress in your game? And if so, could you please do a tutorial on this? I’m sure it would help many people other than myself.

I know I’m selfishly asking a lot, but any insight you could provide would be immensely useful and very much appreciated.

Thankyou.

Paul

Barry  on January 8th, 2010

Hi Mike,

Well, sometimes the answer is so easy that you don’t even notice it. I’m now using the AVAudioPlayer method s.t. when I load sounds, only the file paths are loaded (not the entire sound file). Problem solved.

BTW: If you do have a quick fix/idea for the “removeSoundWithKey:” method, I’d still love to know it.

Thanks,
Barry

Barry  on January 8th, 2010

Oops! Posted my previous item in the wrong forum. I’ll repost in the Tutorial 9 forum.

Simon  on January 14th, 2010

Hi Mike

I have a simple question (possibly a stupid one). Is it necessary to import Foundation/Foundation.h in your MenuScene, GameScene etc when it’s already imported into the AbstractScene which is the parent class for the other Scenes. It probably makes no difference but, as I’m extremely new to all this, I just wanted to know.

Thanks

Simon

strider2k  on January 16th, 2010

Hi,

Is there a reason to have the gameLoopTimer while there’s a while(true) in the mainGameLoop? It seems like you only need to call mainGameLoop once since the while true will run forever until doomsday. Some of the other tutorials had while true commented out while others do not. Thanks.

Ron

mike  on January 16th, 2010

Hi Ron

No, there is no reason to have both. During the tutorials I kept switching between them to see which one was giving me the best results. I would not use them both together for the reasons you mention, but I would sometimes use a timer and other times a closed loop.

Mike

mike  on January 16th, 2010

Hi Simon

Your right, there is no need to import Foundation. In some of the classes I left this is by mistake. It does not hurt, but it should not really be imported.

Mike

Simon  on January 16th, 2010

Thanks Mike, that’s what I thought :)

I do however had one other rather more annoying question, annoying for me that it. My version of Xcode doesn’t have support for the Base SDK i.e. i can only test on 3.0 upwards. Do you know how I can test it on previous verions as when I download your projects I seem to have the full list available but not in the project I’ve created. Any assistance would be greatly appreciated as it’s driving me nuts I’ve searched every where for a solution but just don’t know what I’m looking for.

Thanks

Simon

mike  on January 16th, 2010

You should be able to edit your project settings (Project->Edit Project Settings) there is a Base SDK setting. Set this to a lower SDK version and you should be able to run under that SDK.

I can’t remember if you get all the previous versions when you load the latest or not though. I think you do.

Mike

Simon  on January 16th, 2010

Hi Mike,

Thanks again, that’s worked.. although it’s only giving me the options of 2.2.1 when i run it on the device the simulator itself will still on let me run on 3.0 and above – very strange.

If you know how to remedy that :) let me know

Thanks

Simon

Simon  on January 16th, 2010

Hi Mike,

Back again… I’ve just noticed that in your EAGLView class you’ve changed from initWithCoder to initWithFrame, why?

If it’s explained elsewhere please point me in the right direction as I’d love to know as I’m still using initWithCoder and at present I don’t seem to have any problems.

Thanks

Simon

Simon  on January 16th, 2010

Sorry for double posting – scrap that last question. It’s late I’ve been at it all day, and it’s obvious now I’ve opened my eyes.

Simon  on January 17th, 2010

Hi Mike,

During the tutorial video when you get to explaining the MenuControl class you say that under the initWithImageNamed where you initiate the image variable that you’re casting it to (Image*) as theirs a conflict with the UIImage class. I had a little play around and it looks more like a conflict in the Texture2D class. As I was having similar warnings crop up in other areas that I’m working. I’ve since renamed a few things and the problems have disappeared.

Also in both MenuControl and AbstractControl you’re importing Image.h, Common.h and foundation. Common is imported into Image so is it necessary to import it again? Would I be correct in thinking I could just import Image into the AbstractControl class and then it would know about Common through the Image class?

Thanks

Simon

Peter  on January 19th, 2010

Wanted to thank you Mike for all the hard work you’ve done to get this together for everyone.

I started following your tutorials back when you first started and I wanted to share with you and anyone else that’s interested what we’ve been able to achieve so far using your blog as a starting point.

The game we are developing can be found at our website, another big thanks to your tutorials. Let us know what you think!

Peter  on January 19th, 2010

Sorry finally figured out you can’t post url’s in here. The website is squaresmile.com

Simon  on February 22nd, 2010

Hi Mike,

I’m just going back over the code in your tutorial because I wanted to make sure I was cleaning up NSArray correctly. But I’m looking in the GameScene.m where you’re using a mutable array to hold your entity objects and I don’t see a dealloc anywhere?

Can you confirm that it’s a mistake? (As the array is set using alloc)

Could you also confirm whether i need to release each object and then the array. I assume that I’ll get a memory leak if I don’t do this.

Don’t mean to ask potentialy obvious questions, but I use your tuts as a base for my understanding so I get confused when things don’t seem to be how I think they should be, at which point doubt creeps in :-)

Thanks

Simon

mike  on February 23rd, 2010

Hi Simon

Your right that anything created with alloc should be released when your done with it. This should be in the dealloc method for the GameScene so if its not then that is a bug.

As long as you released the original object after you added it to the NSArray, then just releasing the NSArray will also release the retain it has on all its objects. If this causes the objects to have a retain of 0 then they will be deleted. That is why it’s important to release the object after adding it to the array.

Adding an object to an NSArray will up its retain count to 2, as long as nothing else has also upped the count, so releasing the original object drops it to 1 which is then dropped to 0 when the array is deallocated.

Hope that makes sense.

Mike

Simon  on February 23rd, 2010

Thanks Mike,

That’s pretty much what I thought :)

I just checked again and it’s not in the GameScene.

Simon

PS it’s a bug – one that probably still isn’t in code for SLQ :-)

Simon  on February 23rd, 2010

Thanks Mike,

That’s pretty much what I thought :)

Simon

PS it’s a bug – one that probably isn’t in code for SLQ :-)

Andyewebb  on February 24th, 2010

Hi

Great Tutorials. Not sure if i am being dumb but dont seem to be able to find tutorial 10 part 2? Anyone point me in the right direction.

Andy

mike  on February 24th, 2010

Hi Andy

Your not being dumb, part 2 is still missing in action. With the book I just didn’t get time to do it.

I’m planning on more tutorials once the book is out though.

Mike

Robert  on February 26th, 2010

Great video Mike

Very helpful but I’m a little lost and I just have 2 questions, first how to I set this thing to landscape and second how can i move the little guy around with the joy stick instead of the accelerometer. (i see the code there for it, and I’ve watch Tutorial 11 twice but I just cant get it to work)

Thanks for any help that anyone can give.

Steve  on February 28th, 2010

Hey Mike

I’m a little lost here I’ve switched the game over to Landscape mode using glRotate and glOthof but i cant figure out how to get it to render properly it keeps stretching the image, is that suposed to happen

THX for all your Help, when my game is done I’m definitely giving you a shout out in the credits

Claire  on March 9th, 2010

Hey Mike,
I’m having the same problem as the two above posters, your example code doesnt work properly if i change the PORTRAIT_MODE flag to NO and i have tried your suggestiosn above but am still no getting a coordinate system that relates to any of the corners.
Any ideas what i am doing wrong? (or could you update tutorial 10 so when landscape is used it will work properly?)
Loving your tutorials though its been so helpful.

Greg  on March 25th, 2010

I followed the code provided for setting up landscape mode but images were distorted. I’m determined to get this to work so when I find a real solution I’ll be sure to share.

Thanks Mike for these great tutorials.

Bren10  on May 21st, 2010

Hi Mike

I’ve been following the tutorials and have enjoyed learning the process but have come across a similar stumbling block when attempting to run the app in landscape view.

I’ve tried the above suggestions from other users as well as a few tweaks of my own but all without success. Using Tutorial 10′s code the best I can get is a stretched view of the menu page. Also when the device is rotated the coords of the touches don’t rotate either which gives you incorrect X/Y position on screen if going from the bottom left of the rotated corner.

Can you please provide a solution to this issue of rotating and suggest a way of handling the touches as well as you’ve obviously mastered this in SLQ – nice game by the way..

Sancho  on July 23rd, 2010

And where is part 2?

Dan  on July 30th, 2010

Hey I know this has been posted a few times already, but about the sdk’s…

Im using 4.0 and 3.2 in the simulator, and all the other tutorials so far run fine under 4.0 as I have changed the project settings each time. But in this tutorial this doesn’t work. Also im not sure if thees anywhere to download 2.2.1 anymore… the latest download form apple only includes sdk’s from 3.2 onwards…

Oh and thanks for these tutorials. a very big help, i’ve pre-ordered the book and can’t wait to read it!

Dan  on July 30th, 2010

ah, never mind. I just went around the problem and created a new project and mixed the game im building witht he new tutorial files you’ve provided…

Mp  on August 2nd, 2010

can someone please make an 4.0 version i cant build and run! And when i create new project and drag everything in the project i get 768 errors!!!

thanks soo much!

Mp  on August 2nd, 2010

oh btw the game looks great!!!! i looked at the images and it seems to be helpful! but i cant run anything

thanks again

Simon  on August 2nd, 2010

@mp its asimple to fix, you don’t need to rebuild the app. Open the project in Xcode and change the base SDK.

This can be done simply but double clicking the project file on the the top left or by selecting the file and pushing the info button, you can also get this by right clicking on the file.

Once you’ve done that select the “build” tab and look for “Base SDK” then set it to the current version.

This should make everything work fine!

all the best

Simon

Simon  on August 2nd, 2010

@mp its a simple fix, you don’t need to rebuild the app. Open the project in Xcode and change the base SDK.

This can be done simply but double clicking the project file on the the top left or by selecting the file and pushing the info button, you can also get this by right clicking on the file.

Once you’ve done that select the “build” tab and look for “Base SDK” then set it to the current version.

This should make everything work fine!

all the best

Simon

Mp  on August 2nd, 2010

Thats what I usually do but when I set it and click on the tab it doesn’t show my current version!

mike  on August 2nd, 2010

Hi Mp, I would also make sure that the correct SDK is set in the Target configuration, but double clicking on the target. Also make sure that all configurations have been changed e.g. Debug and Release.

See how that goes.

Mike

Ed  on August 2nd, 2010

Thank you, Mike. I finally got a right track with iPhone game programming. I am a Newbie in Mac and iPhone programming and wanna to build a small game in near future.

I am testing the sample code of tutorial 10 and wanna to change to landscape mode. I changed variable PORTRATE_MODE in OGLGameController.m to NO, but the display result is destorted. I succeeded in changing to landscape mode in other tutorials. Would you please tell me the tricky points to change it to landscape mode.

PS. It seems that rotation can’t take effect to the Default.png, is it correct?

Thank you very much.

Looking forward your great iphone programming book coming.

Ed (from Hong Kong)

Ed  on August 2nd, 2010

Thank you, Mike. I finally got a right track with iPhone game programming. I am a Newbie in Mac and iPhone programming and wanna to build a small game in near future.

I am testing the sample code of tutorial 10 and wanna to change to landscape mode. I changed variable PORTRATE_MODE in OGLGameController.m to NO, but the display result is destorted. I succeeded in changing to landscape mode in other tutorials. Would you please tell me the tricky points to change it to landscape mode.

PS. It seems that rotation can’t take effect to the Default.png, is it correct?

Thank you very much.

Looking forward to your great iphone programming book coming.

Ed (from Hong Kong)

Mp  on August 2nd, 2010

Thank you! Mike ur awsome it worked perfectly!

The targets were wrong! Ur a life savor!

mike  on August 2nd, 2010

Cool :o)

Mike

iPhone Game Programming Tutorial 1 | Hardblog Cafe  on October 6th, 2010

[...] iphone-game-programming-tutorial-9-sound-manager iphone-game-programming-tutorial-10-game-structure iphone-game-programming-tutorial-11-joypad iphone-game-programming-tutorial-12-saving-state [...]

Harold  on October 28th, 2010

Hi Mike,

I have a question about rotating the view to landscape mode. I’ve figured out how to show everything correct in Landscape mode (but when I adjust the Viewport everything gets pushed together, so I have removed that piece of code).

Now, when I touch the screen the touches are still the same as in Portrait mode. All that has to happen is switch them around I guess, but how do I do that? I don’t want to do it everytime I use a touch event..

To clearify: bottom left is 0,0 but top left is 320,0. Which should be 0,320 right?

The causes I thought it might have was that I don’t change anything in EAGLView, but only in ES1Renderer or the GameController. Anyway I couldn’t figure it out and couldn’t find anything on this subject, strange enough.

On a similar note: I keep getting warnings about the touchesBegan (with a view parameter), that it’s not found in the protocol. Do I just ignore these warnings or can I alter the protocol somehow so that my build is clean?

By the way: You really helped me understanding game programming on the iPhone. I’m building my first game for school right now and your tutorials really helped me to get some basic knowledge about this subject. Thanks alot!

Harold

Harold  on October 29th, 2010

Hi Mike,

Sorry for spamming you, but I ran into another problem that I really can’t figure out (and I cannot found anything about it online), so I hope you can help me..

When I render Images or tilesets (anything basically) that have a smooth gradient in them, it gets all striped, like a 64color GIF image. I’ve tried everything I know and can’t fix it, also cannot find anything about this subject online. Are there some settings I have to use to export my images?

Hope you can help me,

Harold

Siamak  on October 29th, 2010

@Harold
Mipmapping your texture will increase the quality, as it goes for exporting, PNG works best.

Harold  on October 29th, 2010

@Siamak

Thanks for your fast reply!

I’m using PNG but don’t know alot about mipmapping. After a quick Google search, I understood that it uses a smaller version of a texture when looking from a distance.

But when I decrease the texture size, the same this still happens. Here’s an example of how it looks: http://nl.tinypic.com/r/wnsqw/7

Notice the stripy-ness of the background and clouds? Since implementing mipmapping will take up some time, I wanted to make sure this problem can be fixed using mipmapping.

So do you think this could be fixed by mipmapping or do you think there might be other issues?

Harold

Siamak  on October 29th, 2010

It does look nasty :p,
I’m not sure if it would solve the problem, but implementing mipmapping is 2 min work, so worth trying it.
upon creation of your texture(in Texture2D.m) change the commented blew with new ones.

//glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER, filter);
//glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER, filter);

glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D,GL_GENERATE_MIPMAP, GL_TRUE);

Harold  on October 29th, 2010

Hmm.. it looks exactly the same with mipmapping. Strange that I couldn’t find anything about this subject online.

Do you have any other ideas of what could cause this?

Harold

mike  on October 29th, 2010

Hi Harold

Something else to check is the colour depth that has been set within EAGLView.m. The following command is in the init method for EAGLView.m file.

eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys:
		[NSNumber numberWithBool:FALSE],
	        kEAGLDrawablePropertyRetainedBacking,
		kEAGLColorFormatRGB565,
		kEAGLDrawablePropertyColorFormat,
		nil];

You’ll see that the color format being set is kEAGLColorFormatRGB565. Try changing that to kEAGLColorFormatRGBA8. RGB565 gives you 16bit color depth while RGBA8 gives you 32bit. If you can get away with the reduced color depth it does give you a small boost in performance. I’m thinking the stripping could be down to the color depth being used.

Let me know how it goes.

Mike

Harold  on October 29th, 2010

Hi Mike,

Thank you for your response.

I’ve already tried that before and it didn’t work. Looks exactly the same. Do you think it has something to do with the performance?

I’m only running one map and two images and the FPS is really high. (Or is that not related?)

I’ve also been trying to export the image differently. It always looks fine in Finder but stripy when rendered. Strange..

Do you (or anyone else) have any other ideas? Does is have to do with some kind of color scheme that’s not appropriate for subtle gradients? Does anyone else have problems with this?

Anyway if I find out, I’ll let you know.

Harold

Jeff  on December 28th, 2010

Just a quick question:

I’ve been trying to make new maps for the game in this tutorial.

I’ve been changing the tmx file just find. Now i’m trying to change the start location of the player, and the camera.

What pieces of code do i need to change to accomplish this? I’ve spent some time searching, but nothing seems to work consistantly.

Thanks!

Jeff

lalit  on June 20th, 2011

this tutorial is awesome..love to see more

Anonymous  on June 27th, 2011

Is Part 2 ever going to be released Mike?

Brenton  on September 14th, 2011

Hi Harold… (and everyone else who has had the striped gradient issue….)

I think I may have solved it as I was experiencing the same issue… FOR AGES!!

Anyway, in Texture2D.m go to the method: – (id)initWithImage:(UIImage *)uiImage filter:(GLenum)filter {}

In here there is a section setting the pixelFormat based on the transparency of the image. As my image has no transparency it was forcing it to be kTexture2DPixelFormat_RGB565 regardless if I set the drawableProperty to kEAGLColorFormatRGBA8 in EAGLView.m init()

In my testing I commented out the code so that everytime it was using kTexture2DPixelFormat_RGBA8888 and it solved my problem.. I’m not certain about any performance hits due to this change, however I didn’t need to alter my image any further than a normal PNG save from Photoshop and it works (for my example at least) so I’m happy with that.

if(CGImageGetColorSpace(image)) {
// if(hasAlpha) {
pixelFormat = kTexture2DPixelFormat_RGBA8888;
// }
// else {
// pixelFormat = kTexture2DPixelFormat_RGB565;
// }

Good luck with your project(s).

Thanks Mike for your tutes, they’ve been very helpful!

Bren10

Leave a Comment