In my game, at specific intervals, a function is called that adds multiple nodes to the scene (between 2 and 6 nodes). These individual nodes are all the same - they consist of the same blender model, same SCNCone, same spotlight and same physics bodies - (The blender model is low-poly, nothing extreme).
When it's time to call the next interval of nodes, the nodes that were called previously are removed (including their actions). This process repeats until the player has died. Now when the nodes are removed and new ones are added, it creates noticeable lag for roughly a second, and doesn't appear smooth.
I'm wondering whether there is a more efficient way to add and remove these nodes that could possibly eliminate lag? Since these nodes are all visibly the same, would cloning a node multiple times be better than re-creating the same node over and over within a for loop?
Any advice on efficiency or better practises would be greatly appreciated too.
Thanks!
Edit: Just a thought, should I have a node at every required position, and basically un-hide and give them actions when needed, and once they've done their job, fade out, put back at initial position, remove actions and hide?
This would mean I would need about 20 nodes in the scene at all times, but at least there would be no need to add any more, or remove any.
Start by turning ON statistics.
scnView.showStatistics = YES;
Click on the + at the bottom left of the screen to the stats screen.
What could be causing the lag? Quick things to check are:
1. Is the geometry too complex?
2. Are the textures too large?
3. Are there too many draw calls?
Cloning is better.
Yes, I think your idea at the end will avoid the lag. If the nodes being added are the same as the nodes being removed it will be more efficient just to hide and reset them.
If you are creating the nodes each time it is likely that is causing the lag, and you could even remove and add them from the scene but instead of creating them when needed store them in an array ready to be reused.
Related
I'm just starting to play about in Scratch...
I seem to have a sprite of a cat with two 'costumes', which I guess are like frames.
I made this sequence:
...but when I click the green flag the cat moves to the right but the costumes don't switch.
If I make a simpler sequence:
...and manually change the costume in the drop-down then the costume does change.
What is the limitation here?
This is by design. By default, loops have a built-in delay of about 1/30 second. (There are ways to eliminate that delay, but that is off-topic here.) This was done to help inexperienced programmers witness the effect of a loop; possibly also to make execution speed more consistent (regardless of client's CPU power).
In your case, that means costume2 will be visible for 1/30 second before switching back to costume1.
Costume1 on the other hand, is instantly followed up by costume2.
Consequently, you will only see costume2.
There are various ways to fix that.
Change your script to repeat 5 { move 10 steps; next costume; } This gives both costumes an implicit 1/30 second delay. If this is still too short, add a delay (wait ... seconds). Note: next costume wraps around, so assuming the sprite has 2 costumes, it will flip back and forth between costume1 and costume2.
Too jerky? Use glide ... secs to ... instead of 'move and wait'.
Or just take smaller steps; swap costume once every few steps.
Make two separate scripts running in parallel, one for the movement, the other for switching costumes. That makes it easier to specify a different delay for each.
Try using a [wait] block: the change between costumes may be so fast that it seems like it is walking without changing costumes...
The concept that I am talking about is similar to the style of game seen in many minimalistic, popular mobile games such as Color Switch, the Line Zen, Phases, or Bounce. These are endless games composed of a series of "levels" or "rooms" that are placed in a random order, and are one after another, creating the effect of an endless game. The key thing is that the challenges in each level are not random, they are drawn up before, and if that certain level is chosen randomly, it appears on the screen and the player moves through that level.
I think this concept might be called procedural generation, though I'm not positive.
How would I do this in SpriteKit using Swift? I'm not really sure where to start, maybe create a function for each level segment and, every few seconds, choose a random one to put on the screen?
Any help is appreciated!
Thanks so much!
Procedural generation is the name of the concept you are describing.
The approach will change a bit depending on the type of game you are trying to make but let's look at procedural generation in an infinite runner game. What you want to do is set up a buffer of level segments. The total size of the segments in your buffer should be at least twice the size of the screen. Every segment should be a child of the same segments node and they should be positioned so that each starts right after the previous one ends.
When a segment moves off screen (the player passed it):
remove that segment from the segments node
initialize a new segment (probably from a sks file)
add the new segment to the segments node
position it behind the last segment in the segments node.
The logic you use for choosing the next "random segment" is up to you. It can be truly random or you can fine tune it for the best user experience (avoid repeating segments, avoid segments that would ruin the flow, etc).
The key is to remove segments as they go offscreen and add a new one at the end of the buffer. This must be position based, not time based (time is less reliable even when the game scrolls at a constant speed).
I have 2D game, where half scene with spawn enemies and (for example) other half scene, where I want use static enemies and other elements.
I thought to create sript that after some time (for example 10 seconds), will stop spawn scripts , and run the movement of other elements.
So. Maybe there is a reasonable solution to this problem.
[UPDATE]
I need the most sensible solution of such a problem, I do not mean to do this, but how to make it better.
1) Can make static elements, which will be a certain time, just stand behind the camera, and then move ... or programmatically create static elements, over time, in advance of known locations...Or download the entire stack of elements over time.
2) Or can completely abandon this idea. A striking example is the Subway Surf, there static scenes (layout) are created in random order.
P.s. I hope I have explained my problem
Just learn to use "Invoke", it's extremely simple.
Invoke( "YourOtherRoutine", 10f );
So after ten seconds it will run the other routine. That routine could easily stop one script running, start another script running, or, whatever it is you want to do. There are tens of thousands of examples of Invoke() and InvokeRepeating() on the usual Unity forums, etc.
From your reference to Subway Surf, I assume that you want to generate static elements like the path and static trains in subway surf and non-Static elements like some moving trains. If so then I have a possible solution.
You can create pre-defined sets of elements (let say 20 or 30 set with different combination of elements) and then spawn them randomly one after another. e.g. have a look at the two reference images below.
Now, note that you might see these scenes exactly as in the images multiple times while playing the game, this is because they are pre-created, The developers behind Subway surf have created these paths and saved them as prefabs and then spawn them at different locations during game play.
You might have noticed that sometime the path is the same but the position of trains is different. This can be achieved by further creating spawn points on your path and then at runtime randomly select points on which you want to spawn your static elements.
In many cases when there are more than one gates you can pass through (I am referring to the gate in the second image). the moving trains spawns on the path of the gate you cross. Spawning the moving train can be achieved as mentioned in step two with a movement script attached to it. Regarding the question of how to know on what path to spawn there are two possible ways (that I can think of right know).
You can keep track of your players current lane and then spawn the train on that lane.
You can place separate triggers on each lane and then detect which lane trigger was triggered and then spawn the train on that lane.
For other moving trains just use the method in step 2 to spawn them but with a movement script attached.
I am trying to create a Pacman AI for the iPhone, not the Ghost AI, but Pacman himself. I am using A* for pathfinding and I have a very simple app up and running which calculates the shortest path between 2 tiles on the game board avoiding walls.
So running 1 function to calculate a path between 2 points is easy. Once the function reaches the goalNode I can traverse the path backwards via each tiles 'parentNode' property and create the animations needed. But in the actual game, the state is constantly changing and thus the path and animations will have to too. I am new to game programming so I'm not really sure the best way to implement this.
Should I create a NSOperation that runs in the background and constantly calculates a goalNode and the best path to it given the current state of the game? This thread will also have to notify the main thread at certain points and give it information. The question is what?
At what points should I notify the main thread?
What data should I notify the main thread with?
...or am I way off all together?
Any guidance is much appreciated.
What I would suggest for a pacman AI is that you use a flood fill algorithm to calculate the shortest path and total distance to EVERY tile on the grid. This is a much simpler algorithm than A*, and actually has a better worst case than A* anyway, meaning that if you can afford A* every frame, you can afford a flood fill.
To explain the performance comparison in a in a little bit more detail, imagine the worst case in A*: due to dead ends you end up having to explore every tile on the grid before you reach your final destination. This theoretical case is possible if you have a lot of dead ends on the board, but unlikely in most real world pacman boards. The worst case for a flood fill is the same as the best case, you visit every tile on the map exactly once. The difference is that the iterative step is simpler for a flood fill than it is for an A* iteration (no heuristic, no node heap, etc), so visiting every node is faster with flood fill than with A*.
The implementation is pretty simple. If you imagine the grid as a graph, with each tile being a node and each edge with no wall between neighboring tiles as being an edge in the graph, you simply do a breadth first traversal of the graph, keeping track of which node you came from and how many nodes you've explored to get there. You mark a node as visited when you visit it, and never visit a node twice.
Here's some pseudo code to get you started:
openlist = [ start_node ]
do
node = openlist.remove_first()
for each edge in node.edges
child = node.follow_edge(edge)
if not child.has_been_visited
child.has_been_visited = true
child.cost = node.cost + 1
child.previous = node
openlist.add(child)
while openlist is not empty
To figure out how to get pacman to move somewhere, you start with the node you want and follow the .previous pointers all the way back to the start, and then reverse the list.
The nice thing about this is that you can make constant time queries about the cost to reach any tile on the map. For example, you can loop over each of the power pellets and calculate which one is closest, and how to get there.
You can even use this for the ghosts to know the fastest way to get back to pacman when they're in "attack" mode!
You might also consider flood fills from each of the ghosts, storing in each tile how far away the nearest ghost is. You could limit the maximum distance you explore, not adding nodes to the open list if they are greater than some maximum cost (8 squares?). Then, if you DID do A* later, you could bias the costs for each tile based on how close the ghosts are. But that's getting a little beyond what you were asking in the question.
It should be fast enough that you can do it inline every frame, or multithread it if you wish. I would recommend just doing it in your main game simulation thread (note, not the UI thread) for simplicity's sake, since it really should be pretty fast when all is said and done.
One performance tip: Rather than going through and clearing the "has_been_visited" flag every frame, you can simply have a search counter that you increment each frame. Something like so:
openlist = [ start_node ]
do
node = openlist.remove_first()
for each edge in node.edges
child = node.follow_edge(edge)
if child.last_search_visit != FRAME_NUMBER
child.last_search_visit = FRAME_NUMBER
child.cost = node.cost + 1
child.previous = node
openlist.add(child)
while openlist is not empty
And then you just increment FRAME_NUMBER every frame.
Good luck!
Slightly unrelated, but have you seen the ASIPathFinder framework? Might help if you have more advanced pathfinding needs.
I would recommend just pre-computing the distance between all pairs of points in the map. This takes n^2/2 space where there are n traversable points in the map. According to this link there are 240 pellets on the board which means there are about 57k combinations of points that you could query distances between. This is pretty small, and can be compressed (see here) to take less space.
Then, at run time you don't have to do any real computation except look at your possible moves and the distance to reach that location.
Every enemy type in my game is a different class, and the instances are stored in a C array. In the main game loop update() is run for each enemy/item instance, and draw() is run. Some of the update() commands require knowledge of where the main player is. What would be the best route to get that information to the instance? I don't think a global variable is the smart way to do it, since multiplayer options may be added later.
This is only an example of the bigger problem, which is how things in the game are supposed to know about each other. How would enemies know they're colliding with other enemies for example.
Your need to build a multi-branched tree type structure (not simple binary tree). The nodes are the locations in the game. Each node can contain multiple simple stuctures/objects pointers (depending on your programming language). As the player moves around the game you move your player position pointer to the tree node representing the location. When you start the game this tree type stucture is populated with things to pick up, monsters etc. A random seed can also be use to scatter monsters around.
This helps the speed of the game as you only have to search current node and nodes one step away from your current location/node. Any routines triggered that monsters advance or retreat just move the monsters pointer to the next node or nodes. If a med pack is used then its pointer is destroyed from the room/node that it is in.
Good luck
One way to make the search a bit more efficient is to split the entities being updated into a quad tree. The tree would get divided based on location on the screen or in the game world you have setup. This way you can set it up so only near by entities get updated. So for example if you're doing hit detection you can totally ignore large groups.
quad trees
hope that helps
A Controller entity?
You need to think carefully about using plain arrays, linear searches through large arrays can be very time consuming to search for things like collisions.
All entities in the game, including the player, should be in the same container. Your AI will loop through them every frame and call some function that executes all the goals of every entity.
Entities (like the player) have access to all other entities through the same container.
You'll have to get clever about the container to make the entity access to the container efficient, however.