Class design for weapons in a game? - iphone

I enjoy making games and now for the first time try myself out on mobile devices. There, performance is of course a much bigger issue than on a nice PC and I find myself particularly struggling with weapon (or rather projectile) class design.
They need to be updated a lot, get destroyed/created a lot and generally require much updating.
At the moment I do it the obvious way, I create a projectile object each time I fire and destroy it on impact. Every frame all active projectiles get checked for collision with other objects.
Both steps seem like they could definitely need improvement. Are there common ways on how to handle such objects effectively?
In general I am looking for advice on how to do clean and performant class design, my googling skills were weak on this one so far.
I will gladly take any advice on this subject.

When you have lots of objects being created and destroyed in a short timespan, a common approach is to have a pool of instances already allocated that you simply reinitialise. Only if the pool is empty do you allocate new instances. Apple do this with MapKit and table views, among others. Studying those interfaces will probably serve you well.

I don't think this is about class design. Your classes are fine; it's the algorithms that need work.
They need to be updated a lot, get destroyed/created a lot and generally require much updating.
Instead of destroying every projectile, consider putting it into a dead projectile list. Then, when you need to create a new one, instead of allocating a fresh object, pull one from the the dead-list and reinitialise it. This is often quicker as you save on memory management calls.
As for updating, you need to update everything that changes - there's no way around that really.
Every frame all active projectiles get checked for collision with other objects.
Firstly - if you check every object against every other then each pair of objects gets compared twice. You can get away with half that number of checks by only comparing the objects that come later in the update list.
#Bad
for obj1 in all_objects:
for obj2 in all_objects:
if obj1 hit obj2:
resolve_collision
#Good
for obj1 in all_objects:
for obj2 in all_objects_after_obj1:
if obj1 hit obj2:
resolve_collision
How to implement 'all_objects_after_obj1' is language specific, but if you have an array or other random access structure holding your objects, you can just start the indexing from 1 after obj1.
Secondly, the hit check itself can be slow. Make sure you're not performing complex mathematics to check the collision when a simpler option would do. And if the world is big, a spatial database scheme can help, eg. a grid map or quadtree, to cut down the number of objects to check potential collisions against. But that is often awkward and a lot of work for little gain in a small game.
Both steps seem like they could definitely need improvement.
They only 'seem'? Profile the app and see where the slow parts are. It's rarely a good idea to guess at performance, because modern languages and hardware can be surprising.

As Jim wrote you can create a pool of objects and manage them. If you looking a specific design pattern there is Flyweight .Hope it will help you.

Related

Is GameObject.FindObjectOfType() less expensive in performance than GameObject.Find() in Unity?

I'm on my last finishing touches with my indie game using Unity and I've been thinking about improving my game's performance. I was wondering if GameObject.FindObjectOfType() is less expensive than GameObject.Find()? Thanks!
If you really care about performance, try using none of them - or at least minimise it.
Using these Methods will loop through the list of GameObjects and return the object and because of the looping it is pretty heavy on the performance. So if you use them, never call them in the Update()-Method, call them in Start() or any method that doesn't get called often and store the value.
To be honest I don't know, which one is faster. If I had to guess, I would say it is GameObject.Find(), since it's only checking the name, whereas FindObjectOfType() checks the components.
But even if I would consider using FindObjectOfType(), because Find() uses a string and you might want to avoid that, because of typos (if you are not storing it inside a single class and just reference the variable)

GKEntity/Component update cycle best practices

The subject
My question is about the division of the update cycle when combining Apple's frameworks in order to respect the typical patterns and good practices on the subject, since most of the documentation and example code has not been adapted to Swift yet (or at least I can't find it anywhere).
There are so many ways to manage the update cycles in GameplayKit that I'm not too sure what is a good way of combining everything.
The elements
First and foremost: every class (GKComponent and GKEntity (sub)classes) in the Entity/Component has an update() method that you can override to perform per-frame updates. That has to come from the update cycle of the current GKScene/SKScene.
Then you have the GKComponentSystem that you can use to fire up the update() methods of every component from a given type that has been added to it. I see the point, it's very handy.
But I also want to use the state machine system and it also has an update cycle of it's own... Combining all that got me confused.
My situation
In the case where I have a subclass of GKEntity with an instance of a GKStateMachine created on initialization. The state machine has a few states (for the moment: 'Spawn', 'Normal', 'Stunned' and 'Death'.
Right now, I'm creating a big "cookie cutter" with my GKEntity subclasses and create all the components it's gonna use during the initialization. But it's becoming very impractical. For instance, I have a MovementComponent, which is a subclass of GKAgent2D. I created a singleton that manages entity creation, so after the instance is created, if loops through all the entity's components and add them to the related GKComponentSystems. The singleton has an update() method of it's own that updates passes the call to the GKComponentSystems. Some of the components I use do not need per-frame update, so no GKComponentSystem has been created for them and I update them manually as required.
If I come back to my entity, since I create everything at once and use GKComponentSystems to update the components, my component's update method is loaded with guard and if-let statements because I need to access the entity's state machine, check if it's a state where the entity can move (Normal state) and do its thing or escape the function. This is not efficient in my view: the move component doesn't need to get updated when it's spawning, stunned, or dying.
On top of that it makes my use of GKStateMachine completely overkill since my update methods are empty: the components get updated by the GKComponentSystem anyway.
My ideas
Drop the GKComponentSystems completely and simply loop through all my entities (maybe sort them in different collections at some point if need be) and call their update() methods. Dispatch the updates to the state machine which in turn will update the components involved in that state.
Keep the GKComponentSystems and use the state machine to juggle with the components, for example by adding and removing the MovementComponent from the component systems when entering and exiting the Normal state.
Option 1 is straightforward but could cause problems on the long run when my structure gets more complex becasue some components could need to be updated before others. Having each entity update its own components would scatter the update process.
Option 2 can get confusing too in a way, but my biggest concern is about the creation/removal of the components. Do I only take them out of the GKComponentSystems or do I take them out of the entity completely? What is the most efficient way of doing it?
The actual question
which one of my options would be the best? is there any better way of doing it.
If you are using GKComponentSystem to perform updates, then I would go with just that. I think a component should update only once per frame.
It's not clear from your question what you need to do with StateMachines, but there is no reason to not have them involved either directly in your GKEntity or contained within a GKComponent like the DemoBots IntelligenceComponent.

Storing object pointers efficiently for game c++

I'm making a hooked modding code for GTA San Andreas. The game has its own classes, one of them is class CPed. It handles the attributes of random pedestrians created by the game, which is huge in storage. I work with pointers to these objects in my code CPed*. Right now I use vector<CPed*> myList; to work with these objects/peds.
What is the most efficient way to store these into a container for further use? The game, itself, handles the destruction of these objects.
std::vector should actually be enough for the most part. In general, when picking a container, you should think about operations you want to do with it, but vector is almost always a good start.
If you need key-value lookup, then std::unordered_map/std::map could be of use as well.
If you need absolutely top performance, you need to benchmark different containers yourself. Using std:: algorithms and range-for should guarantee easy replacement.

Cocoa Touch Programming. KVO/KVC in the inner loop is super slow. How do I speed things up?

I've become a huge fan of KVO/KVC. I love the way it keeps my MVC architecture clean. However I am not in love with the huge performance hit I incur when I use KVO within the inner rendering loop of the 3D rendering app I'm designing where messages will fire at 60 times per second for each object under observation - potentially hundreds.
What are the tips and tricks for speeding up KVO? Specifically, I am observing a scalar value - not an object - so perhaps the wrapping/unwrapping is killing me. I am also setting up and tearing down observation
[foo addObserver:bar forKeyPath:#"fooKey" options:0 context:NULL];
[foo removeObserver:bar forKeyPath:#"fooKey"];
within the inner loop. Perhaps I'm taking a hit for that.
I really, really, want to keep the huge flexibility KVO provides me. Any speed freaks out there who can lend a hand?
Cheers,
Doug
Objective-C's message dispatch and other features are tuned and pretty fast for what they provide, but they still don't approach the potential of tuned C for computational tasks:
NSNumber *a = [NSNumber numberWithIntegerValue:(b.integerValue + c.integerValue)];
is way slower than:
NSInteger a = b + c;
and nobody actually does math on objects in Objective-C for that reason (well that and the syntax is awful).
The power of Objective-C is that you have a nice expressive message based object system where you can throw away the expensive bits and use pure C when you need to. KVO is one of the expensive bits. I love KVO, I use it all the time. It is computationally expensive, especially when you have lots of observed objects.
An inner loop is that small bit of code you run over and over, anything thing there will be done over and over. It is the place where you should be eliminating OOP features if need be, where you should not be allocating memory, where you should be considering replacing method calls with static inline functions. Even if you somehow manage to get acceptable performance in your rendering loop, it will be much lower performance than if you got all that expensive notification and dispatch logic out of there.
If you really want to try to keep it going with KVO here are a few things you can try to make things go faster:
Switch from automatic to manual KVO in your objects. This may allow you to reduce spurious notifications
Aggregate updates: If your intermediate values over some time interval are not relevant, and you can defer for some amount of time (like the next animation frame) don't post the change, mark that the change needs to posted and wait for a the relevent timer to go off, you might get to avoid a bunch of short lived intermediary updates. You might also use some sort of proxy to aggregate related changes between multiple objects.
Merge observable properties: If you have a large number of properties in one type of object that might change you may be better off making a single "hasChanges" property observe and having the the observer query the properties.

What is the most practical Solution to Data Management using SQLite on the iPhone?

I'm developing an iPhone application and am new to Objective-C as well as SQLite. That being said, I have been struggling w/ designing a practical data management solution that is worthy of existing. Any help would be greatly appreciated.
Here's the deal:
The majority of the data my application interacts with is stored in five tables in the local SQLite database. Each table has a corresponding Class which handles initialization, hydration, dehydration, deletion, etc. for each object/row in the corresponding table. Whenever the application loads, it populates five NSMutableArrays (one for each type of object). In addition to a Primary Key, each object instance always has an ID attribute available, regardless of hydration state. In most cases it is a UUID which I can then easily reference.
Before a few days ago, I would simply access the objects via these arrays by tracking down their UUID. I would then proceed to hydrate/dehydrate them as I needed. However, some of the objects I have also maintain their own arrays which reference other object's UUIDs. In the event that I must track down one of these "child" objects via it's UUID, it becomes a bit more difficult.
In order to avoid having to enumerate through one of the previously mentioned arrays to find a "parent" object's UUID, and then proceed to find the "child's" UUID, I added a DataController w/ a singleton instance to simplify the process.
I had hoped that the DataController could provide a single access point to the local database and make things easier, but I'm not so certain that is the case. Basically, what I did is create multiple NSMutableDicationaries. Whenever the DataController is initialized, it enumerates through each of the previously mentioned NSMutableArrays maintained in the Application Delegate and creates a key/value pair in the corresponding dictionary, using the given object as the value and it's UUID as the key.
The DataController then exposes procedures that allow a client to call in w/ a desired object's UUID to retrieve a reference to the actual object. Whenever their is a request for an object, the DataController automatically hydrates the object in question and then returns it. I did this because I wanted to take control of hydration out of the client's hands to prevent dehydrating an object being referenced multiple times.
I realize that in most cases I could just make a mutable copy of the object and then if necessary replace the original object down the road, but I wanted to avoid that scenario if at all possible. I therefore added an additional dictionary to monitor what objects are hydrated at any given time using the object's UUID as the key and a fluctuating count representing the number of hydrations w/out an offset dehydration. My goal w/ this approach was to have the DataController automatically dehydrate any object once it's "hydration retainment count" hit zero, but this could easily lead to significant memory leaks as it currently relies on the caller to later call a procedure that decreases the hydration retainment count of the object. There are obviously many cases when this is just not obvious or maybe not even easily accomplished, and if only one calling object fails to do so properly I encounter the exact opposite scenario I was trying to prevent in the first place. Ironic, huh?
Anyway, I'm thinking that if I proceed w/ this approach that it will just end badly. I'm tempted to go back to the original plan but doing so makes me want to cringe and I'm sure there is a more elegant solution floating around out there. As I said before, any advice would be greatly appreciated. Thanks in advance.
I'd also be aware (as I'm sure you are) that CoreData is just around the corner, and make sure you make the right choice for the future.
Have you considered implementing this via the NSCoder interface? Not sure that it wouldn't be more trouble than it's worth, but if what you want is to extract all the data out into an in-memory object graph, and save it back later, that might be appropriate. If you're actually using SQL queries to limit the amount of in-memory data, then obviously, this wouldn't be the way to do it.
I decided to go w/ Core Data after all.