title: Approach to puzzle generation

text:
# Question
Title: Approach to puzzle generation
I have a task in hand about making a puzzle generator, that can fill a game board with colored pearls, that then needs to be solved by the player.

The core rules are

* Pearls are placed in a grid, size varying each level.
* The player needs to clear out all the pearls, or the level is lost.
* Only three pearls in a row (adjacent to each other) can be popped.
* Popping 7 or more will pop each pearl of that color, easing up the board quite a lot.
* Pearls are affected by gravity, and will fall down on the cleared pearls place.
* No new pearls are spawned.

I also need two levers to adjust difficulty. One being the number of colors the pearls can have (clear to the player) and another being a "cruelty" factor in how tight the spectrum of right solutions vs dead ends the level contains.

I seem to be at a crossroad between two ways of approaching this, and would like feedback from you gents and gals.

My two options seems to be :

* Start out with a clean board, and programmatically add pearls-combos to the board till its full. Then the player needs to track backwards from there to solve it. (They wont see it actually being generated, this will happend backstage) This should ensure that a board always have at least one solution, which is backtracking how the engine placed the pearls in the first place.
* Making a pure random board, and then set a scripted runner to try and solve it, branching every time there are more than poppable option, and starting over on a new board if all branches leads to a dead end. This should give me a good result about how many dead ends vs solutions the board contains.

Im not sure which is the best approach, or if I got it all wrong and need to go for a third approach to this. Admittedly, this is my first attempt on a puzzle game mechanics.

# Answer
Use the first approach. pick a random place on the board an add a threesome by pushing all the elements in these spots in the three columns, one row up. At a certain rare %, add a seven-some. This will allow you to add random pearls everywhere. You can guarantee multiple solutions by adding threesomes that are not codependent. breaking threesomes "bad" will make them dependent and increase the difficulty. How to break threesomes you ask?

To create a dead-end scenario:

This is how you break threesome and increase difficulty:

1. Add a threesome:

2. Add a second one underneath it (making the first depend on the second).

3. You can keep going and add a third one underneath them both (now they both depends on the purple one).

You can also add one in the middle (instead of the bottom), see how the red-orange one is completely dependent on at least three other threesomes?

If you want to lessen difficulty, add them in an "organized" way where a lesser number of rows are broken like this.
> 1 votes

---
Tags: procedural-generation, puzzle, difficulty
---


# Question
Title: Should device tilt give my object a starting speed or acceleration?
I'm developing a game for iPhones, which have a body placed in the bottom center of the sreen, and I want to move that body in horizontal axis by player tilting his device in y axis.

Everything okay with that, but I want the body to move in a physical-credible manner.

I have a formula for a velocity of the body:

V\[current\] = V\[previous\_step\] + acceleration * dt;

I don't understand (totally) a couple of things:

1. If user tilt a device, and we have a float value aTiltVector, that changes through -1 to 1, and gives us a magnitude and direction of a tilt, should I add this vector at beginning as an acceleration, or startup velocity? Should I add this value to the velocity of the body or its acceleration?
2. How should my body stop? If we give an initial velocity and acceleration, how should it stop if no other force is impacting our body? It would roll down to the edge of the screen then.
3. How do you typically achieve that behavior?

# Answer
> 1 votes
When you want it to be physically credible, all of your objects will accelerate slowly and not instantly. So add/subtract an amount of speed from the current speed of your object which is proportional to the current tilt factor.

To prevent your object from accelerating and moving indefinitely, there is friction. Friction increases quadratically with speed. So every physics frame you reduce the speed by

```
speed -= (speed * speed) * friction

```

The ideal friction should be a floating point number somewhere between 1.0 and 0.0 (but usually closer to 0.0). The exact number depends on how high your speed is and how easy you want your object to control. The ideal value needs to be found through experimentation. A higher value means a lower top-speed which is reached quicker but also makes objects stop earlier.

---
Tags: physics
---


# Question
Title: How to make and correctly use progress bar in cocos2d-iphone?
I have a game that uses a progress bar to inform player of level of certain stats of the player. For example hunger, when it starts at zero and slowly adds up to maximum bar. When he eats the hunger reduces.

I tried implementing as progressBar, but it works wrong, as the bar expands both ways, and I need it to grow one side only. Also I had hard time setting the bar, since it uses actions.

Is there an easy way to do it?

# Answer
> 1 votes
Found the following answer over here.

Grab the following image: https://i.stack.imgur.com/O5DRf.png. It is 2x30. I want to make a bar that is 15 pixels high. Normally, the dimensions would be 1x15, but since I assume you're working with retina display, we have to double such dimensions to 2x30.

Create a CCSprite with it, and set the anchor point to ccp(0.0,0.5):

```
CCSprite *bar = [CCSprite spriteWithFile:@"MyBar.png"];   // Create it
bar.position = ccp(240,160);                                // Position it
bar.anchorPoint = ccp(0.0,0.5);                           // Anchor point

```

Now the question is, how long (max) is the health bar? Let us say it is 200 pixels long. Therefore, 100% = 200 pixels long. Let us set it to 200 pixels long then:

```
bar.scaleX = 200;    // The bar is 200 pixels long now

```

So, how about 50% of health? Then, clearly, the property `.scaleX` should be 100.

```
bar.scaleX = 100;    // The bar is 100 pixels long now (50% health)

```

That is pretty much all you might need to create a simple bar quickly.

---
Tags: cocos2d-iphone
---


title: Behavior tree implementation details

text:
# Question
Title: Behavior tree implementation details
I have been looking around for implementation details of behavior trees, the best descriptions I found were by Alex Champarand and some of Damian Isla's talk about AI in Halo 2 (the video of which is locked up in the GDC vault sadly).

However, both descriptions fall short of helping one actually create a BT, one particular question has been bugging me for a while.

When is the tree in a behavior tree evaluated?

Furthermore:

If the tree is in the middle of executing a sequence of actions (patrolling waypoints) and a higher priority impulse comes in (distraction sound) , how to switch to that side of the tree seamlessly without resorting to a state machine like system and if it is decided that the impulse was irrelevant (the distraction is too far away to affect this guard), how to go back to the last thing that the guard was doing ?

I have quite a few questions like this and I don't wish to flood the board with separate queries so if you know of any resource where questions like these can be answered I would be very grateful.

# Answer
> 1 votes
If you have the computational resources, it is best to evaluate the tree every frame. If CPU time becomes an issue, you may switch to event-driven BTs or update with lower frequency.

**Behavior Switching**

To properly handle switch to a different behavior, it is vital, that all your nodes enforce an init-update-done lifecycle. That is, prior to switching to a different behavior in a selector, you call done() on the subtree you are terminating and then init() on the new subtree, only after both finish you start sending updates.

The init/done calls propagate through the tree the same way regular updates do. In the articles on AIGameDev, Alex supposes, that the init/done calls are instantaneous, but if your game features more complex logic, it might be useful to allow the init and done operations to take more than one frame, that is the node can now have much more states:

* none (prior to initialization)
* initializing (the init operation requires more updates)
* running (init finished, executing normal updates).
* stopping (node is requested to stop but requires more updates)
* done (node has finished)

Note that if a selector is about to change which branch is executing, it first signals the currently running branch to stop and only after the branch transitions to "done" does it start executing the new branch. This requires more complex logic in the sequences/selectors/decorator nodes but may save you a lot of headache in the long run. It also lets you to create special nodes that have a whole subtree to perform for when initializing/stopping. E.g. you have a behavior when your character is drinking in a pub, in the init subtree you perform a sitting animation and notify the barman that you want a beer. In the stopping subtree you perform a standup animation a notify the barman that you are leaving.

**Handling distractions**

If the tree switches to a different subtree upon a sound distraction only to realize it was not actually a distraction and switches back, you are doing something wrong. The subtree should be switched only when the impulse is actually considered important. A parallel node may help you to run some more complex code to evaluate the impulse without interrupting the guard behavior. If the code in the parallel branch decides the distraction is important, it sends the impulse to the selector to do the actual change (e.g. sets a variable).

If you for some reason need to maintain state when the NPC switches to a different behavior, you may have two kinds of operations to stop execution of a subtree:

1. Stop - stops the execution and clears state (as usual)
2. Suspend - stops the execution without clearing the state (e.g. a sequence node remembers the index of currently executed node).

A selector then may decide whether to stop or suspend the tree. Once again, you may need intermediate state "suspending" to let suspend take more than one frame.

# Answer
> 0 votes
I've been working to implement a behavior tree in Unity for the last week or two, now, and I've found that it's much better to use very generalized task nodes when developing these things. For example: It seems (to me, at least) to be a lot simpler to have only one type of sequence and one type of selector, and to have "decorator" nodes that can change the behavior of whatever comes after them.

Additionally, I've found that polling from the root out, every frame, is a bit wasteful when one is only really executing one task at a time, so I've been using a simple interrupt system, much like most modern CPUs do, rather than constantly polling a piece of hardware that is doing a task that can take quite some time to check if it's done yet, and keeping a reference to the "current task" (lowest level) that is being executed.

When the interrupt is sent, depending on the reason for the interrupt, the current action decides how to handle it.

If the interrupt is coming back because the task either completed successfully or failed, it tells its parent task to move on past it, and to continue with its operations.

If the interrupt is coming back because of a stimulus that took higher priority than the current task being executed, I set the current task (the reference I mentioned earlier) to the root of the tree, and poll. If your system is set up properly, your higher priority nodes should be earlier in the base few layers' selectors' lists, and so should be found needing before whatever it was that the agent was doing earlier would even be checked if it should execute.

---
Tags: behavior-tree
---


# Question
Title: XNA Texture.GetData "Size of the data passed in is too large or too small for this resource."
I am attempting to retrieve the color data for a given sprite located on a texture atlas by creating a new color and passing a source rectangle width and height for the given sprite. I am then passing this color variable into XNA's Texture.GetData method, as seen below. When this code is executed at runtime I receive the following message "Size of the data passed in is too large or too small for this resource."

```
Texture2D texture = level.Tiles[x, y].Texture;
Rectangle source = level.Tiles[x, y].Source;

Color[] colorData = new Color[source.Width * source.Height];
texture.GetData(colorData);

```

As far as I am aware this approach should work as it has worked previously with other spritesheets within the application. Could someone please explain why such a message would be thrown in the first place and how I may resolve it?

# Answer
> 1 votes
It seems I have managed to resolve the issue by using the overloaded Texture2D.GetData (int level, Rectangle? rect, T\[\] data, int startIndex, int elementCount) method.

```
Texture2D texture = level.Tiles[x, y].Texture;
Rectangle source = level.Tiles[x, y].Source;

Color[] colorData = new Color[source.Width * source.Height];
texture.GetData(0, source, colorData, 0, colorData.Length);

```

However I am still unaware as to why I recieved the error message in the first place. Any information on this would be appreciated.

---
Tags: xna, c#, xna-4.0, monogame, texture-atlas
---


title: How to handle input in Monogame

text:
# Question
Title: How to handle input in Monogame
I've just switched over to MonoGame from XNA. Since MonoGame is supposed to have the same API (implying that any copied code should work as usual), I've run into a strange issue- input doesn't seem to be handled through MonoGame.

When I tried to fix any missing "using" directives in that class, it automatically added `using Microsoft.Xna.Framework.Input` which implies that there's no MonoGame equivalent.

Googling the issue had no success- all the tutorials I found for MonoGame said to use XNA's input.

Is there a MonoGame equivalent for handling input, or do I just need to use XNA for that?

# Answer
> 2 votes
MonoGame intentionally uses the same namespaces as XNA as required to make it a drop in replacement.

For Example look at the MonoGame VS2010 Template

```
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

```

The `using Microsoft.Xna.Framework.Input` uses MonoGame if Monogame is included as a reference; alternatively, it uses XNA if XNA is included as a reference. If you have both frameworks referenced it would throw an error and force you to disambiguate.

---
Tags: xna, monogame, input
---


# Question
Title: Portable buffered keyboard input for XNA / MonoGame?
As a preliminary solution, I am currently using the Nuclex framework (see note below) in an C#/XNA game project for buffered keyboard input. Sadly, Nuclex relies on SlimDX.Directinput.dll and therefore to my knowledge can only be used under Windows OSs. However, I use MonoGame to target other platforms (Linux, OSX, etc.) and therfore I am looking for a portable way to integrate buffered keyboard input aross all platforms. Is there any?

Note:
This question originally linked to Nuclex on CodePlex, which has been in archive mode since 2017 and will be going offline soon.
The link now provided (mirror) goes to a copy of last version of Nuclex posted to CodePlex.
Cygon appears to be maintaining development here.
A different branch is available here.

# Answer
> 4 votes
SharpInputSystem was created for this exact purpose. It provides a portable way of access the Keyboard and Mouse on most platforms and GamePad/Joystick on a few others. In full disclosure, I am the author, but I needed a similar library for the samples I provide with Axiom.

It may need to be modified to load the MonoGame assemblies properly, I am currently loading the Xna libraries dynamically to avoid a dependency on a strong name. I can either look into making those changes if you want or if you feel up to it, submit a patch once you've got it working.

# Answer
> 0 votes
While not properly portable (it is only for Windows and Linux). MonoGame has an event for text input that uses properly buffered keyboard input.

## MonoGame.Framework/GameWindow.cs

```
    /// Use this event to retrieve text for objects like textbox's.
    /// This event is not raised by noncharacter keys.
    /// This event also supports key repeat.
    /// For more information this event is based off:
    /// http://msdn.microsoft.com/en-AU/library/system.windows.forms.control.keypress.aspx
    /// </summary>
    /// <remarks>
    /// This event is only supported on the Windows DirectX, Windows OpenGL and Linux platforms.
    /// </remarks>
    public event EventHandler<TextInputEventArgs> TextInput;

```

---
Tags: xna, xna-4.0, input, monogame, keyboard
---


title: Leaving a trail in Game Maker Studio

text:
# Question
Title: Leaving a trail in Game Maker Studio
I'm making a game in Game Maker that involves the player leaving a trail of debris behind them. This trail is permanent and has gameplay implications (for which I'm using a fairly coarse grid to store the player's movements), so I need to draw it on the screen. I'm comfortable with GML.

I have a sprite (with subimages) that represents the debris left behind. I'm not sure of the best way to go about it. Surfaces perform well and are straightforward to my mind - I draw the trail to the surface, then the room draws the surface between my objects and the background - but my rooms are more than a screen, and surfaces seem intended more as an image buffer than as a large background. A background resource I edit as I go would probably be better, but this doesn't appear to be an appropriate use of backgrounds.

Is there another approach that would work better? One consideration is that I need to be able to store the trail at checkpoints so that it's not destroyed if the player dies.

# Answer
Having a surface that draws over your entire level probably wouldn't be a good idea in terms of memory usage, but a background that does the same thing would not be any better, in fact it would be worse. You might not have any problem just having each trail piece as an individual object, but objects are pretty heavy weight and can slow your game down if you have too many. One way that could work is having a single object draw the sprite repeatedly in the correct locations. I recommend storing the trail locations in a ds\_grid then in the draw event of your trail drawing object you can have:

```
for(i = 0; i < ds_grid_width(trailGrid); i+=1)
{
    draw_sprite(trailSprite, subimage, ds_grid_get(trailGrid, i, 0), ds_grid_get(trailGrid, i, 1))
}

```

where the x values are stored in the 0 position in the grid and y is stored in 1. But all those draw calls will quickly get out of hand in terms of speed. Basically you have to choose whether to sacrifice memory or speed, whether you have a surface drawn over the whole level or you make lots of draw calls. But wait! Theres a third option. Deactivating instances.

You could have each trail be an instance and deactivate them when they are out of view, this will cause them not to take up processing time while they can still be reactivated in the game.

```
instance_deactivate_object(trail);
instance_activate_region(view_xview[0] - 64, view_yview - 64, view_wview[0] + 64, view_hview + 64, false);

```

This will deactivate all the trail objects in the room and activate the ones in the view, with a little buffer on the sides. A note of warning from the GM manual: "It is normally not necessary to deactivate instances every step of your game and this can actually cause your game to lag and runs slow. Instead it is recommended that you only run these functions every few steps in an alarm (for example), or if the view has changed position, and it is especially important that you do not use these functions in the draw event as this can lead to serious errors in your game."

This is probably your best bet as it will save you processing speed without killing your memory.
> 3 votes

---
Tags: game-maker
---


# Question
Title: How can I know how difficult a question is?
I'm making a "Who Wants to be a Millionaire" style of game. I'm really stuck at the part where I should arrange questions from easy to hard.

Isn't this subjective? How can I tell how hard/difficult a question is?

# Answer
Your assumption that question difficulty is subjective and is itself a hard question is absolutely correct! From a professional assessment standpoint it's a known issue, and while there are techniques to assist, it is best considered "an ongoing process" that requires testing and adjustment - like trying to figure out what just the right amount of salt to add to a soup.

However, there is some good news - in game shows (and their video game equivalents), they don't actually do as much ranking by difficulty as you think. In Jeopardy games, as a for-instance, sometimes $1000 questions will reappear in other play-throughs as $100 questions! So let's consider how Who Wants To Be A Millionaire-style games do it.

First, these style of games have changed a lot over time, so I'll go with the "Classic Millionaire" approach that the show started with. As the questions move up, it's better not to think of a strict rank-ordering as in each question has a specific class, but rather that they are more broadly grouped.

The early sets of questions (say, the first 2-4) were written with children in mind. This was to give a chance to let families play, and also to give the contestant a chance to warm up/adjust to their nervousness. The questions might be inspired by actual school child homework, or just generally made easy to understand (no big words), not require special deep knowledge in any particular subject, and 1-2 of the 4 multiple choice options were pretty obviously silly (usually with one trying to be outright funny).

Once the easy questions are done, the questions are more challenging. Challenge is usually defined as a mixture of these three elements:

* The question requires special, specific knowledge that is not commonly known (who is the 17th President of the United States?). Popular trivia might require you to know the binomial nomenclature for specific plants and animals, or of a particular part of a certain places history.
* The multiple choice options presented. Are any of them specifically recognizable as definitely not right? Can you logically exclude some possibilities? If the question was about an early US President and one of the choices is someone you don't think was president ever, or if they were but much more recently, then you can narrow down the options.
* Can an answer be logically arrived at, or do you just have to know the answer outright? If you are asking about a botanical name and all the options are botanical names, then you either know the answer or you don't - a genius IQ and critical thinking is of no help if "if you either know it or you don't".

So the total question difficulty is related both to how obscure the trivia being asked is (rarity of knowledge), whether or not the question is pure trivia or if you can at least partially reason an answer logically, and what choices are offered to choose from.

In Millionaire-style games the top few (hardest) questions are one's that require incredibly specific knowledge (know all the names of horses who won at least two of three Triple Crown races), have no ability to be logically deduced (all names presented are actual race horse names), and where you can't exclude any of the options (none of the names are the really famous familiar names who have recent movies about them).

## A Simplified Proposal To Get Started

Since ultimately only play-testing will really let you figure out what questions themselves are really hard, I will propose a way to get started and get you past the block.

First, write out some questions. Then put them into three piles: potentially easy kid-friendly questions (ones about common pop culture and everyday experience), medium (you don't think everyone will know the answer automatically, but it's not obscure - preferably about a common topic that's covered sometimes in movies and documentaries, like Civil War America or Famous Conquerors), and questions you suspect are going to be pretty rarely known (dig down - if it's about Presidents, don't pick one that shows up on common coins or popular monuments!). Don't worry about strict rank ordering - it's inevitable that some people just know some subjects more than others and they will think one thing is easier/harder than someone else.

Then to produce more fine-grained difficulties in the game, I'd pick "really easy" where you take easy items and pair them so that only one choice immediately appears very plausible. Easy question are then easy items with two plausible choices, one that obviously isn't right, and one more that isn't very plausible but isn't silly. And then you work up to the really hard questions where "you either know it or you don't" and it's very hard to really exclude anything, and it's the hardest (obscure sorts) of questions you manage to have.

Then, because I assume this is computerized: record the time taken to answer the question, "phone a friend" style special bonus invocations (which show the question must have been difficult to the person), and success/failure counts. This will allow you to see whether you were right or not and tweak later - but you can't get there if you don't get started!

So get started! And good luck.

...and that's my final answer.
> 9 votes

# Answer
The "difficulty" of a question is certainly hard to classify. There is a large amount of subjectivity to the issue -- for example, a question about mathematics will likely seem harder to a person with no mathematics background in their education.

You can't classify the "difficultly" of questions in general with an algorithm; you'll have to do it yourself.

One such strategy might be to introduce the concept of topics into your game, and lump each question into one or topics. Within that topic, assign each question a difficulty level (manually, based on your own personal assessment of the question). Then sorting from easy-to-hard becomes a simple matter of sorting on the scale you define for the difficulty (for example, one to ten). The topic does not need to participate in the sort, it's purely for taxonomic purposes.

You'll probably have to tweak those difficulties during play-testing. I'd suggest building in a feedback mechanism into your beta builds -- after every question, show the user the topic and difficulty of the question (as in, "that question had a difficulty of 3/10 in the math topic. Do you agree with that difficulty assessment?") and record their responses so you can make adjustments.

As with all data-collection programs, make sure your beta testers are aware that you'll be collecting their responses to these questions.
> 4 votes

# Answer
The very first thing you need to determine is what is your target audience. Your target audience will help you determine the range of what is considered common versus uncommon type questions. The broader the audience, the more generalized common becomes because the questions will have to span larger age groups of where educational boundaries vary significantly. For example, what kids learn today in school is drastically harder than what our grandparents were taught.

The next thing is to try and categorize your questions based on their commonality. For example, "Who was the first US President?" is a fairly easy and common question that most anyone with any exposure to US history should know. It is far more common than asking "What President gave the Gettysburg Address?".

The next factor to consider is that your questions are being given with multiple choice answers. This obviously can make more difficult answers much easier because of deduction to reason the valid versus invalid choices. This would make questions like my former far easier even for people who may not have had exposure to US History, but also could make the latter question even easier for those whom may not be overly familar depending on your choices. -- listing Lincoln with other names which were not even US Presidents but perhaps Presidents of other countries.

So yes, it can be subjective but there are ways you can rate your questions in a way that can be labeled as easy to difficult but the key factor is your audience.
> 4 votes

# Answer
Actually there's a simple formula for it but its based on how many people on average would get the right answer in a population.

difficulty = correct - wrong

where correct is the number of people that got it right and wrong is the number of poeple that didn't when asked to a large group of people.

The real question is ...

how do you figure out how many people on average would get the answer to a question?

When you figure that out you have your answer.

Typically, the more specific to particular focus / topic a question is the harder it is so if your questions are separated enough you may be able to "figure these numbers out" with some reasoning.
> 1 votes

# Answer
Is your game online? Then you could use a crowdsourcing approach. Just check how many players answer a question correctly and rate the questions accordingly. This can be made completely automatic.

A simple solution would be to have every question start with a score of 0. When a player answers it correctly, you subtract 1 from the score. When a player answers it wrong, you add 1 to the score. A more advanced algorithm could also take player strength into account (when your top player answers a question incorrectly, it means more than when your dumbest player fails).

You can then calculate the percentile each question falls into and confront the player with questions from higher and higher percentiles during their game.
> 1 votes

# Answer
**Questions**

I agree with the others that this since this is a trivia game, the "heart" of your game is the questions, and this is where a considerable amount of time should be spent. I would recommend starting with a list of metrics on which to "Grade" each question:

* Topic
* Sub Topic
* Geographic Uniqueness
* Percent Correct Female
* Percent Correct Male
* Percent Correct Overall
* Difficulty of the answers
* Difficulty
* etc

The gender metrics may make sense on questions related to topics such as fashion or video games. The point is not to stereotype individuals, to but to present questions that most reasonably match the level of difficulty at the point in the game where that particular player is at that time.

Use whatever you can think of that will be measurable. Then come up with a whole bunch of questions. Get friends, family, coworkers, the Internet, etc to answer the questions and begin assigning values to the metrics. By doing this, you will likely come up with a number of other metrics, and may even scrap some of the existing ones.

When you come up with other metrics then go over the questions again, then again, and again. The questions are the most important aspect of the game. Players will know if they are being fed the same questions over and over.

One of the other answers suggested using the "intelligence" of the answerer to adjust the grade. Intelligence is based on the number of correct questions, or to be more specific, number of correct answers in that topic, since different people may be very good in different subjects and bad in others.

You can even use those metrics on the fly during the game. Like if a player is answering a lot of questions in a particular topic correctly, then you can decrease the likelyhood of receiving that question as they progress in the game.

**Answers**

For the answer difficulty, if you are doing the "Millionaire" style game, then there will be answers for each question. The answers will matter considerably. The answers should also be graded based on their difficulty when stacked up against a particular question.

A "hard" question can be answered very quickly if the answers are not well designed, and conversely a "simple" question may become very difficult when the answers are very specific.

Specificity matters too. Players can become frustrated in the early questions if the answers boil down to splitting hairs. But in the latter levels, that will be expected.
> 1 votes

---
Tags: game-design, difficulty
---


# Question
Title: How can I fill a Color[] from a Texture2D given a Rectangle in SharpDX?
I used to fill a `Color[]` using XNA's

```
Texture2D.GetData<T>(int, Rectangle?, T[], int, int)

```

method, but there doesn't seem to be an equivalent overload on SharpDX's `Texture2D`. Anyone know how I can get this same functionality with SharpDX?

**EDIT**

How can I fill a `Color[]` from a `SharpDX.Toolkit.Graphics.Texture2D` given a `Rectangle` in SharpDX?

# Answer
SharpDX is a *DirectX* wrapper, not an XNA one. XNA's `GetData` methods are higher-level abstractions on top of the underlying DirectX functionality.

If you're using the D3D9 interface, you probably want a variant of `LockRectangle`. If you're using D3D11 you probably want some variant of `MapSubresource` (or the similar method for D3D10). Note that in D3D9 the operation is a method of the texture, but in 10 and 11 it's a method of device context.
> 2 votes

---
Tags: xna, c#, textures, sharpdx
---


# Question
Title: How to create soft Icecream like particles with Liquidfun and Corona
Currently using the "elastic" flags for particle behavior, which looks decent when it is flowing downwards but when the icecream collects in cup it is too liquidy. Also this gives it a springy bounce which I am not sure how to take out. I am wondering how I should make it thicker more solid along but to stay a bit elastic? Can I change behavior of particle after it is created?

I have tried with a "spring" flag and "viscous" flag but it looks sort of the same.

Demo Clip

```
Corona/LiquidFun

  -- Create Particle System
  local particleSystem = physics.newParticleSystem{
    filename = _PRT,
    radius = 1,
    imageRadius = 2
  }

  offset_x = _C.x + 70
  offset_y = _UL.y + 100
  -- Paramaters for red particle faucet

  local particleParams_red =
  {
          flags = { "elastic"},
          linearVelocityY = -10,
          color = { 1, 0, 0.1, 1 },
          x = offset_x,
          x = offset_x + display.contentWidth * 0.15,
          x = offset_x + display.contentWidth * -0.15,
          y = offset_y,
          lifetime = 60.0,
          radius = 5,
  }

```

# Answer
Check out the powder toy: enter link description here

The ice cream you are attempting to create is a lot more like a collection of soft bodies:

See this video for demonstration please.

It doesn't need to be *liquidy* once it's in the cup. The liquid could be visually in another layer just to simulate the smooth movement of ice-cream pouring down.

The real icecream (that will stay in the cup) does not have to be *liquidy* going down. You should consider using soft bodies with little bounce and high friction and a small mass. You can use the liquid for the visual effect of pouring and use a lot of possibly blurred tiny soft bodies cause ice-cream is a lot more like *sticky sand* than liquid and will look when tweaked right, more realistic as such.

Another option if you don't plan to move continue with the physical simulation, is to build the solid shape of the ice-cream programatically by adding mass where the liquid hits.
> 1 votes

---
Tags: particles, corona-sdk
---


# Question
Title: How do I handle game lag due to background apps
I'm developing a game using libgdx and have noticed on several occasions that other background apps running can cause lag in my game - especially when those apps are being updated in the background. I'm talking serious lag like from 50-60 fps down to under 10 fps while the other app installs.

How should I handle this very noticeable lag?

Thanks!

# Answer
> 1 votes
Of course if other apps are being installed while the user is playing your game it will lag. I don't think there's anything you can do about that since it is a function of the Android settings and not your game. Usually other apps do not take much processing power away from the current visible app. Maybe you personally have too many aggressive apps on your phone or you have an older phone that lags more readily.

# Answer
> 0 votes
I think you need to figure out why this is happening. Can you reproduce the behavior by creating a `daemon` app and letting it run in the background? Do other games respond the same way exactly? If not then why is your game slowing down so dramatically is the question and it's a debug question.

1. If you let the game continue as normal, it will probably highly increase the chances that the player will lose the game. This will cause frustration.
2. If you pause the game automatically it will possibly disrupt the player.

What you could consider is accepting more vague and inaccurate input from the user as correct input during this lag and when it occurs.

For instance, if the play had to touch the screen on the left between 7.3 and 7.7 seconds into the stage the give the player a wider time frame. This is hard to do but I feel it is more suitable than the other two options namely doing nothing & pausing.

Alternatively, you could simply slow down the gameplay pace when framerate drops beyond a certain point like under 30fp, you could slow down the gameplay according to the fps rate.

---
Tags: android, libgdx, lag
---


# Question
Title: Can I use flat shading on a generated mesh?
I tried to generate a mesh from code in Unity. The problem is, that the edges are automatically smoothed. When I import a model into Unity, I can set the smoothing angle of the edges, but is something like this possible with a generated mesh?

I would like to have no smoothing at all.

# Answer
> 2 votes
The normal for a vertex is generated by taking the mean of the normals for each face that contains that vertex.

As such if a mesh contains two (or more) triangles that share vertices they will be displayed with a smoothed edge.

If you use separate vertices (they can have identical positions) then they will be displayed with a hard edge.

There is some coverage of this topic on Morten Nobel's blog post on procedurally generating meshes over here.

---
Tags: unity, procedural-generation, mesh, shading
---


# Question
Title: How do I access a Unity class from an Android Activity?
I have made my own C# classes in Unity. How can I access them from the Android Activity that starts the `UnityPlayer`?

*Example*: I have a C# class called `testClass` in Unity:

```
class testClass {
    public static string myString = "test string";
}

```

From the Android activity in Java, I want to access a member of that class:

```
string str = testClass.myString;

```

Is this possible? If so, how? Is there another way to do this? In the end, I basically want to communicate between my Android activity and the UnityPlayer object.

---

**Edit**: I found a solution.

I looked at building Android plugins for Unity but this wasn't satisfactory to me.

I ended up building a socket client-server interface in Unity with C# and another one in Java for the Android app: Unity listens on port X and broadcasts on port Y. The Android activity listens on port Y and broadcasts on port X. This is necessary as both interfaces are running on the same host.

So that's how I solved my problem, but I'm open for any suggestions if anyone knows a better way of communicating between the Unityplayer and your app.

# Answer
The degree of access you are expecting may or may not be doable. However there is a simple callback function designed for sending messages from native plugins back to Unity: UnitySendMessage(). That will call the named method on the named object; in other words, you need to have an object with the desired method in the scene and then your plugin can call that. Typically most plugins create an empty object with DontDestroyOnLoad and a series of callbacks.

For example, look for that function explained on this page http://docs.unity3d.com/Manual/PluginsForIOS.html

Note that page is about iOS and not Android. However it works the same way in Android; in order to call UnitySendMessage() from Java code, you must include the Unity jar. That import is explained on this page; scroll all the way down to "Extending the UnityPlayerActivity" http://docs.unity3d.com/Manual/PluginsForAndroid.html

and another page explaining that command http://forum.unity3d.com/threads/android-plugin-call-c-from-java.78598/
> 1 votes

# Answer
If you just want to access the value of a member variable of any unity class or want to call a method of Unity class from Android activity, you can always use JNI for this. You'll need to create a C++ interface between them as well(Dunno if it can be done without C++ interface, but I believe that's required).

Check this link for a quick solution.
> 0 votes

# Answer
As far as I know, the C# classes inside Unity won't be directly accessible from outside (i.e. in your Activity). You can use the function UnitySendMessage, but it is a relatively simple function with some strict limitations on it (such as you can only send 1 parameter, and it will be a string). If you need to do something more complex, then your method of creating a localsocket connection is certainly not a bad one.

The other possibility is to send a message to the Unity app that data is available, and then have the C# code query into the Android code to get the values. For example, if you receive an in-app purchase, you can have the Android Activity signal to the C# app that there a new in-app purchase event has occurred, and then the C# code can query into the Android activity to get the results of the purchase. Generally speaking, this is how I've set up my code.
> 0 votes

---
Tags: android, unity, socket
---


# Question
Title: How can I tint a Texture2D with a gradient?
I am working on a lighting system for my game. Instead of lighting each tile completely with only one color, I want to create a gradient on that tile so to make the lighting look more dynamic and nicer.

I am using C# and Monogame (DirectX). Each tile is drawn as a `Texture2D` with this call:

```
spriteBatch.Draw(
    Block.getBlockByID(blockID).getTexture(side),
    new Rectangle(x * 28 - offx, y * 28 - offy, 28, 28),
    color
);

```

The first parameter gets the texture to use and the second one places the texture down. The third one is a pre-calculated `Color` which shades the texture that color. How can I replace that `Color` with a gradient?

# Answer
The easiest thing would be to create a gradient in Photoshop/Paint.NET/GIMP/whatever you use and blend that with your tile(s).

If you want a more procedural approach, then take a look at `Color.Lerp`. A gradient with that method is simple. The first color parameter is the light shade, the second is the final dark shade and the progress is the row/column of the texture data (depending on vertical/horizontal application of gradient) from 0 to width/height.
> 2 votes

---
Tags: c#, directx, lighting, monogame, color
---


# Question
Title: Is it bad practise to have an object for every tile?
In the game I am working on, many of my tiles must have special attributes (such as triggers when the player steps on them). I was wondering if it would be bad practise to create an object for every tile, so that I can do `map.getTile(5, 3).setWalkable(true);` (psuedocode).

The only alternative I can think of to this would be to create one instance of every tile, then just look at the properties of that type of tile, which might be okay.

Is it okay to have an object per tile?

---

I am using C++ with SFML, but I doubt that matters. I know there is a similar existing question, but it doesn't answer how to manage the tiles if they do unique things.

# Answer
> 4 votes
It is fine to have lots of instances. An instance of a class without virtual methods is just like a `POD` C `struct` in terms of memory consumption which is similar to `primitive data types`. It is no problem.

Your concern when instantiating many instances of a class are resource related I would think.

1. CPU - should not be affected because you will be instantiating whilst the level loads (so it will not affect gameplay).
2. Memory footprint - If you don't use virtual methods, it's the same as the sum of the `data types` plus a little bit of padding perhaps.

The only thing I would change, is perhaps to not use any tile for an empty tile and use a 'sparse array'. Including only the outer walls to conserve some memory and improve performance.

Another consideration you may wish to take for optimization is to use a 1-d array and getting the tile by doing something like `x + y * stageWidth` because I find that 2-d array could be a slight hindrance to performance. This is a very minor issue unless you are doing `getTile(x, y);` very often.

# Answer
> 3 votes
You need to remember that C++ is a multi-paradigmatic (OOP, functional, procedural, ..) language and you should use the programming paradigm that best solves your current issue.

OOP doesn't lend itself well to this problem. In OOP you think about single objects in isolation (concept of "a tile"). But most of your algorithms will operate on a whole collection of tiles, not a single tile.

* Find a walkable path from A to B
* Render the whole map
* Load a whole map (not load one tile N times)
* Save the whole map (not save one tile N times)
* Turn all water tiles in a radius of R into ice tiles (some magic spell for example)
* Move all actors along the map while resolving collisions

Just turning a single water tile into ice for example is a special case then. The other way around, using a function that sets a single water tile to an ice tile does not scale well at all however.

We can assume for example that most tiles on the map will not have some special script to execute (e.g. trap tiles). If you think about a single tile in isolation, then create a 2D array of tiles, every tile will have this functionality.

If you think about a whole collection of tiles instead, you can have some separate container that has the scripts to execute only for tiles that actually do require this functionality (which will probably be few in comparison).

This saves memory and performance (glampert mentioned better use of the CPU cache). It also makes your algorithms simpler and gives other advantages such as much easier and more efficient multi-threading.

OOP has its place, but in this case even people who use OOP as a silver bullet will tell you to scale it down (advice such as composition over inheritance, have a Map class but no Tile class etc).

# Answer
> 1 votes
(I cannot comment so I'm answering)

If you build an array with reference for the types of the files (I don't know much of C++, so I'll pseudocode)

```
 tiles[0,0] = ref_to_fire_tile
 tiles[0,1] = ref_to_fire_tile
 tiles[0,2] = ref_to_grass_tile
 ...

```

Where ref\_to\_\*_tile holds a reference for a specific type of tile which inherits from a generic one, this way you combine arrays, with inhiritance and use fewer objects (in my exemple for 3 tiles the user perceive, I used only 2 tile instances, so you can spare some memory).

**EDIT**

> This will allow me slightly more freedom, because it will mean that I can make something apply to a tile that's just at a location

Given that you want to use location, I'd sugest to change you code for use a Tile class (which holds the location and a reference for a tile type) and a TileType class (which is a "root" class to be specialized; it performs actions on who steps on it).

Or more easily just use the array to be your location (as if the array index itself was an instance of the Tile class I mentioned before)

# Answer
> 1 votes
I would advise against using inheritance to manage different tiles. Imagine how annoying it would be having to define a new class every time you add seemingly different types of tiles. That would result in a lot of implementations for simple things like a grass or a dirt tile. It is much simpler and more maintainable to make tiles configurable. Define a `Tile` type and derive its behavior from its data/parameters. This is a simple form of component-based design.

Having a single type/class of tile also unlocks an optimization: You no longer need to store pointers to polymorphic objects, but the objects themselves. This will result in much better data locality when processing the tiles. E.g.:

With an abstract `Tile` and N implementations, you would have to store pointers:

```
Tile * tiles[TILEMAP_SIZE];

```

Iterating the `tiles` array will result in poor CPU cache usage, since the data is scattered over the memory.

With a concrete configurable `Tile`, you can store by value and have very good data locality:

```
Tile tiles[TILEMAP_SIZE];

```

# Answer
> 0 votes
To give an example to my comment

```
    public class Tile
    {
        //some variable stuff;
        public Tile()
        {
            //some constructor stuff;
        }
    }

    public class FireTile
    {
        //some variable stuff;
        public FireTile : Tile()
        {
            //sets player on fire
            //some constructor stuff
        }
    }

```

And then

```
 if(player steps on fireTile)
      set player on fire;

```

---
Tags: c++, 2d, architecture, platformer, sfml
---


# Question
Title: Edit spawn location according to vector direction
I'm trying to make a turret in Bukkit (Java). This will shoot an arrow to the players that are in the shooting radius. But now I've a little problem, the arrow gets stuck inside the block where its spawned. Now I'm trying to spawn the arrow at the side of that block so it wont get stuck anymore, but I don't know how to calculate the best side of the block to set the new spawn location. Like North, East, South or West of the block.

So is there someone who can help me with this? Thnx!

Code that I use for now:

```
Vector v = pl.getLocation().add(0, 2, 0).toVector().subtract(loc.toVector());
Arrow arrow = (Arrow) Bukkit.getWorld(loc.getWorld().getName()).spawnArrow(loc, v, (float) 4, t.getAccuracy());

```

So the variable loc needs to be recalculated so it will be outside the block to the right direction from the vector 'v'.

# Answer
> 1 votes
Ex-Bukkit dev here. Not sure if you still want this with the whole bukkit situation...

Really, the only thing to do here is use some tricky packets, to make it not collide, or simply offset the y of where you spawn in up one. You could even use trig to see whee the arrow would fly, and spawn it one block in that direction.

Easiest would be to simply offset it's y coord.

---
Tags: java, vector, bukkit
---


title: Getting more particles in engine

text:
# Question
Title: Getting more particles in engine
I followed rbwhitakers tutorial on making a particle engine and I'm wondering how to get more particles on the screen. I was thinking that the "total" variable would do it but it doesnt. Is this something I'm doing wrong in the method or a hardware problem?

```
private Particle GenerateNewParticle()
    {
        Texture2D texture = textures[random.Next(textures.Count)];
        Vector2 position = EmitterLocation;
        Vector2 velocity = new Vector2(0, 10);
        float angle = 0;
        float angularVelocity = 0;
        Color color = Color.LightSkyBlue;
        float size = (float)random.NextDouble();
        int ttl = 100;

        return new Particle(texture, position, velocity, angle, angularVelocity, color, size, ttl);
    }

    public void Update()
    {
        int total = 100;

        for (int i = 0; i < total; i++)
        {
            particles.Add(GenerateNewParticle());
        }

        for (int particle = 0; particle < particles.Count; particle++)
        {
            particles[particle].Update();
            if (particles[particle].TTL <= 0 || particles[particle].Position.Y > 550)
            {
                particles.RemoveAt(particle);
                particle--;
            }
        }
    }

```

Im creating rain but I want it to be really heavy rain. Right now it just looks like a heavy sprinkle...I guess I would call it.

```
            particleEngine.EmitterLocation = new Vector2((float)rand.NextDouble() * (graphics.GraphicsDevice.Viewport.Width), 0);

```

# Answer
> 2 votes
```
    for (int i = 0; i < total; i++)
    {
        particles.Add(GenerateNewParticle());
    }

```

This is being called once per particleEngine.EmitterLocation assignment. This means you're creating 100 particles in the same location every frame.

Try this:

```
    for (int i = 0; i < total; i++)
    {
        particles.Add(GenerateNewParticle());
        EmitterLocation = new Vector2((float)rand.NextDouble() * (graphics.GraphicsDevice.Viewport.Width), 0);
    }

```

You may need to make graphics.GraphicsDevice.Viewport.Width available in this scope somehow.

---
Tags: xna, particles
---


title: Beginner: How do I calculate a vector?

text:
# Question
Title: Beginner: How do I calculate a vector?
I am trying to wrap my head around some concepts in a side project I'm working on. I'm struggling with how I can calculate a vector based on my character movement logic. Here are the relevant details of my character movement:

1. The character's hit box for collisions (and map position validity) is defined as a rectangle: x,y,w,h
2. A character can move in 8 directions, let's keep this simple to ignore strafing, call this `direction`:

* Left`(x-1)`, Right`(x+1)`, Up`(y-1)`, Down`(y+1)`
    * UpLeft`(x-1,y-1)`, UpRight`(x+1,y-1)`,DownLeft `(x-1,y+1)`, DownRight`(x+1,y+1)`
3. The character can be in two moving states, again keeping numbers simple:

* Walking `1 x offsets`
    * Running `2 x offsets`
4. When a character is moved the following logic happens:

* Create their proposed new hit box by adding an offset to their x & y coordinates based on their `direction`, call this `proposedHitBox`
    * Check if the `proposedHitBox` is a valid position on the map, if so, then update the character's position to the location defined on the `proposedHitBox`
    * If the `proposedHitBox` is not a valid location on the map it should try to glance the character. This is where I'm having trouble.

Given all this, how do I essentially, calculate a vector of their proposed motion?

Example:

1. Character is at 10,10.
2. Character starts running.
3. Input is `DownLeft`.
4. Proposed location is 8,12 `(x-(1x2),y+(1x2))`.
5. Proposed location is valid.
6. Update character position to 8,12.
7. What calculation defines my vector? How does magnitude come from this? Is that generally stored as Z in a 2D game? So I'd use a Vector3 to store it? How does velocity come into this?

I'd assume my vector is a 45deg angle from current to proposed...?

**Edit**

Here is a picture of what the walls can look like in the game. The red box being the hit box as discussed above. The character is bound inside the blue polygon (which represents outer walls). Black being inner walls. The way I was doing glancing was overlaying 4x4 tiles across this entire map and then for each tile that the character should glance on I would choose an incoming `direction` (i.e. `DownLeft`) and then redirect them to a different `direction` (i.e. `Down`) which should make the proposed hit box in a valid position. This is however very tedious as I have to create glances for multiple directions for every tile. I'm looking for hopefully a better way.

I was reading that you could add vectors to each tile but I'm not sure how this works because on some tiles a incoming `direction` does not always have the same out `direction`.

# Answer
> 5 votes
You're on the right track. I would start by determining the player's direction based on the keyboard state:

```
direction = Vector(0, 0)
if up pressed:
    direction = direction + Vector(0, -1)
if down pressed:
    direction = direction + Vector(0, 1)
if left pressed:
    direction = direction + Vector(-1, 0)
if right pressed:
    direction = direction + Vector(1, 0)

```

Then, multiply by the player's speed to get the velocity vector (or motion vector, as you say):

```
if running:
    speed = 2
else:
    speed = 1
velocity = speed * direction

```

So, the proposed location is

```
proposed location = current location + velocity

```

As you say, if the proposed location is valid, it becomes the current location. If not, the easiest thing to do is to not move the player at all. But you probably want the player to slide against walls...

## Sliding

If your walls are axis-aligned, we can just add two cases, one for sliding horizontally and one for sliding vertically:

```
if (proposed x, proposed y) is a valid location:
    location = (proposed x, proposed y)
if (proposed x, current y) is a valid location:
    location = (proposed x, current y)
if (current x, proposed y) is a valid location:
    location = (current x, proposed y)

```

If your walls are not axis-aligned, sliding becomes somewhat more complex. We first need to determine which wall the player is facing. Now, we can think of the velocity vector as having two components: one which points into the wall, and one which moves sideways along the wall. We need to remove the component which points into the wall, so that we're left with a "sideways" motion vector.

The velocity component which points into the wall is the velocity vector's projection onto the wall's normal vector. We can compute this as

```
(v dot n / magnitude(n)^2) n

```

where `v` is the velocity vector and `n` is the wall's normal vector. If `n` is already normalized, this simplifies to

```
(v dot n) n

```

Now, subtract this from the original velocity to get the "sideways" component of velocity, which we can add to our location without running into the current wall. We should still check that this new proposed location is valid before accepting it, in case we run into a different wall.

## Demo

I put together a JSFiddle to demonstrate. The logic for sliding against walls is in `updatePosition`.

---
Tags: 2d, movement, vector, rpg
---


# Question
Title: Why does my modern OpenGL heightmap render as line segments instead of faces?
I'm brand new to OpenGL and have been trying my hand modern openGL. A few days ago, I tried to create some terrain by using a heightmap stored in a grayscale 32-bit BMP. I am using SDL 2.0, GLEW and OpenGL 3.3.

So, I wrote the following height map loading function:

```
bool terrain::loadHeightMap( const char* path ) {
Uint32 start = SDL_GetTicks(); // track the start time for performance testing

/* Load the heights from file */
std::cout << "Loading heightmap '" << path << "'..." << std::endl;
SDL_Surface* img = SDL_LoadBMP( path );
if( !img ) {
    std::cout << "Failed to load heightmap: " << path << ". SDL Error: " << SDL_GetError() << std::endl;
    return false;
}

// get the width and the height of the terrain
width = img->w;
height = img->h;

// get the bytes per pixel to verify that it is a 32-bit BMP file
int bpp = img->format->BytesPerPixel;
if( bpp != 4 ) {
    std::cout << "Could not load heightmap " << path << ". BMP is not 32-bit." << std::endl;
    return false;
}

// stores the vector for the current row.
std::vector<float> temp;

Uint8 g,b; // junk values, which we need for the SDL_GetRGB() below. We define them here so that they do not need to be re-defined on each loop.

for( int y=0;y<height;y++ ) {
    for( int x=0;x<width;x++ ) {
        /* Here p is the address to the pixel we want to retrieve */
        Uint8 *p = (Uint8 *)img->pixels + y * img->pitch + x * bpp;
        Uint8 r;
        SDL_GetRGB( *(Uint32 *)p,img->format,&r,&g,&b); // get the red pixel data
        temp.push_back( (float)r/255 );
    }
    heightMap.push_back( temp );
    temp.clear();
}

SDL_FreeSurface( img );

/* In order to give the vertices to openGL we need to create a vector */
std::vector< glm::vec3 > vertices;
for( int y=0;y<height;y++ ) {
    for( int x=0;x<width;x++ ) {
        vertices.push_back( glm::vec3( y,heightMap[x][y],x ) );
    }
}

/* Pass the data to openGL */
glGenVertexArrays( 1,&vertexArrayID );
glBindVertexArray( vertexArrayID );

glGenBuffers( 1,&vertexBufferID );
glBindBuffer( GL_ARRAY_BUFFER,vertexBufferID );
glBufferData( GL_ARRAY_BUFFER,vertices.size()*sizeof(glm::vec3),&vertices[0],GL_STATIC_DRAW );

/* Compute normals */

std::cout << "Successfully loaded heightmap in " << SDL_GetTicks()-start << " ms." << std::endl;

return true;

```

}

I then used the following rendering code to render it:

```
/* Compute the model, view, projection and MVP matrices */
glm::mat4 Projection = glm::perspective( 60.0f,80.0f,0.01f,1000.0f );
glm::mat4 View = cam->getMatrix(); // view matrix
glm::mat4 Model = glm::mat4(1.0f); // model matrix
glm::mat4 MVP = Projection * View * Model; // Model-View-Projection matrix

glUniformMatrix4fv( matrixID,1,GL_FALSE,&MVP[0][0] ); // set the MVP matrix as the current active matrix

glUseProgram( shaderID ); // set the terrain shader to the current shader

/* First attribute buffer : vertices */
glEnableVertexAttribArray( 0 );
glBindBuffer( GL_ARRAY_BUFFER,vertexBufferID );
glVertexAttribPointer(
    0,                  // attribute 0. No particular reason for 0, but must match the layout in the shader.
    3,                  // size
    GL_FLOAT,           // type
    GL_FALSE,           // normalized?
    0,                  // stride
    (void*)0            // array buffer offset
);

/* Render the terrain mesh */
glDrawArrays( GL_TRIANGLES,0,width*height );

glDisableVertexAttribArray(0);

```

However when I render it and move around with my camera I get strange line formations instead of filled in surfaces... The height map is correct as when I move around I can see the relief I loaded in the BMP file, but no faces! Could this be because I should be using something other than GL\_TRIANGLES in the glDrawArrays() function?

Here is my vertex shader:

```
#version 330 core

// Input vertex data, different for all executions of this shader.
layout(location = 0) in vec3 vertexPosition_modelspace;

out vec2 UV;

// Values that stay constant for the whole mesh.
uniform mat4 MVP;

void main(){
// Output position of the vertex, in clip space : MVP * position
vec4 v = vec4(vertexPosition_modelspace,1); // Transform an homogeneous 4D vector,     remember ?
gl_Position = MVP * v;
}

```

Here is my fragment shader:

```
#version 330 core

// Ouput data
out vec3 color;

void main(){
    color = vec3(0,1,0);
}

```

Any suggestions would be appreciated :)

# Answer
> 0 votes
You can't just generate the points in a grid and hope OpenGL figures our what you want. When you use `glDrawArrays` you need to pass the whole triangles (or whatever primitive you're drawing) to it. So either change your loop to:

```
for( int y=0;y<height-1;y++ ) {
    for( int x=0;x<width-1;x++ ) {
        vertices.push_back( glm::vec3( y,heightMap[x][y],x ) );
        vertices.push_back( glm::vec3( y+1,heightMap[x][y+1],x ) );
        vertices.push_back( glm::vec3( y+1,heightMap[x+1][y+1],x+1 ) );

        vertices.push_back( glm::vec3( y,heightMap[x][y],x ) );
        vertices.push_back( glm::vec3( y+1,heightMap[x+1][y+1],x+1 ) );
        vertices.push_back( glm::vec3( y,heightMap[x+1][y],x+1 ) );
    }
}

```

Obviously you also need to set `glDrawArrays` to `glDrawArrays( GL_TRIANGLES,0,(width-1)*(height-1)*6 );`. Of course you can make it a lot more efficient if you use `GL_TRIANGLE_STRIP` but I just thought I'd give you the minimal amount of things to change first.

Or you can add an index buffer and use `glDrawElements` or the like

---
Tags: opengl, sdl, heightmap, sdl2
---


# Question
Title: How to remove the old sprites in pygame and show them at a different location
I am trying to show the motion of some basketballs towards walle using the pygae sprites. The idea is that I don't know how to remove the old ones so they won't show. Is there a move method so that it would know it has to draw it again at the specified location? I created a sprite class. Then I have a Character class that uses the sprite class and threads to calculate the intermediary coordinates for them. But I don't want them to show on the screen forever, like the pictures show. Thanks!

```
 import pygame

 class CharacterSprite(pygame.sprite.Sprite):

   def __init__(self, location, image, surface):
       pygame.sprite.Sprite.__init__(self)
       self.image = pygame.image.load(image).convert_alpha()
       self.rect = self.image.get_rect()
       self.rect.center = location
       self.surface = surface

    def draw(self):
       self.surface.blit(self.image, self.rect)

   def update(self, location):
      self.rect.center = location
      self.draw()

import threading
import pygame
import os
from random import randint
from Sprites.CharacterSprite import CharacterSprite

LOCK = threading.Lock()

class StudentCharacter(threading.Thread):
   NRSTEPS = 3
   YPOS = 440
   TEACHERPOS = 40
   IMAGE_PATH = os.path.join('images', 'ball.png')

def __init__(self, screen, xpos, interval):
    threading.Thread.__init__(self)
    self.screen, self.xpos, self.ypos, self.interval = screen, xpos, self.YPOS, interval
    self.draw(self.xpos, self.ypos)
    self.configure()

def draw(self, x, y):
    self.circle = CharacterSprite([x, y], self.IMAGE_PATH, self.screen)
    self.circle.draw()

def configure(self):
    (left, right) = self.interval
    self.target = randint(left, right)
    xdif = self.target - self.xpos
    ydif = self.TEACHERPOS - self.ypos
    self.normal = {'x': int(xdif / self.NRSTEPS), 'y': int(ydif / self.NRSTEPS)}
    print self.target, self.normal['x'], self.normal['y']

def update(self):
    self.circle.update([self.xpos, self.ypos])

def run(self):
    i = 0
    while i < self.NRSTEPS:
        LOCK.acquire()
        pygame.time.wait(100)
        self.xpos += self.normal['x']
        self.ypos += self.normal['y']
        self.update()
        print self.xpos, self.ypos
        pygame.display.update()
        i += 1
        LOCK.release()
    print "Done"

```

# Answer
> 4 votes
Yes, thats called *dirty blitting*. The *Newbie Guide to pygame* touches on this.

The steps they recommend to implement it are:

1. Blit a piece of the background over the sprite’s current location, erasing it.
2. Append the sprite’s current location rectangle to a list called `dirty_rects`.
3. Move the sprite. Draw the sprite at it’s new location.
4. Append the sprite’s new location to my `dirty_rects` list. Call `display.update(dirty_rects)`

---
Tags: sprites, pygame
---


title: GLSL: Vertex attribute to int

text:
# Question
Title: GLSL: Vertex attribute to int
I'm trying to write a shader which renders a multitextured geometry wihout rerendering the geometry with each texture.

In my test I'm not using textures, I just convert the texture index to a color (0: red, 1: blue, 2: green). I'm rendering 3 planes with 3 different "texture index" attributes. The vertex shader just passes that float to the fragment shader where I convert it to an integer (and use this interger as an array indexer in the main shader).

So a vertex consists 4 floats (0-2: position, 3: texture index). Everything is fine until I'm trying to use that "texture index".

Here's the VertexShader:

```
#version 130
uniform mat4 proj;
uniform mat4 view;
uniform mat4 world;

in vec3 in_position;
in float in_fl;

smooth out float FL;

void main(void)
{
    FL = in_fl;

    gl_Position = proj * view * world * vec4(in_position, 1);
}

```

FragmentShader:

```
#version 130

out vec4 out_frag_color;
smooth in float FL;

void main(void)
{
    int i = int(FL);

    if(i == 0)
        out_frag_color = vec4(1,0,0,1);
    else if(i == 1)
        out_frag_color = vec4(0,0,1,1);
    else if(i == 2)
        out_frag_color = vec4(0,1,0,1);
    else
        out_frag_color = vec4(1,1,1,1);
}

```

And the result (the numbers are the "texture index" of the plane): Tested on an Intel HD 4000 GPU and an nVidia GTS 250, same result. As you can see 0 is OK, but 2.0 is sometimes 2 (green), sometimes 1 (blue), why? If I pass that "i" to a sampler2D array, nothing shows up on the screen, because "i" is out of the array bounds.

The rendering is done using OpenGL 3.0, with a VAO, an ArrayBuffer and an ElementArrayBuffer.

This is how I setup the attrib pointers:

```
GL.EnableVertexAttribArray(0); //pos
GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, true, sizeof(float) * 4, 0);

GL.EnableVertexAttribArray(1); //tetxure index
GL.VertexAttribPointer(1, 1, VertexAttribPointerType.Float, true, sizeof(float) * 4, sizeof(float) * 3);

```

I've tried using VertexAttribPointerType.Int and int attributes, Also I've tried setting the "FL" varaible in the vertex shader, with 0, the result is red which is good, but if I use 1 or 2 the result is again a mess.

So what do you think? It's a rounding problem? Or how should I render the geometry with multiple textures wihout rerendering the geometry with each texture?

# Answer
I managed to find out what my problem was. The "smooth" keyword.

Vertex shader:

```
...
in float in_fl;

flat out int FL;

void main(void)
{
    FL = int(in_fl);
...

```

Fragment shader:

```
...
    flat in int FL;
...

```

So now I have a red, a blue and a green square, as I wanted.

Anyway thanks for any help.
> 3 votes

---
Tags: c#, opengl, shaders, glsl, opentk
---


title: Swarm Algorithms

text:
# Question
Title: Swarm Algorithms
I have been asked to deliver a presentation for my university course on ant, bee and particle swarm algorithms. Therefore I am attempting to learn more about swarm algorithms and their uses within games. What I am looking for are presentations and articles which would help me to get a better grasp of the subject matter. As well as this video demonstrations of swarm algorithms used within games. Any help in finding relevant and up to date material would be appreciated.

# Answer
> 4 votes
Flocking behaviors is the way to go. This link gives a great explanation on how to code flocking in really any game engine.

---
Tags: algorithm, ai, optimization
---


# Question
Title: Creating a Player object in a physics engine
I have a working physics environment using Farseer - but how do I create a player object that can walk around?

My current attempt involves applying forces to a rectangular body whenever keys are pressed.

This... works... to some degree. The player box moves around and such, after significant angle damping doesn't flip over much either. But I want a smooth moving simple player that can walk around and climb slopes but not walls and stuff like that. As it currently stands, the player object can climb any slope no matter how steep due to continue sideways force being applied. The player also does not stop quickly, but rather slides heavily due to low friction - and raising the player body's friction value doesn't help all that much.

I just don't know how to do a standard player object without making it move around in ridiculous ways due to the physics engine being a full physics engine.

# Answer
> 0 votes
I've already got a pretty reasonable answer to this over here, with some video examples.

The short version is: You cannot reasonably use rigid body physics to simulate biped locomotion in the kind of responsive way you'd want for a platformer. You have to do something else.

---
Tags: c#, box2d, physics, farseer-physics-engine
---


title: Can't figure out projection transform

text:
# Question
Title: Can't figure out projection transform
I'm trying to fugure out all the spaces transformations, and currently have some inconsistency I can't understand. I'm working on a 2D game (so we assuming `Z` is always 0 for now), on a device with 960x544 resolution. So, as far as I understand my `World Space` is left-top `(0, 0)` to right-bottom `(959, 543)`, with `Y` axis inverted (going down). Let `w = 960`, `h = 544`. To transform it to `Eye Space` we need to move `(0, 0)` to center of the screen, so it would be simple translation, `viewT`:

```
1, 0, 0, -w/2
0, 1, 0, -h/2
0, 0, 1, 0
0, 0, 0, 1

```

Next step is `Clip Space`. I want all world space to be rendered so it's just scaling. But we also need to invert `Y` axis and that's the part I'm unsure of. My assumption would be that we just add minus sign for the `Y` scale, and thus `projT`:

```
2/w, 0, 0, 0
0, -2/h, 0, 0
0, 0, 1, 0
0, 0, 0, 1

```

Then `viewProjT = projT * viewT` would give me:

```
2/w, 0, 0, -1
0, -2/h, 0, 1
0, 0, 1, 0
0, 0, 0, 1

```

But in samples I have, "reference" matrix is:

```
2/w, 0, 0, 0
0, -2/h, 0, 0
0, 0, 1, 0
-1, 1, 0, 1

```

i.e. it's my `viewProjT`, but transposed. And that's the part I don't understand. Can someone clarify why I need to transpose matrix to get correct matrix? Is this somehow related to inverting `Y` axis?

Note: I'm using this, as a basis for my calculations. And image to illustrate my World and Clip spaces:

# Answer
Found answer myself. Long story short, it all depends on assumptions on both how matrices are applied to points (`row vector` or `column vector`) and how matrices are stored in memory (`row major` or `column major`). These differ for DirectX and OpenGL, there DX usually uses row vector and row major matrices, and OpenGL the other types. But in both cases, due to double "error" compensation, given *mathematical matrix* (i.e. we not assuming any memory layout here, just indices):

```
m11 m12 m13 m14
m21 m22 m23 m24
m31 m32 m33 m34
m41 m42 m43 m44

```

translations will always be in array indices 12, 13 and 14. So for DirectX (row major) this will map to `m41, m42, m43` and for OpenGL (column major) to `m14, m24, m34`. For more details on subject see here.

AFAIU in my calculations I used column vector assumption (and indeed, if I apply my transformation matrix to column vector I get correct results). But in fact my system uses (relatively of course, which system to use is a user's choice, but I just want to stick with existing samples) row vectors, so I need to either change assumption in calculations or just transpose final matrix.
> 1 votes

---
Tags: transformation, psm
---


# Question
Title: "Game Property Values" for online game on Database or somewhere else?
I'm working on a online game but, what would be the best way to store values like damage,movespeed,turnrate, and so on.. ?

My answer would be, to store them in a Database, so they can easily be changed by any developer and are "unreachable" for the useres, or are there better ways to do that?

# Answer
There are different options to consider. Which one you pick depends on your requirements and preference.

## Hardcoded values

You just put all the values right into your sourcecode.

This is the easiest solution for the programmer because no code is needed to read these values from a file or database. Unfortunately it is a real maintainance nightmare, because only a programmer can change the values and each change requires to recompile the binary.

This solution is only recommendable for very small games or during the prototyping stage.

## Put the values in a file

You store the values in one or more file in JSON, XML, CSV or some other format. When the server starts, it reads the file and loads all the values from it. When you do it well, you can even design your server in a way that it can reload and apply the files without having to restart.

Maintainers can then edit these files with any text editor without having to change the sourcecode. You also have the option to develop a GUI-based tool to edit these files, when you feel that it is worth the effort.

Another advantage of files is that any files which are needed by both the server and the client can be easily shared between server and clients through your usual asset distribution process.

## Put the values in a database

You need a database anyway for storing all your dynamic data, so putting your static data there seems like an obvious solution.

The advantage is that databases are built for having multiple users work with them at the same time. That means your maintainers can work in parallel without edit conflicts. When you would use files, multiple users would not be able to edit the same file at the same time.

However, there are some drawbacks to databases: Editing a live SQL database (or some noSQL solution, when you swing that way) can not be done with a text editor. Your maintainers either need to know SQL (which is a really inconvenient way to do data entry) or they need a GUI tool. There are general-purpose GUI tools available for SQL databases which make this a bit more convenient than a SQL shell, but are still not as intuitive as a simple text editor. That means you likely won't get around writing your own GUI tool for maintaining your data.

Another drawback of databases is that they usually can not be versioned. A text file can be put under version control, so you have a change history. But with a SQL database, you can't do this. You would have to implement your own versioning feature in your GUI application.
> 1 votes

# Answer
I personally think these values are best stored inside a text file in plain text. There is nothing easier to read an edit. Each class (game character class like Fighter, Mage and so) could have it's own text file and every monster as well. It keeps things manageable and accessible to none programmers. JSON is great until a confused none programmer erases a `{` by accident or misses a `'` that is needed for a string.

A plain text with comments like this:

```
# Fighter class configuration
name: Fighter
# This affects damage output
attack: 12
.
.
.

```
> 1 votes

---
Tags: databases, online
---


# Question
Title: Shader - Calculate depth relative to Object
I am trying to calculate **depth** relative to the **object**.
Here is a good solution to retrieve **depth** relative to **camera** : Depth as distance to camera plane in GLSL

```
varying float distToCamera;

void main()
{
    vec4 cs_position = glModelViewMatrix * gl_Vertex;
    distToCamera = -cs_position.z;
    gl_Position = gl_ProjectionMatrix * cs_position;
}

```

With this example the depth is relative to the **camera**.
But I would like get the depth relative to the object. I would like the same depth and value if I am near from the object or if I am far.

Here is an example of what I am trying to achieve. On the left you can see that the depth is relative to the camera. And on the right even if the camera moves back from the object, the depth remains the same because it is dependant to the object.

# Answer
What you essentially want is the depth in camera coordinates, but relative to model, not camera. the easiest way to achieve that is to calculate the position of the origin of a model coordinate system in camera coordinates.

```
...
vec4 cs_position = glModelViewMatrix * gl_Vertex;
vec4 origin_position = glModelViewMatrix * vec4(0,0,0,1);
distToOrigin = origin_position.z - cs_position.z;
...

```
> 2 votes

# Answer
* calculate a bounding volume of the object (sphere, convex hull, box - depends on your speed/accuracy needs), this needs to be done only once - at initalization
* while rendering, for each object:
    + transform camera (origin, direction) to object space
    + project bounding volume on camera direction axis and subtract camera origin projection to retrieve min/max distance
    + calculate local distance in the shader: `d_local = (d_world - min) / (max - min)`

This solution may not be completely accurate with all volume types (expect pixels not reaching limits at all times for bounding spheres/boxes) but it should be fast enough for dynamic objects.

There's also the issue of never reaching the maximum distance in case of overlap but to fix that, serious resources would have to be spent on this (double rendering, clearing buffers between renders etc.) so for whatever you're doing, there should be a better way if you feel this might be an important issue to solve.
> 1 votes

---
Tags: opengl, shaders, directx, glsl, hlsl
---


# Question
Title: How do I procedurally create a directional light cone with an HTML canvas?
To create a directional light effect, I want to draw this kind of transparency mask on an HTML canvas (using context2d):

I also want to be able to generate such a mask dynamically. I've tried using `arc` to create this kind of light cone, but I'm not able to draw nice, smooth and naturally looking light.

How can I do this?

# Answer
> 1 votes
When you want a really advanced light engine where objects create shadows, you should look into WebGL and use a 3d engine.

But when you don't need accurate shading and only want objects to create cones of light which illuminate the canvas without respect to content, this is what you could do.

1. Have two canvases, the normal scene and a second background canvas
2. Draw your scene with normal illumination on the front canvas
3. Fill the second canvas all black, and then draw the lights on them.
4. Draw the lightmap to the game scene using globalCompositeOperation = "multiply"

Areas which are all black on the lightmap will also be black in the final output (dark). Areas which are pure white, will be drawn the way they were originally on the input bitmap (bright). Any shades in between will be in twilight. You can also use colors in your lightmap.

Here is a jsfiddle demo:

http://jsfiddle.net/1odkyj42/2/

A word of warning, though: It doesn't work in Internet Explorer because MSIE doesn't support the multiply composite operation yet (even in Version 11). There are workarounds for that, but that's a different topic for a different questions.

---
Tags: html5, lighting, html-canvas, transparency, masking
---


# Question
Title: What is the advantage of 6 Directional Movement vs, for instance, 8 or 4
I'm making a fallout 2 inspired game and I'm wondering what you guys think about its use of 6 directional movement. It kind of bugs me for some reason and seems like it would make game play odd and programming it would be more difficult than 8 directional movement it seems.

Any thoughts?

# Answer
> 2 votes
Hexagons as a grid type are not uncommon in games, particularly games involving tactical elements.

In a 4-way movement scheme, in order to move diagonally you have to expend two moves. In a 8-way movement scheme, you either have to make the diagonal moves have a cost of two, one, or a fractional sqrt(2) cost in resources.

Hexagonal grids allow movement along three axes with equal cost, which lessens the impact of which way the grid is laid out.

Programming with hexagonal grids is not hard. You store staggered rows of the grid and indexing is very cheap.

---
Tags: c++, game-design
---


# Question
Title: Get Facebook Picture in Cocos2d-iphone V3
I'm trying to get the profile picture from Facebook, but I'm getting the following error:

```
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIImage stringByStandardizingPath]:

```

This is my code:

```
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://graph.facebook.com/%@/picture?type=square", userid]];
 NSData *data = [NSData dataWithContentsOfURL:url];
 UIImage *image = [UIImage imageWithData:data];
 //convert UIImage to CCSprite
 CCTexture *texture = [CCTexture textureWithFile:image];
 CCSprite *sprite = [CCSprite spriteWithTexture:texture];
 sprite.position = ccp(winWidth*.5, winHeight*.5);

```

The error occurs in the UIImage \*image line.

# Answer
> 1 votes
That error occurs on this line:

```
CCTexture *texture = [CCTexture textureWithFile:image];

```

And this is the right way to do this:

```
CCTexture *texture = [[CCTexture alloc] initWithCGImage:image.CGImage
                                                   contentScale:image.scale];

```

---
Tags: software-engineering, cocos2d-iphone, cocos2d, facebook
---


# Question
Title: How do I fairly distribute new powerful cards to players in a collectible card game?
I'm writing a game in which users start with a few cards. They use those cards to play against other players. The winner can steal a card from the other player.

The aim is to get more/different/rare/higher-powered cards.

If everyone starts with 10 low-powered cards, how would anyone ever get higher powered cards? They'd just be playing against people who have the same type of cards as them.

How do you fairly distribute these more powerful cards among players?

# Answer
> 17 votes
Some suggestions to bring more cards into the game:

* When a player wins a match, reward them with two cards: One from the losers deck and one newly created one. You might also consider giving a generated card to the loser to compensate for the loss, otherwise they would progress backwards, which is a real motivation breaker.
* Reward players for playing by giving them some kind of resource after every match, and allow them to buy better cards with said resource.
* Allow players to buy better cards with micro transactions.
* Have a mechanic to convert multiple low-powered cards into one random card of the next higher tier - that way you ensure that players always have some use for trash cards they don't want to play with.
* Allow players to earn new cards through actions *during* the match (however, make sure that winning the match is still important, or players will concentrate on earning cards, not on winning the match).
* When you want to keep the stealing mechanic as the primary source of cards, allow the players to play against AI bots with better cards (the AI bots should not lose cards - when they lose a match, the earned card is duplicated).

Regarding fairness: When long-time players do not just have an advantage because of their experience but also because they have access to far superior cards, it will be very hard to gain any new players after a while. They won't just lose because of their inexperience but also because the game is stacked against them. This will cause many newbies to be frustrated and leave. To avoid this, you can do this:

* A good matchmaking system which matches players against each other which have a similar deck strength
* Avoid cards which are "just better" than others. A skilled player with basic cards should be able to beat a bad player with advanced cards. You can do this by making sure that cards which are numerically stronger have some kind of drawback or specialization, so that the more advanced cards are rather tradeoffs than upgrades.

---
Tags: game-design, balance, card-game, economy
---


title: How to handle tiles on top of players

text:
# Question
Title: How to handle tiles on top of players
I am creating an 2d bird view tile game using the pixijs render framework. Like pokemon or oldtime zelda.

In those games you sometimes walk behind buildings where the tile would be drawn on top of the player.

I am using an multidimensional array for each tile properties. Where you can set ground level images and level on top of ground level images.

The 'z-index' can be changed.

Should I create an new property to flag it as an tile that can be on top of the player? Where all those tiles with that property are drawn on top of the player. But there is an possibility that you can climb/walk on the building and the player should than be drawn on top of the tiles.

You should take the following into consideration

* the game is an multiplayer game.

This could be an conflict if all the players/characters (the player,npc, cpu) are one layer and the tiles that can be drawn on top of the player are one layer. Because for example: one player is walking on top of the building and one is behind the building. You cant change the z-index of the player one lower. Because the player behind the building wil look like he is on top of it because the player is drawn on top of it by the changed z-index.

* you can be drawn on top of the tile level (like walking om top of the building or mountain)
* tiles can change (a building that is going to be destroyed for example) thus are not fixed

So how can I handle tiles on top of a player which can be also beneath one player but not the other?

# Answer
Draw all your tiles AND your sprites in the correct order:

* z-index from bottom to toplevel
* y-index from upper side to downside of screen
* x-index from left to right

Note: The characters and tiles must be drawn in the same loop. That means a tile left, below or under the character must always drawn before the character.

You should also determine if the player is -within- a building and possibly not draw anything that is in the level above the player. So you can still see the player moving inside the building. This can be achieved by marking special tile types for the floor inside of buildings (= saves memory). If the player is now located at a special position you use the type of tile below to determine, if your player is within a building. If so, you only display tiles up to the current z-index of the players position. Alternatively, you can store this information on each map position (= needs more memory).

**Some example code:**

```
// X=0 is west end, X=MAXX-1 is east end
// Y=0 is north end, Y=MAXY-1 is south end
// Z=0 is downside, Z=MAXZ-1 is upside
#define MAXX 128
#define MAXY 128
#define MAXZ 4

// map stores tile ids for each
// position in pseudo-3d space
// 0 == no tile
// Actors Images are stored as tiles,
// so they get drawn at correct z-index
int map[MAXX][MAXY][MAXZ];

// All indoor tiles get an index >= 128
bool isIndoor(int tileid) {
  return (tileid >= 128); // return true
}

void drawTile(int rx, int ry, int z, int tileid) {
  // calculate isometric tile position on screen
  int screen_x = center_tile_x + rx*tile_size_x - z*z_shift_x;
  int screen_y = center_tile_y + ry*tile_size_y - z*z_shift_y;

  drawImage(screen_x, screen_y, tile_gfx[tileid]);
}

// we have max 15x15 tiles on screen
// 7 tiles north, west, east and south
// from tile in screen center...
int max_visible_dist_x = 7;
int max_visible_dist_y = 7;

// Function drawView draws Viewport
// having map coordinates x,y,z
// in the middle of the screen.
void drawView(int x, int y, int z) {
  int maxz;
  // if tile below current viewpoint center is an indoor tile
  // draw upto current "z" position only
  if (isIndoor(map[x][y][z-1])) maxz = z; else maxz = MAXZ;

  for(int z=0; z<maxz; ++z) {
    for(int ry=-max_visible_dist_y; ry<=max_visible_dist_y; ++ry) {
      for(int rx=max_visible_dist_x; rx<=max_visible_dist_x; ++rx) {
        int tileid = map[rx+x][ry+y][z];
        if (tileid != 0) drawTile(rx, ry, z, tileid);
        // Note: Actors gets drawn as tile too!
        // If not: check each coordinate rx+x, ry+y, z
        // for identity with actor positions and
        // call draw function when matching!
      }
    }
  }
}

```
> 1 votes

# Answer
The solution is simple: draw all the tiles (and anything inside them, such as players) in **top-down row order**. You could of course do the same using z-index - anything on tile row X will have z-index greater than tile row X - 1.

I believe your conundrum is due to drawing all tiles first, then all players. I suspect you also simply use the Y coordinate as the z-index. This is reasonable if there is no elevation in your game, but as you've found, it causes issues when you have elevated tiles. Instead, you should draw tiles and their contents together, in top-down order or by doing the same using z-index.
> 3 votes

# Answer
You can render the real-world tile depth to the z-buffer. When you render your characters, you can simply cull the pixels that fail the z-depth test, i.e. a tile closer to the camera is occluding the character.

For pure opaque/transparent tiles, the advantage is that you can do this per pixel, i.e. no sorting of tiles is necessary. If your tile graphics contain alpha, you can use that so that opaque parts have the depth rendered to the z-buffer, and (fully) transparent parts do not. Works for very basic tiles.

For tiles with alpha's strictly between 0 and 1, you still need to z-sort these with your characters, and quite possibly, this will still not be correct unless you resort to depth-peeling and other more advanced techniques.
> 1 votes

---
Tags: tilemap, depth
---


title: using delta timing is causing shake

text:
# Question
Title: using delta timing is causing shake
I am using delta timing to account for potential drop in frame rate. Only trouble being when I do this, I can notice an ever so slight wobble. I checked out the following JSFiddle coming from a tutorial on the subject and I can even see the wobble there, specifically on the 30fps example. http://jsfiddle.net/straker/bLBjn/

my code is:

```
var delta = {
    now: 0,
    last: 0,
    difference:0,
    time: 1000/60
}

var d = function(val){
    return val/delta.time * delta.difference;
}

```

Then further down at the game loop

```
delta.last = Date.now();
animate();
function animate(){
    delta.now = Date.now();
    delta.difference = delta.now - delta.last;
    delta.last = delta.now;

    //update a sprite
    platform.x -= d(10);

    requestAnimationFrame( animate );
}

```

How can I keep the animation smooth?

# Answer
> 1 votes
The problem is most probably the `window.setTimeout(callback, 1000 / 60);` and then using (% 10 == 0). The window.setTimeout() callbacks are not "accurate". Thus, if you update your objects this causes the noticeable wobble.

Also your timeout functions runtime is shorter or longer depending on "counter % 2 == 0" and "counter % 10 === 0" is true. So you should call window.setTimeout() for the next callback directly at the beginning of the method!

```
var animate = (function () {
    return function (callback, element) {
        window.setTimeout(callback, 1000 / 60);
        if (counter % 2 === 0) {
            animate30();
        }

        if (counter % 10 === 0) {
            animate10();
        }

        counter = ++counter % 60;
    };
})();

```

Better would probably be the usage of window.setInterval() as like this:

```
var animate = (function () {
    var ref =  function() {
        animate60();
        if (counter % 2 === 0) {
            animate30();
        }

        if (counter % 10 === 0) {
            animate10();
        }

        counter = ++counter % 60;
    };
    window.setInterval(ref, 1000/60);
    return ref;
})();

```

A working example can be found at http://jsfiddle.net/t0sxynvc/.

---
Tags: javascript
---


# Question
Title: How to color each letter text in Phaser.js?
I have a text created with text object (game.add.text) and I would like to color each letter differently if that is possible.
If not, how can I achieve this?

# Answer
> 2 votes
Support for this was added in Phaser 2.1.2. Please see the Text.addColor method.

---
Tags: javascript, text, phaser
---