# Question
Title: VBO with texture index buffer different than vertex index buffer
I am trying to write my own OBJ importer and renderer in OpenGL (yes, I know, reinventing the wheel) and I found a problem that I don't knwo how to handle.

In an OBJ file faces are defined by a list of indices that refers to the vertices IDs that belongs to that face (and the same for texture coordinates IDs), an example of a face could be:

> f 2411/905 2414/906 2913/1463

which would mean that this face is created by vertices `2411, 2414, 3913` and texture coordinates IDs `905, 906, 1463`. And this leads to different index buffers, if I am not mistaken...

Now the question is, having both a buffer of vertices and a buffer of texture coordinates, how can I use both "at the same time", if I am only able to bing one index buffer and the indices to be used for a particular face are different for vertices and texture coordinates? Is there any trick to bind two index buffers, one for vertices and another one for texture coordinates?

And finally, just to give some code of what I've tried and that obviously doesn't work because I am binding two different `GL_ELEMENT_ARRAY_BUFFER_ARB` before drawing..., so it ends up with random texture coodinates.

```
// TEXTURE VBO
glBindBufferARB(GL_ARRAY_BUFFER_ARB, texCoordBuffer);
glTexCoordPointer(2, GL_FLOAT, 0, 0);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);

glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, texIndicesBuffer);
glIndexPointer(GL_INT, 0, 0);

// GEOMETRY VBO
glBindBufferARB(GL_ARRAY_BUFFER_ARB, vertexBuffer);
glVertexPointer(3, GL_FLOAT, 0, 0);
glEnableClientState(GL_VERTEX_ARRAY);

glBindBufferARB(GL_ARRAY_BUFFER_ARB, normalBuffer);
glNormalPointer(GL_FLOAT, 0, 0);
glEnableClientState(GL_NORMAL_ARRAY);

glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, indicesBuffer);
glIndexPointer(GL_INT, 0, 0);

// Bind texture and draw...

```

# Answer
You cannot use separate index buffers in the way you intend to. But since you are writing your own importer, you can very well reorganise the in-memory data so that both the position and texture information are indexed the same way. This possibly means duplicating information in the process, but that cost must be put in regard to the overall bandwidth gain provided by the use of index buffers.

The recently released book OpenGL Insights has a chapter about how to do this efficiently: Indexing Multiple Vertex Arrays, by Arnaud Masserann. Even if you do not have the book or the article, the author provides the full source code on GitHub.
> 8 votes

# Answer
What you *have* to do is "dupe up the data".

Say for (a contrived) example you have a square, but for some reason all 4 points of the square use the same normal:

```
v 0 0 0
v 1 0 0
v 1 1 0
v 0 1 0

vn 0 0 1

f 1//1 2//1 3//1
f 1//1 3//1 4//1

```

Great! Now what do you do?

When you're building your vertex array, you just duplicate `vn` 4 times. So your vertex array would contain:

```
struct Vertex{
  Vector3f pos, norm ;
}  ;

vector<Vertex> verts(4) ;
verts[0] = Vertex( Vector3f( 0, 0, 0 ), Vector3f( 0, 0, 1 ) )
verts[1] = Vertex( Vector3f( 1, 0, 0 ), Vector3f( 0, 0, 1 ) )
verts[2] = Vertex( Vector3f( 1, 1, 0 ), Vector3f( 0, 0, 1 ) )

verts[3] = Vertex( Vector3f( 0, 0, 0 ), Vector3f( 0, 0, 1 ) )
verts[4] = Vertex( Vector3f( 1, 1, 0 ), Vector3f( 0, 0, 1 ) )
verts[5] = Vertex( Vector3f( 0, 1, 0 ), Vector3f( 0, 0, 1 ) )

```

So you see, the normal `Vector3f( 0,0,1 )` has *got* to be duplicated all over the place. If you use an index buffer, you can reduce this to **4** verts. But that's the best you can do with a situation like this.
> 1 votes

---
Tags: c++, opengl, textures, vbo
---


title: Interpolation between two 3D points?

text:
# Question
Title: Interpolation between two 3D points?
I'm working with some splines which define a path a character follows (you can see a gameplay video here to get a better understanding of what's going on: http://www.youtube.com/watch?v=BndobjOiZ6g). Basically the characters 'forward' look direction is set to the 'forward' direction of the spline and when players tilt their phone left and right the character is strafed along its 'right' coordinate.

The issue with this is (rather obviously) in performance, interpolating over a spline to find the nearest position and tangent relative to the player is an incredibly costly operation. To get by this I cache a finite number of positions in what I call 'SplineDetails', the class is as follows:

```
public class SplineDetails
{
    public SplineDetails()
    {
        Forward = Vector3.forward;
        Position = Vector3.one * float.MaxValue;
        Alpha = -1;
    }
    public float Alpha; // [0,1] measured along length of spline where 0 is the initial point and 1 is the end point of the spline
    public Vector3 Position; // the point of the spline at this alpha
    public Vector3 Forward; // the forward tangent of the spline at this alpha
}

```

I populate this with say 30 coordinates and I can give a rough estimate of a coordinate and 'forward' based on a position past in. It's not as accurate but it's much faster.

But now I'd like to make the system work better by estimating positions and 'forward' directions by interpolating between two of the cached points though I'm stuck trying to figure out some logic.

My first problem is, how can I determine between which two points the object is? Given each point can be placed at different intervals along the spline it could mean that two points in front or behind the object can be closer to the object.

The other problem is to figure out the proportion between the two paths it's between, i.e. if there is a point a at coordinate (0,0,0) and point b at coordinate (1,0,0) if the object is at position (0.5,0,0) then the result it should give is '0.5' (as it is equal distance away from point a and point b). That's a simple example, but what if the object is at coordinate (0.5,3,0) for example?

# Answer
> 3 votes
1. Find distance **L** the proportion **p** between the two points **P1** and **P2**

**L = dot\_product ( P - P1, P2 - P1) / length ( P2 - P1 )**

**p = L / length ( P2 - P1 )**
2. Find vector **D** by interpolating between vectors **D1** and **D2** using **p**

**D = D2 * p + D1 * (1 - p)**
3. Find the middle point **M** by interpolating **P1** and **P2**

**M = P2 * p + P1 * (1 - p)**
4. Find the vector **A = M - P**
5. The desired direction in blue is **A + D**, optionally by multiplying **A** by a smoothing factor would cause the object to move faster or slower toward the spline

---
Tags: c#, mathematics, vector, splines
---


# Question
Title: GPU particle system using vertex texture fetch in Direct3D9
I've been reading up on particle systems amongst other stuff and one interesting approach uses rendertargets to store a particle's position, velocity, lifetime, etc. A pretty neat summary is given here, for example.

However, I'm wondering how to effectively use such a system? How would you create new particles, upload them to the GPU and how'd you determine what particles to draw? I mean, if you've got a 512x512 rendertarget storing particles, would you really just send a vertexbuffer with 262144 quads to the GPU and let the shader figure out which particles to draw and which to ignore?

Right now this sounds like a good idea for those bigger, continuous particle effects like weather or something... particle systems, which don't change often, can run for a while or where particle generation. I don't really see how they'd be performant enough to power dynamic one-off effects like explosions or something, because uploading new particles would basically require locking the rendertarget(s) and manipulating its (their) pixels, right?

# Answer
> 1 votes
As it is stated in the link you refer to, those particle systems have their limitations. As it is also mentioned, sometimes, stencil pre-pass is used to eliminate unused pixels.

Now to your questions:

> How would you create new particles, upload them to the GPU and how'd you determine what particles to draw?

This can be done in pixel shader, you first read render target which stores particle info and determine if it is dead. If yes you just write to the output RT initialized particle (as usually done on the CPU as well). Of course, you are not able to add more particles in this case.

There are more possibilities in DX10/100 however. Using geometry shader, more sophisticated techniques can be used. E.g. geometery shader can read buffers data which store particle info and based on this output triangles or not. But you'll have to anyway pass through the whole array. However you can split this in two passes: 1) generate triangles and output them to Stream Output stage buffers. 2) Use DrawAuto to shade only the previously output data.

So, basically yes, you can make decisions inside your shader about which particles to draw.

There are other more GPGPU like techniques, and it can be done using just DX9. E.g. After some time most of the particles may be dead, so in order to not waste time on them you can sort your buffers (render targets). For such a basic case like dead/alive *Histopyramid* method will suffice. This can be especially useful for the effects like explosions, when many particles quickly die.

> because uploading new particles would basically require locking the rendertarget(s) and manipulating its (their) pixels, right?

Yes, if you really want to do it on CPU. But you do not always need to, if you can generate your particles on GPU. Again in DX10/11, you can use Stream Output to generate your particles. In vertex shader you may use SV\_VertexID semantics to determine current vertex ID and generate particle based on this ID. You can also generate your particles in pixel shader by output data to render target. This all depends on what you are doing. Some techniques could be more suitable than other.

---
Tags: rendering, directx9, particles
---


# Question
Title: Blender 2.6: Move Mesh to X Coordinate of Another Mesh
## An example:

There are two planes `A` and `B` with the following median points:

```
    ( X | Y | Z )

M_A ( 3 | 2 | 2 )
M_B ( 6 | 1 | 1 )

```

Now I want to move the plane `A` on the `X`-axis to the `X` coordinate of the plane `B` (the `Y` and the `Z` coordinate of plane `A` should stay the same). That's the desired result:

```
M_A ( 6 | 2 | 2 )

```

## My Question:

How can I **move** a mesh **to the `X` position of another** mesh (or to the `X` postition of the 3D cursor) without touching the `Y` and `Z` coordinates. - It's a bit like the Blender function called `Snap`, but what I want is **just about `X` coordinate**.

Thanks for your ideas (please comment if anything is unclear!).

# Answer
> 0 votes
You can constrain movement to an axis even when using the various snapping modes in Blender. 'g' to start a move, 'x' to constrain to the x axis, and hold down control to snap (change snapping modes in the popup menu next to the magnet on the toolbar).

Alternatively you can enter the coordinates directly in the object property panel.

---
Tags: models, movement, blender, 3d-meshes, coordinates
---


# Question
Title: Component / Entity-based design => no inheritance at all?
*\[I understand that this this could be seen as a rather theoretical question, but I think it has real-application impact\].*

**"Academic" base**
With a component-based design one wants to get rid of the long inheritance chains known in larger games ("deadly diamond of death"). So we create a `BaseComponent` class that handles all the administrative chores (ID and type handling, possibly a generic list of properties, ...).

Now each actual `Component`should inherit from that base *\[start of academic/dogmatic flair\]* and ***only*** that base *\[end\]*.

**Concrete situation/example:**
Assume I have three components with different attributes:

1. `Person`: age, name, gender, isTired, isSick, ...
2. `Guest`: satisfaction, desires, ...
3. `Employee`: current duty, shift end, ...

Now in traditional OOP design, `Person` would act as the base class for the other two. As I currently "forbid" that type of inheritance for the components in my project, everytime I am e.g. processing my employees and checking/updating their state attributes I have to either use some helper function to access the sibling component `Person` (if it exists) or send a message out that hopefully `Person` will be registered for and will process. Or I can simply assume that each `Guest` and `Employee` always will have the component Person. But then I might as well let those two components inherit from `Person`, so they for example both have the member functions to manipulate some specific properties.

***Note:*** There will never be an `Entity` that has the component `Employee`, but not component `Person` (same applies to `Guest`). They are a fix requirement, which is why I am considering inheritance here at all.

**Question:** My question is now whether anyone can see any real-life problems that would be introduced by (re-)incorporating ***a bit*** of inheritance into my components other than to a degree violating the original base/dogmatic concept and the risk that (if used excessively) I would end up with the exact same problem the component-based design tried to solve in the first place?

*References:*
Thread that ultimately led my to asking that question, showing such inheritance.

# Answer
> 2 votes
> Question: My question is now whether anyone can see any real-life problems that would be introduced by (re-)incorporating a bit of inheritance into my components other than to a degree violating the original base/dogmatic concept and the risk that (if used excessively) I would end up with the exact same problem the component-based design tried to solve in the first place?

By doing that, you make explicit the requirement that every guest is a person, and that every employee is a person, but you've also added the implicit requirement that no guest is an employee (or vice versa) because then they would share 2 copies of 'person' data. You will need to think about how you manage that. And, once you have put in place a system that allows you to forbid certain pairs of components on the same entity, you will see that an almost identical system would allow you to enforce the presence of one component on an entity if another is present.

So, given that you have to address the mutual component compatibility problem one way or another, I'd be inclined to suggest you're better off keeping Person and Guest/Employee separate. Not only is further separation a good thing in software development terms (eg. the Single Responsibility Principle) but it leaves your design open to future extensions to Robot Employees, Animal Guests, or Guest Employees.

(PS. There is nothing inherently wrong with inheritance as a programming language construct. Component based systems for games are not about trying to remove the use of inheritance from the code base but about finding a more flexible way to represent the large permutation of traits that can apply to any single entity in the game. You might have inheritance in hundreds of places throughout your code but the components mean you never have to derive anything from the Entity class that exists in your game world.)

# Answer
> 2 votes
You are concerned about the diamond problem in regards to some minor entity inheritance. Don't be. *Inheritance* is for *is-a* relationships. *Composition* (as used to construct entities) is for *has-a* relationships. Inheritance hierarchies for components are nearly always *is-a*.

Mick West's seminal article on the topic deserves a thorough read-through, as it gets down to the heart of the issue of how processing should work. You will note in the final part of his article that OO is not strictly a requirement, as you can do this with nothing but procedural programming and monolithic arrays.

Keep your inheritance at the component level, there is nothing wrong with a bit of inheritance here. There should OTOH be only one level for `Entity`, no subclassing unless there is something very specific you are trying to achieve... one example that comes to mind is having a lighter-weight entity class such as `EntityLite` that saves on memory consumption by holding fewer component references, and might be used for say, particles that don't need things like AI, inventory and so on. As for inheritance in components, I've found myself using it e.g. for the idea of health and mana tracking components being similar, so I subclassed these and then filled in the differences in the subclasses representing each component. It is a valid pattern.

The aspect which you noted in the comments to this response is a separate matter. Certainly you can try to access other entities from a global list or hash, but really the reference to the entity you are trying to access should always be gotten from some more direct mechanism, often geometrically / physically based, or faction-based. So you could get a particular team member to send them a message based off the fact that you have a list of team member entities (example might be AI inspecting it's teammates, then throwing some ammo to whichever soldier has the least ammo) or based off the fact that you did eg. a raycast collsion with that character (example might be an AI talking to someone it can see directly) which returns you the collided object and thus the entity you are looking at. It's important to get those communication channels right from the start, rather than selecting some arbitrary entity out of a massive list, if only for efficiency reasons.

# Answer
> 1 votes
I'm not sure about your Person / Guest / Employee example (depends on what you want to do with these components) but I have used deeper inheritance for my graphical components:

```
abstract GraphicalComponent : Component {...}
//has abstract GetAABB and Draw methods
//there is a system to manage all GraphicalComponents

SpriteComponent : GraphicalComponent {...}
//draws textured quad

ParticleEmitter : GraphicalComponent {...}
//draws many textured quads

SkeletonComponents : GraphicalComponent {...}
//for skeletal animation

```

I don't see any benefits from having separate system for each type of graphical object. With one system I can implement spatial partitioning, layers, etc.

---
Tags: architecture, component-based, entity-system
---


# Question
Title: Component/Entity-based design + Behavior Trees => how to integrate?
For my current project I implemented a ***component/entity-based system***, basically following most of the best-practice there is in this rather undefined area.

So I got (slightly extended) **Entities**, which are basically an `int` ID, a human-readable Name, a `std::map` of components and a `long` "type indicator" which is used to show what components are present (I have an power of two `enum` for all the components types and whenever a component is added to the Entity, I automatically alter that long via bitwise operations, compare this answer).

Then there are the **Components**, also rather simple: `int` ID, `enum` as component type, parent Entity pointer and a `std::map` of all properties this component holds.

Lastly some **Systems/Managers** that handle the actual logic processing. They first check if the currently processed Entity has a matching `long` "type indicator" = all necessary components for that system are present. It then accesses some properties if needed and either directly calls some functions in the respective component or send some messages (via a message dispatcher).

***Bottom-line:*** Until here, a rather standard event-driven component/entity-based system combined with a data-driven approach (compare, components do not have hard-coded data variables, but instead a generic map, as (some) components/archetypes of components will later be read from files with the option to add additional data, that is not part of the actual component code.

Now I would like to also introduce ***Behavior Trees*** (based on AiGameDev BTSK) into that project, but I am not sure if and how they should be linked to the already existing components or how to integrate those design in general.

*Several related ideas/points/questions come to mind:*

1. My BTs will be read from files (again). I currently have a hard time seeing how I would however best make the connection between an *`BT Action`* in that tree and the actual coding in my application. Should I build up some sort of map between the action names used in the BT files and a function pointer to the actual logic implementation? What is the usual approach to solve that?
2. I assume that I will have to create BTs for all my different `Entity` types (so for each game-logic/AI-relevant combination of components as indicated by my multiple times mentioned long "type indicator"). As a result it doesn't make sense to put the *`BT Action`* implementations in the components as most likely many components will be involved per action, does it?
3. So should the *`BT Action`* logic sit in a/multiple separate systems (to whose methods the map from idea #1 points to)? The system would then check per my `long` "type indicator" whether the `Entity` for which the BT is currently checked and that was told to execute a certain action (= method in the system) is actually allowed to do so (= has the necessary components). But then, if not (because for example the BT creator did overlook a specific situation, where a necessary component might not be attached to the Entity at runtime anymore), nothing would happen.

*Questions:*

* Are there proven concepts for that kind of integration?
* What is your take on my 3 points above?
* Any other things that come to mind, also regarding my component/entity-based design in general?

# Answer
> I currently have a hard time seeing how I would however best make the connection between an BT Action in that tree and the actual coding in my application. Should I build up some sort of map between the action names used in the BT files and a function pointer to the actual logic implementation? What is the usual approach to solve that?

Forget about function pointers and think about objects. Each node in the behavior tree (BT from this point on) would ideally correspond to one object in your code. Those objects will have a standard interface to let you arrange them as a tree and for traversing them. A set of function pointers is fine for the behaviour but it doesn't capture the structure of your tree at all.

> As a result it doesn't make sense to put the BT Action implementations in the components as most likely many components will be involved per action, does it?

I would expect entities to have a single BehaviorTree component which stores the relevant data for that entity's BT. Execution of the BT is either done by the BT Component or the BT Subsystem depending on how you handle components in your system. As with pretty much anything using components, they will have to refer to other components to get the job done, but those other components won't have to know anything about BTs.

The different actions available would, at the simplest level, be encoded into the various BT node objects. They should be able to make the relevant entity act by manipulating the components as necessary, eg. accessing the movement component to move.
> 2 votes

---
Tags: ai, component-based, entity-system, behavior
---


# Question
Title: Creating an illusion of stress and danger
I'm currently experimenting with an adventure game setting where at some point the game is quite calm and the player has to solve puzzles and at some point there are enemies or environmental traps.

I don't want to have any surprising danger events coming out of nowhere that would scare the player, so I would like to **build up the players' tension** before a section of the game starts which will contain multiple "player-killing" obstacles (may they be enemies, or the ground falling apart..).

My sound artist made some really good music and sound effects to slowly build up the tension, but game elements during this phase are missing. It's like the player is running from a **puzzle-zone to danger-zone** through a boring plain section.

Beside sound, what are some generic ways to build up the players' tension? Can i aid with special Visuals, or do i have to improve the story or possibly invent some pre-danger-zone easy obstacles?

# Answer
> 22 votes
I sometimes think the act of having to make a decision with a sense of "if I don't decide, things will not be as I wish" is good to create tension.

It doesn't have to be that making the decision IS important, but that the player thinks they need to.

For example, there's the idea of false danger. Crossing a rickety bridge (that really isn't going to fall) creates more tension that a bridge that really does fall some times.

Another thing is just giving the player heads up on something that's going to happen, but don't tell them when. Finding wanted posters for a notorious killer early on is a big hint you'll meetup with him - and there's tension in that. Finding the aftermath of an extraordinary event that hints at something the player will encounter later works the same way. Wiped out platoon for example.

Think of it this way - a good book can have tension and be scary, but clearly it has no sound fx, light changes or anything else - it's all in your head (and the storytelling).

# Answer
> 23 votes
This really all depends on what *kind* of game you're making. Not only the genre, but how you're presenting it: 2D top-down, 2D side-scroller, 2D isometric, 3D first-person, 3D third-person shoulder, 3D third-person isometric/freecam...

Basically, from an artistic standpoint, rather than an actual game-mechanic standpoint, there are several things that you can do. Things like palette-changes, lighting-changes, starker/longer shadows, visual-noise, tightening the camera (sense of claustrophobia), shaky-cam...

...switch the character's running speed, slightly, change idle/movement animations to depict that the characters, themselves are nervous.

Generate spiders or bugs, or whatever is creepy and fits within the theme. Make them tiny, non-interactive, but make tiny visual cues of some sort. Not a ***BOO*** factor, but a ***creepy*** factor.

I can't tell you how to do it in YOUR game, because there are too many variables we don't have, both in theme and in presentation, but you should watch some old horror movies or old psychological-thrillers, et cetera. Avoid newer movies, because, surprise, after the mid-'90s, most have been "slasher-horror" with pop-up scares. Pay close attention to what mechanics worked for film-making in the old days.

Sound was a big deal! Not just music, but sounds and sound-themes (nature or sewers or empty streets, etc). So were pacing and lighting and camera angles (I suggest looking at *Evil Dead 1* -- the effects are dated, but some of the shots are still mind-blowing).

Unless you're doing a lot of cutscenes or controlling the character movement like in a Point'n'Click setting, all of these things aren't always available in a 1:1 translation to your game's format, but whether they come through as special effects, or as cutscenes, or artistic direction for level design, or pacing in terms of ramping up dangers or ramping up numbers or difficulties of enemies... each or all of these things can improve the sense of tension.

If you're going to put insta-kill traps out, then put some warnings out, maybe a pre-sprung trap with a corpse in it.

So yes, music, sound-effects, soundscapes (sometimes the most-effective "tense" scenes are the ones where the tense music goes away, and you're left with a creepy soundscape), but also character-animation, colour-palette changes (just look at the average Super Mario World level versus colours inside of a haunted house), camera-angles, decreases in visibility (fog of war, or zoomed-in camera), increases in shadow-intensity and shadow-length, artistic creepiness (spiders/bugs/intestine-covered walls/alien growth/etc), visual cues to increased danger (pre-sprung traps/previous adventurers/etc.)... the more of these you put together (especially when you mix pacing with visual with audio), the more tension people are going to feel.

The question, of course, is how to pull it off in your particular game. And really, it's just an art which needs to be practiced and tested and revisited, because there is no one correct mix.

# Answer
> 7 votes
I think that tension comes from a change in your perception. When you feel secure and confident, you dont feel tension. Everything goes well.. or at leat, even if everthing is running with difficulties, at least are well knowed difficulties.

When your perception of the world changes, you start to feel great incertitude. That is what generates a great tension.

For example. If you are playing Doom 1 or 2, everthing passes on narrow corridors and small rooms. But.. sometimes you find a very wide place. You then, feel very strange... this is different, you dont know what kind of dangers are awaiting in this new "world".

In contrast, you can think visceversa. If you play Journey, everything is very big and wide. You play the game feeling free, you fly, you float... but if you enter in a small place, you start to feeling compressed and tensioned.

I think that the major thing that makes people feel tension is "the change".

# Answer
> 3 votes
I just wanted to mention the game Amnesia: The Dark Descent. The game is basically scaring out the player and building tension. Not really creating stress, so these things might be not really what you are looking for. Of course music and sounds effects are important for the effect. But some things I noticed in the game are:

* Creating dark environments, with some flickering light points like candles.
* Wind streams that closes/opens a door or causes candles go out.
* Using a smaller field of view.
* Camera bobbing (simulation that the player steps).
* In scary situations, some visuals effects like:
    + Adding a red/purple shine to the screen
    + Disturb the view by:
        - Adding smoke or fog
        - Using a higher field of view (gives the effect that distances are longer and the camera zooms out, also creates the illusion of moving very quickly.)
        - Transform each vertex of the geometry in the vertex shader to make the screen totally go crazy.
* Make the player walk in a slightly wrong direction (like when you for example in a sinking ship, so the ground is not perfectly horizontal). This might cause the player feeling dizzy. You can use this effect even if the ground is perfectly horizontal.
* Weak and fluctuating current (electricity).

The sound effects I like are:

* Hearing your own heartbeat, breath and footsteps
* Wind
* Squeaking doors
* Dripping or streaming water

Another nice effect to create tension is to stop music. It will give the effect of: "what happens, music stops?" For example, music stops and the only thing you hear is your breath and the noise of a leaking tap and a broken light that keeps flickering (like the starter of a TL light that keeps trying turning the light on).

---
Tags: game-design, storyboard
---


# Question
Title: Why is my obj file imported into pyglet showing a blank screen?
I am trying to figure out how to import .obj files generated using Blender into my Pyglet game. There is an importer object, example code, and an example .obj/.mtl file within Pyglet's contrib directory.

The pyglet contrib version works (and is flickery; comment out `w.flip`) with the pyglet/contrib .obj/.mtl files. When I try to run it with **my** .obj and .mtl files I get a blank screen.

Why am I seeing a blank screen instead of my Blender-generated object?

FWIW, here's my test repo.

# Answer
There were no normals, so nothing was displaying. I updated the git repo to warn on missing normals.

Unfortunately, I have no ground-breaking debugging techniques to report. I opened up the working .obj file and the "broken" .obj file, and by comparing them I noticed that one of the files had normals, and the other one didn't.
> 2 votes

---
Tags: obj, pyglet
---


# Question
Title: What is actually drawn when glDrawArrays and glDrawElements are called?
In my journey out of immediate mode I've come across a snag that I haven't been able to find a decent answer for in any tutorial or API, namely: Which data structures are actually invoked when I make a call to a glDraw\* function in OpenGL3.3+?

For example, if I want to draw two 3D models and I've put their vertex data in two different VBO's, does invoking glDrawArrays draw everything set under the current VAO? Or does it only draw the currently bound VBO sampling from the currently bound texture?

I basically understand VAO's and VBO's conceptually but its down to implementation that I'm running into problems, it's a big jump to go from the "stability" of immediate mode to the a-synchronicity of modern OpenGL.

# Answer
`glDrawArrays` will draw from the currently bound vertex attribute arrays, which are "created" and bound themselves with `glVertexAttribPointer` and `glEnableVertexAttribArray`, which *do* use the currently bound vertex buffer. It doesn't matter if the vertex attributes are all from one buffer or multiple buffers, and you don't need any particular vertex buffer to be bound when drawing; all the `glDraw*` functions care about is which vertex attribute arrays are enabled.
> 5 votes

---
Tags: opengl, graphics
---


title: Nine Patch Images in DirectX

text:
# Question
Title: Nine Patch Images in DirectX
In Android development I found nine patch images very useful to draw images that have a fixed border. When the image is scaled the inner part scales, but the border stays at a fixed size.

I was looking for something similar in DirectX. Does anyone have information/pointers to nine patch images in DirectX?

# Answer
> 2 votes
Well, to do 9-Patch drawing, you would find the coordinates of the individual regions and then convert those to UV coords (percentage of image size). You would then draw those to quads.

The corners quads would be the size of the region of the image and the middle sections would be whatever dimensions you want (where the edges only manipulate the edge direction).

You would also set your projection matrix to an orthographic view if you wanted to draw in 2D to get accurate pixel representation.

---
Tags: directx, shaders, hlsl, directx11
---


title: Player movement behind objects

text:
# Question
Title: Player movement behind objects
I was playing around on RPG JS and Browser Quest, and the player, when moving, can give the effect of walking behind the trees or houses etc, so the player effectively disappears while it is "behind" the object.

How is this effect created?

I am building and RPG using javascript and canvas at the moment, and would love to try and implement this into the game. I am working on A\* movement for my character.

# Answer
> 2 votes
That's layer rendering techniques. The idea is to overlap images that gives it the illusion of depth. For instance, consider a static looking map array that look like this:

```
[1][1][1][1][1][1][1][1][1]    [1] = Map Boundaries
[1][ ][ ][ ][ ][ ][ ][ ][1]    [P] = Player
[1][ ][P][ ][H][H][H][H][1]    [H] = House or any solid tile that the player cannot
[1][ ][ ][ ][H][H][H][H][1]          get through.
[1][ ][ ][ ][H][H][H][H][1]
[1][ ][ ][ ][H][H][H][H][1]
[1][ ][ ][ ][ ][ ][ ][ ][1]
[1][ ][ ][ ][ ][ ][ ][ ][1]
[1][1][1][1][1][1][1][1][1]

```

If the computer were to use this map and draw exactly what it reads, the problem we will encounter is that the player will be on top of the house if the player decides to move two tiles to the right.

```
[1][1][1][1][1][1][1][1][1]    // The player is on top of the house
[1][ ][ ][ ][ ][ ][ ][ ][1]
[1][ ][ ][ ][P][H][H][H][1]
[1][ ][ ][ ][H][H][H][H][1]
[1][ ][ ][ ][H][H][H][H][1]
[1][ ][ ][ ][H][H][H][H][1]
[1][ ][ ][ ][ ][ ][ ][ ][1]
[1][ ][ ][ ][ ][ ][ ][ ][1]
[1][1][1][1][1][1][1][1][1]

```

But of course, we want the player to be behind the house, after all it only makes sense that a player will be behind the house and not on top. But that cannot be accomplish using one map *(actually yes you can, but for simplicity we use two maps to demonstrate the layering in effect)*. So instead, we instruct the computer to render our images by separating the map into different layers. Foreground, Midground and Background

Background is the images that the player will walk on. Midground is where the NPC, player or anything that moves will be on. Foreground is the tiles that you want to overlap your character to give it the look of depth.

```
[1][1][1][1][1][1][1][1][1]    // Background where all solid and static tiles are.
[1][ ][ ][ ][ ][ ][ ][ ][1]    // Tiles that the player cannot freely move through.
[1][ ][ ][ ][ ][ ][ ][ ][1]    // Notice the top line of the house is missing.
[1][ ][ ][ ][H][H][H][H][1]
[1][ ][ ][ ][H][H][H][H][1]
[1][ ][ ][ ][H][H][H][H][1]
[1][ ][ ][ ][ ][ ][ ][ ][1]
[1][ ][ ][ ][ ][ ][ ][ ][1]
[1][1][1][1][1][1][1][1][1]

[ ][ ][ ][ ][ ][ ][ ][ ][ ]    // Midground where your NPC and players are.
[ ][ ][ ][ ][ ][ ][ ][ ][ ]    // N = NPC
[ ][ ][ ][ ][ ][ ][ ][ ][ ]    // I am playing the NPC right behind the house
[ ][ ][P][ ][ ][ ][N][ ][ ]
[ ][ ][ ][ ][ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ][ ][ ][ ][ ]

[ ][ ][ ][ ][ ][ ][ ][ ][ ]    // Foreground where your players can walk underneath
[ ][ ][ ][ ][ ][ ][ ][ ][ ]
[ ][ ][ ][ ][H][H][H][H][ ]
[ ][ ][ ][ ][ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ][ ][ ][ ][ ]
[ ][ ][ ][ ][ ][ ][ ][ ][ ]

```

The final render of the map would look like:

```
[1][1][1][1][1][1][1][1][1]    // When all three layers is put together.
[1][ ][ ][ ][ ][ ][ ][ ][1]    // NPC had been overdrawn by the foreground.
[1][ ][P][ ][H][H][H][H][1]    // But the NPC is still there conceptually, you will
[1][ ][ ][ ][H][H][H][H][1]    // need other codes to tell it that the NPC is there.
[1][ ][ ][ ][H][H][H][H][1]
[1][ ][ ][ ][H][H][H][H][1]
[1][ ][ ][ ][ ][ ][ ][ ][1]
[1][ ][ ][ ][ ][ ][ ][ ][1]
[1][1][1][1][1][1][1][1][1]

```

That's how I have done it in any 2D games, hope this helps.

---
Tags: javascript, movement, html-canvas, rpg
---


# Question
Title: Architecture of "doodle jump" type gameplay infinite looping background
I am planning make a doodle jump type game, character jumping on platforms. A scrolling or doodle jump like background which ll appear to move when character moves upward and appear moving (just like in doodle jump) so, my thoughts are for this kind of background is

* to take a large image i.e of 2048x2048, make 2 planes, set this texture to them, when first image ends other ll move its position on top of first, when second ends first ll move on top of second and so on.
* Other approch could be a "Instantiate" and "Destroy" of small images having textures on them according to jumping character position ( which i doubt ll b expensive )

They are my thoughts, I want to go for best approach and would like to listen the best one. Is there any more appropriae way to achieve moveable background, I ll appreciate your suggestions. Thanks.

# Answer
We are in the making of a similiar game, without the left-right scrolling. We decided to load as much texture as we can, becouse it can be real slow when our character moves up fast regardless how we try to load it(eg. AssetBundle's loadAsync). Plus, when our level loads we pre-create(Instantiate) some platforms and particles, but instead of destroy(when they gone out of vision) we will store them and reuse them(classic object pools). So my suggestion is: preload/pre-create then reuse as many `thing` as you can to achive fast gameplay.
> 3 votes

---
Tags: unity, 2d
---


# Question
Title: SharpDX (DirectX) - possible to measure Frame time?
I'm trying to benchmark various ways to draw 2D lines and have a snag. A D3D10Device that I draw with (and flush) doesn't appear to block, so I can't accurately measure frame rate (or time to render 1 frame).

Here's some code

```
    // Inside my custom render context - at end of setting up draw calls
    public void Dispose()
    {
        {
            _vertexBufferStream.Close();

            _direct3D10Image._d3d10Buffer.Unmap();

            // Vertex buffer contains LineList with 200k vertices
            _direct3D10Image._d3d10Device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(_direct3D10Image._d3d10Buffer, 32, 0));

            int targetWidth = _direct3D10Image._renderTargetTexture2D.Description.Width;
            int targetHeight = _direct3D10Image._renderTargetTexture2D.Description.Height;
            _direct3D10Image._d3d10Device.OutputMerger.SetTargets(_direct3D10Image.DepthStencilView, _direct3D10Image.RenderTargetView);
            _direct3D10Image._d3d10Device.Rasterizer.SetViewports(new SharpDX.Direct3D10.Viewport(0, 0, targetWidth, targetHeight, 0.0f, 1.0f));
            _direct3D10Image._d3d10Device.ClearRenderTargetView(_direct3D10Image.RenderTargetView, _direct3D10Image.ClearColor);
            _direct3D10Image._d3d10Device.ClearDepthStencilView(_direct3D10Image.DepthStencilView, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1.0f, 0);

            // Shader is generating geometry based on line-list to render a 2D plot
            for (int i = 0; i < _direct3D10Image._technique.Description.PassCount; i++)
            {
                _direct3D10Image._pass.Apply();
                _direct3D10Image._d3d10Device.Draw(
                    (int)(_linesCount * 2),
                    0);
            }
        }

        // Flush doesn't appear to block - how to get meaningful time to draw out of SharpDX?
        _direct3D10Image._d3d10Device.Flush();
        _direct3D10Image._dx10ImageSource.InvalidateD3DImage();
    }

```

Now if I time the setup of draw calls and the Dispose method above, it reports 15ms to draw. However, there appears to be a significant lag between start of draw and the screen actually presenting.

How can I measure the time to present (or is it possible to make D3D10Device.Flush() blocking?)

# Answer
Accurately measuring the performance of graphics API (D3D or OpenGL) calls isn't always a matter of timing the CPU-side code, because some of those CPU-side calls you're making could dispatch work to the GPU and block (or not) and the timing you get doesn't really account for that in a useful fashion.

This guide discusses some techniques for profiling D3D which are applicable (since you're just using a wrapper). You'll need to adapt them if you aren't using D3D9 but it's not that difficult as most of the discussion is conceptual: why profiling is hard, how correctly profiler the CPU aspect, and how to control driver optimizations and use the query APIs to get information about GPU-side performance.
> 1 votes

# Answer
Ok - I think I figured out what was going on.

My laptop has two graphics cards, an integrated Intel GPU and an nVidia 650GM. At the time when I saw lag after render I was using Integrated (possibly software emulation?). Anyway with nVidia enabled there is no delay in presenting, its pretty much instant (and a lot faster to boot!)

So I'm getting pretty accurate frame times measuring start of drawing instructions to \_d3d10Device.Flush()
> 0 votes

---
Tags: directx, frame-rate, sharpdx
---


# Question
Title: Extracting Frustum Planes (Hartmann & Gribbs method)
I have been grappling with the Hartmann/Gribbs method of extracting the Frustum planes for some time now, with little success. There doesn't appear to be a "definitive" topic or tutorial which combines all the necessary information, so perhaps this can be it

First of all, I am attempting to do this in C# (For Playstation Mobile), using OpenGL style Column-Major matrices in a Right-Handed coordinate system but obviously the math will work in any language.

My projection matrix has a Near plane at 1.0, Far plane at 1000, FOV of 45.0 and Aspect of 1.7647.

I want to get my planes in World-Space, so I build my frustum from the View-Projection Matrix (that's projectionMatrix * viewMatrix). The view Matrix is the inverse of the camera's World-Transform.

The problem is; regardless of what I tweak, I can't seem to get a correct frustum. I think that I may be missing something obvious.

Focusing on the Near and Far planes for the moment (since they have the most obvious normals when correct), when my camera is positioned looking down the negative z-axis, I get two planes facing in the same direction, rather than opposite directions. If i strafe my camera left and right (while still looking along the z axis) the x value of the normal vector changes.

Obviously, something is fundamentally wrong here; I just can't figure out what - maybe someone here can?

**EDIT:** Applying the algorithm to *just* the Projection matrix (i.e. model and view matrices are identity) I get the Near and Far planes returned as the following; Far: normal\[0,0-1\], distance 1 Near: normal\[0,0,-1\], distance -0.3328891

Can someone tell me if these seem correct? Using the algorithm with just the Projection Matrix should return the planes in View Space (camera space)

# Answer
> 1 votes
Firstly, extracting from just the projection matrix is a good place to start debugging.

To answer your question:

In this case, your near and far plane values should be \<0, 0, 1, -1\> and \<0, 0, -1, 1000\> respectively. In practice, it might be off by a little due to floating point rounding errors.

Now to help you solve your larger problem:

1. You say you are getting a near and far plane of \<0, 0, -1, -0.3328891\> and \<0, 0, -1, 1\> respectively. These values comes directly from summing/subtracting rows or columns from your projection matrix, so writing out the projection matrix values on paper and eyeballing it might make it obvious.
2. Make sure your projection matrix is correct.
3. Make sure your plane normalization routine is correct (\<a / |n|, b / |n|, c / |n|, d / |n|\>, where |n| is the length of \<a, b, c\> ONLY).
4. Make sure you are not getting your rows and columns mixed up.

You are basically going to need to comb through your code step-by-step and make sure everything has been done correctly.

I recently did this (for Direct3D though) and had to go through the same steps.

---
Tags: culling, frustum, occlusion
---


# Question
Title: Simultaneous events in a realtime system, where processing order causes different outcomes
I am working on a realtime dungeon crawler, focusing on a relatively complex and flexible skill system. Somewhat similar to MMORPGs with many compound spells, area effects, buffs/debuffs, ect. I am working on the last few subsystems of the engine.

I found a problem with actions happening in the same logic frame which change an actor's attributes.

For example, let's say two actors use a skill on eachother in the same logic tick, which deals 100 damage and leaves a debuff which halves damage done.
If I simply iterate over each actor and process their abilities, the one which gets processed sooner will deal full damage, the other will do so with the debuffed state, dealing only 50. Ideally, I'd like both of them to work similarly, dealing full damage and leaving the debuff.
What annoys me is the undetermined nature arising from the order of iteration.

---

One solution I thought about was to defer all the stat value changes and buff/debuff application until all the abilities are processed, since these are the only things which can affect the behaviour of abilties. So essentially I loop over actors, process their ability methods, but queue up the stat and status effect changes in a list.
Once I processed every ability I iterate over once more, this time changing the actual stats from the queued values.

This fixes the determinism problem, but causes another.

To use another example (since I can't exactly phrase the general case):
Let's say the player has 100 mana, and gets hit by ten manaburn attacks in one frame, each burning at most 50 mana, and dealing damage equal to the mana burned.
If I don't use the former fix, it'll work correctly, two will burn out the 100 mana of the player dealing 100 damage, the rest eight will do nothing.

With the fix however, since the player's mana value doesn't change yet, all ten attacks will land and deal 500 damage, more than the amount of mana the player has, which is an even more silly situation than before.

---

I'm quite an amateur, I have less experience than wit for designing complex systems. Is it possible to have determined behaviour for actions happening in the same frame while avoiding nastier consequences like the second example?

I know the player will unlikely notice the errors in the first case, and I don't think other developers bother with this issue either.

I'm still curious though, is such thing possible, a pipe dream, or just I have a warped idea about how the game logic should work?

Thank you!

# Answer
> 3 votes
Good question. Your 2 examples are obviously incompatible by design - either the effects of previous actions are available when calculating results of the current action, or they're not.

First, though: the phrase *"I am working on a realtime dungeon crawler"* implies that this sort of problem really shouldn't happen often enough to be a problem. The essence of real-time is that things happen so quickly that it's easy to accept that the other person acted just milliseconds more quickly than you, and so an arbitrarily sequential order of execution is almost never a problem for the player.

If, for some reason, everybody does tend to use abilities on the same tick, you could just use some system to spread them out so that this is a much rarer occurrence. Make the ticks shorter and more frequent, or have characters act on different ticks based on a speed or initiative value. Or, just randomise the order of logic processing so that nobody gets a persistent advantage.

But if you really want to 'solve' the problem, one way is to split the system up into phases, one for evaluating simultaneous actions, one for applying the results, and one for evaluating AND applying sequential ones. That way the buffs all get resolved fairly and only once that's done are effects like manaburn executed. Generally speaking the only actions that need to be sequential are the ones where the character being changed is the same character that's being examined, because each action needs to perform the whole read-then-write atomically for the system to make sense.

# Answer
> 0 votes
I had a theoretical idea how to combine delaying changes to the world with having the updated values available. I realized the issue mainly boils down to somehow have a defined order of events happening inside a frame, somehow subdividing the frame into smaller, but undefined units in time, both in length and count.

**The theory:**
Each event is a series of simple actions, which either sample the world, or change them by inserting new entities, changing attributes or applying effects. As Kylotan pointed out, if the changes to the world are delayed, they are not available when an event is processed.

I thought about putting some kind of breakpoints into an event, which mark that we need the updated state of the world to continue. Each segment between breakpoints is processed sequentially.

In the main game loop, the processing of the events is done in a second loop:

1) each event sequentially gets processed up to the next breakpoint.
2) The attributes and status effects of the entities are updated.

This is repeated until there are no unfinished events left.

I am using Java, I don't have any idea how this could be implemented most cleanly. One idea I had is to break the event method into a switch, each segment going into a case.

This would translate the following (pseudo-code)

```
Event manadrain(){
  player.mana.add(-5);
  waitWorldUpdate();
  int v = min(target.mana, 10);
  player-mana.add(v);

```

into:

```
public void processEvent() {
    switch (segment) {
        case 1:
            player.mana.add(-5);
            return true;
        case 2:
            int v = min(target.mana, 10);
            player - mana.add(v);
            return false;
    }
}

```

the segment variable can be incremented internally; the return value returns true if there are more segments to be processed. The events can be processed in a list, and removed when they return false.

This way, both of my examples in the question are solved. In the damage debuff example, there are two potential outcomes:

1. If we do the damage and the debuff application in one segment, both of them will deal 100 damage, and receive the debuff.
2. If we apply the debuff first, wait for an update then do the damage, both will do 50 damage with the debuff on.

The manadrain example is simpler, the events are not needed to be broken apart; since they are processed sequentially, the first two will land and burn 2\*50 damage, the rest will fail.

Why would such a deterministic solution be important?
For example if two similar entities are created at the same time, and affect eachother in a similar way to the first question example, it may be desired that both of them change in the same way.

On the other hand, the more time I spend working on this problem, the more potential aberrations I find. Not to mention this would likely be a nightmare to debug and work with. I am not even sure this solution is good enough. Please tell me if there are any cases where the above solution fails.

---
Tags: game-mechanics, game-loop, rpg
---


# Question
Title: Should I be using Blender game engine as my first engine?
I am new to game development. I was learning how to create 3d models in Blender to use in an Android game, but I was reading that you can use Blender game engine for creating android games.

Is it a good idea to use it since I couldn't find any reviews about it. Is it actually being used by developers to create Android games?

# Answer
It is a good idea to test your idea in Blender app engine as a new 3D modeller. The game engine requires less programming knowledge, free, and you don't need reviews because it already has a great community. It is not as widely used by developers as other commercial game engines but it is still a good start.
> 1 votes

---
Tags: blender
---


# Question
Title: Is it acceptable to say "Inspired from ... game"
For a game I'm developing, I would like to use "inspired from ... game" to acknowledge and praise that game. But I'm not sure if this is a good idea from a legal point of view. They might think my game is a ripoff, and base the claim on my word.

Any ideas?

# Answer
> 7 votes
Professionals making games with relatively deep pockets have said things like this, 3:55 into this talk Luke Muscat says he took his inspiriation for Jetpack Joyride from that helicopter game everybody's seen.

Obviously JJ is **way beyond** that helicopter game in terms of execution, delivery and the things they built around it (just listen to the part near the end where he talks about how they developed the goals system). I can't see helicopter guy suing Halfbrick for what he's done, even though he openly admitted the basic mechanic of his game is based on it.

**Was this a mistake by Muscat**? I'd like to hear someone say otherwise.

I also heard various other programmers (such as John Carmack) say things like Commander Keen was all about bringing side scrollers **such as Super Mario Bros** to the PC (he specifically says "we had a nintendo there, we were playing Super Mario 3, that is what we set out to do as we were making those games on there, **we wanted to bring the console experience to the PC**")

So anyway, keep in mind the game makers that end up citing other games, when you look at the "derived" game or the game it cites as an inspiration, there's no way you could say the "derived" game "ripped off" the other. The game they made and the game cited as inspiration (more so for the Commander Keen/Mario comparison than for Jetpack Joyride) are totally different. I mean these developers are smart, they developed something cool and unique, and they didn't do some blatant plagiarism such as *rip art or sprites* from other games.

Anyway the gaming community is pretty critical and will probably accuse you of ripping off 10 other games you've never played before than the inspiration you cite.

So in short, **no don't worry about citing your inspiration at a high level**. There are 10k side scrollers, and 40k fps, and 90k RTS's. If people sued each other for minor similarity in play, there would be but 3 games for us to play.

But **yes, don't blatantly rip off artwork or copy-protected stuff that anyone in their right mind would go after you for**. Don't make a clone of a game and try to pass it off as your own idea.

# Answer
> 1 votes
I should preface this by stating that I both have no formal legal training and that my statements are based on:

1. my personal, incomplete understanding of conference panels and classroom discussions of rights issues in the creative arts and digital media
2. requests I've made to individuals and organizations for the rights to use their material
3. take-down requests I've had to make to protect my own creative work from unauthorized, unattributed sharing

Due to the nature of legal issues, you'll most likely find that anyone who **does** have the legal training to answer your question with certainty will be reluctant to do so informally due to potential liability issues they face as legal professionals.

As with rights-ownership issues in many media, different content owners will have different prerogatives and will defend their content differently. Some content owners will appreciate your adulation, and others will aggressively defend their brands and content from all unapproved uses. Their options will vary based on the level of copyright and trademark protection they have sought for their work, whether you've profited from your use, and whether your use has cost them sales or reduced the value of their IP (even if that's just a trademark on the name).

The *best* way to protect yourself is to seek both legal counsel and explicit, affirmative written permission to make the reference you'd like to make.

That said, in personal practice I have sought permission on more than one occasion to share published creative/educational material, as well as to use restricted public APIs in ways not explicitly permitted in the terms of service and in every case thus far I've received something ranging from a polite acknowledgement of my permission to use their content in only the way specified by my request to grateful personal thanks for the interest and granting of permission. Likewise in making take-down requests to protect my own content I've found that service-providers who had been used to host the unauthorized content were more than helpful.

---
Tags: legal, business
---


# Question
Title: A* mouse movement javascript top-down game
Im trying to implement a\* path finding for my character movement in my game.

The game is written in javaScript along with jQuery in a canvas.

I have read up on A\* so i believe i understand what it is and how it works.

My questions:

1) do you know of any a\* tutorials specific to JavaScript and canvas? Just to get a bit more of an understanding so its concrete.

2) Once the a\* is implemented, how would i get my player to move along that path to the destination? Obviously id use the player X,Y for the start pos and the mouse click for the end pos, but when the algorithm has completed the path, how would i proceed to make the player follow that path?

Thanks for any help and advice!

# Answer
1. No I don't. Since canvas is relatively new I'm not sure you'll find one. This one is pretty good but you might have seen it already: Link
2. Once the algorithm has worked out the path, you should have some kind of sorted array/list of tiles which take the player from their current position to the target tile.

Since you are probably working with a grid of squares equal size, you can easily work out the center x and y positions of each tile in the path. So, you make the player head towards each tile in the array in turn. When the distance between the player and the center of the target tile is small enough, move onto the next tile (next tile in path array).

Moving towards the center of the tiles is probably simplest, but depending on the game you might prefer finding the closest edge of each tile to get a "direct" route through. You need to read up on vectors if you haven't used them before.

Rough pseudo code-ish example:

```
i = 0;
while(i < path.length) {
  target = path[i]; // path is array of grid tiles created by algorithm
  targetx = target.col*tileWidth + (tileWidth / 2); // col = column of tile in grid (x)
  targety = target.row*tileHeight + (tileHeight / 2); // row = row of tile in grid (y)

  // TODO:
  // calculate distance from player to target
  // set heading vector

  if(distance < 2) // if near center of target tile, head to next tile in path
    i++;
}

```
> 3 votes

# Answer
I recently implemented a\* in a game I'm working on in JavaScript, so I thought I'd try my best to answer your question. The path finding is functional in the Ludum Dare build and you can search for "findPath =" in the JavaScript file if you want to see my implementation, but it is custom for my game.

The basic idea of a\* is that you have several possible positions that something can be in, each being connected to those near it, forming a web. In a lot of cases, this is a grid of some sort. a\* is then able to find the shortest path from a starting position to a destination, if there is one, and try to do so quickly by guessing roughly how far a step will be from the destination using a heuristic before actually testing it. More possible positions will use up more memory and need more processing time. I could explain a\* in more detail, but you're just as well off doing a search to learn more.

From how you have phrased your question, it sounds like you want to create a path using images that have been drawn to a Canvas (you can correct me if I'm wrong). Unless you are only drawing collision-useful images to the Canvas, this isn't a practical approach. You will likely want to be keeping track of player positions and collision information somewhere else. Path finding is not related to the way that you are displaying an image to a user, it's more about how you're storing collision and position data. A Canvas doesn't know anything about what you put on it aside from what everything looks like when it's done drawing.

Most a\* implementations will give you a list containing steps. In the case of my game's implementation, it returns an array of grid indexes (y\*width+x), in reverse order of when they should be traveled to. It's a fairly small tile-based game, so there aren't a lot of positions to check, and it skips checking empty or impassable tiles on the grid.

You can use this path to move your player character. Change its position to the next location in the path (if the distance between the points is long, you can always smooth it out a bit), wait a bit, then move it to the second location, and repeat. You should be redrawing the Canvas (or at least the parts that changed) whenever the player moves. Waiting can be done using a timeout or an interval, but rendering is generally best done using requestAnimationFrame because it waits until the user's monitor is ready to display the image.
> 0 votes

---
Tags: javascript, path-finding, movement, html-canvas
---


# Question
Title: Is it possible for automated testing applied to Angry bird
In simple case, just the first release of Angry Bird is OK

I am thinking if the testers can automated to find out all possible routes ( removing those shooting back) to get the marks stats (and also fix hidden bugs)

thx, though this may be a very simple question here

# Answer
> 1 votes
Short answer: yes-ish, but the point of it all is rather debatable.

Yes, it is possible to run a simulation of all angles and shot strengths, and to let the physics run through, and to get some values out. There's two slight problems with this, however.

**First**: What would you consider a failure? If you are looking for crashes, that's a clear thing, but any other kind of tests would be harder to make.

How do you know if some values are wrong? Would a human watch every single iteration to make sure nothing funny happens? Or would you just set some arbitrary boundary values that are checked against ("no object may ever fly over 2 kilometers" or some such..).

If you keep the results for sanity testing, any small change in the application may change the results dramatically. If 50% of your values are suddenly different, can you say it's due to an introduced bug, or if, due to some small floating point accuracy difference, the physics simulation just happens to act slightly differently?

Let's say you're looking to stress the physics engine, and have some boundaries to check against.

**Second**: Is it really sane to iterate through *every single* possible angle and shot power? The number of iterations required is probably immense, and since the physics simulation takes some time to execute. It is still *probably* possible to test them all, especially if you throw the problem to some cloud processing service, but whether it is cost-effective is another matter.

More likely it's worth it to make some hand-crafted boundary case tests (the cases you'd expect to have problems; shooting straight up, straight right, max power, min power, etc), combined with random testing that can be left running overnight.

---
Tags: testing
---


# Question
Title: Is it viable to wrap D3D to change its API style?
I have an interest in developing games professionally and have started learning DirectX 11 to that end.

I come from a Java background, but with the recent changes introduced with C++11, I've come to like C++ a lot. Coming from Java, I find that the DirectX API reliance on output arguments and a lot of descriptor structs a little disconcerting.

I'm trying to build a framework around the API that returns values instead of using output arguments. The framework also rolls descriptors into the class (e.g. DXGI\_SWAP\_CHAIN\_DESC into a SwapChain class) and internally handles the updating that would be required for any changes. I also plan to use exceptions rather than return codes to handle error conditions.

Is such a framework viable or it just a Java programmer carrying over his coding style into C++?

EDIT: The goals I'm trying to achieve with the framework are that, I want it to rely on returning values, throwing exceptions, handling memory using C++11 and ATL smart pointers. An early iteration of the framework can be found at: https://github.com/Dolvic/DirectX-Classes

# Answer
> I'm trying to build a framework around the API that returns values instead of using output arguments. The framework also rolls descriptors into the class (e.g. DXGI\_SWAP\_CHAIN\_DESC into a SwapChain class) and internally handles the updating that would be required for any changes. I also plan to use exceptions rather than return codes to handle error conditions.
>
> Is such a framework viable or it just a Java programmer carrying over his coding style into C++?

It's certainly viable, and if it makes you more productive in the long run, then it could be a good idea. However I'd advise caution on two points:

* It does sound to me like you're suffering a little from the "culture shock" of an unfamiliar API design and rather than trying to understand it and immerse yourself in it, you're trying to *change* it. This isn't necessarily the best approach.
* Some aspects of the D3D API are that way due to convention (the COM-style API it uses is not an uncommon API design, even if it seems unusual to you), but some are there for very good reasons. Be aware that you could be introducing some subtle performance issues in your transformations of the API in the name of making it "easier" to use. These performance issues *probably* won't be serious enough to matter, but then again they might be. It's hard to say beforehand.

Finally, wrapper-style APIs don't tend to be terribly interesting from a professional experience standpoint (for example, were you to submit the code to me as part of a job application, I'd probably reject you).

I would advise instead that you try to create an API that builds upon D3D but itself exposes a higher level of abstraction than D3D does -- in other words, don't create something with a 1:1 mapping of every interface in D3D to your new "improved" API style, but instead combine related interfaces (employing them in their native style to help you learn them) and expose something more useful. Two such examples might be:

* Creating a "model" interface that deals with the vertex and index buffers, textures and shader references necessary to manipulate and render a single logical model to the screen.
* Creating a "renderer" interface that abstracts away the details of device, context and swap chain set up and management.
> 7 votes

# Answer
It is viable, DirectX is low level and COM biased, most of people are not familiar with it. Most of the code you will add will be used only on Creation/Initialization phase, they probably wont hurt the performance (and even if it hurts, the gain you will have in productivity will "pay the price")

Take a look at Hieroglyph 3.

The creator did some of the things you are willing to do (actually it did lots of more things ), and it worked pretty well !!!
> 1 votes

---
Tags: c++, directx
---


# Question
Title: How to make a 3d beam effect with XNA 4.0?
Do you know any demo or tutorial to learn to make a 3D Beam effect?

I have learn to make a 2D laser by simply using a texture and moving it thru screen. But I am a little bit lost while trying to do it in 3D.

After googling I've found several examples, but they are old, not working or made for an older version of XNA.

As a visual hint, what I want to achieve is some 3d beam effect similar to this photo:

# Answer
> 2 votes
Not sure if is exactly this what you are looking for !!

http://www.catalinzima.com/samples/lightning-sample/ (in the end of the comments there is a link for a Xna 4.0 version) if you adjust the provided setting, you will be able to create an effect similar to the one you posted.

---
Tags: 3d, xna-4.0, graphic-effects
---


# Question
Title: In UDK, how and where do I script to enable Alt-F4 for exiting game?
By default, Alt-F4 does not work in a UDK game.

How would I go about adding unreal script to cause the game to exit to desktop upon Alt-F4?

# Update

This is what I've tried:

```
; Primary default bindings
.Bindings=(Name="F4",Command="exit",Alt=True)
.Bindings=(Name="F10",Command="ToggleInventory")
.Bindings=(Name="SpaceBar",Command="GBA_Jump")

```

# Answer
> 2 votes
That would be your DefaultInput.ini. If you add something along the lines of `+Bindings=(Name="F4",Command="exit",Alt=True)`, that should do the trick. The next time you run the game, the UDKInput.ini will be rebuilt using a combination of DefaultInput.ini and the BaseInput.ini in Engine\Config.

---
Tags: udk
---


title: What is the color value of daylight?

text:
# Question
Title: What is the color value of daylight?
This is a very short question. I want to implement ambient light in the color of daylight from the sun. What is the color value of sun light?

# Answer
That depends. Our perceived color of the sun depends on a variety of factors -- the color we observe is due primarily to the scattering of the light in the atmosphere, so the content and quality of the atmosphere has an impact along with the sun's relative position in the sky.

Wikipedia's article on color temperature has some reference values for the sun, but does note that they may vary wildly. However if all you're after is a quick-and-dirty color value, one of them may suffice.

Practically speaking, the formula you use to apply this color in your lighting calculations will have a large impact on the resulting scene as well. Simply modulating the color into your lighting calculations as an ambient term might result in overly orange or tinted renders -- in many cases, you'll probably want to either use something more complex to make the impact of the sunlight color subtle, or you'll want to do nothing at all (if your scenes are always in "broad daylight" you don't really need to involve simulation of the sunlight).

Especially if you're going to have the sunlight color vary based on the time of day (or weather conditions) you'll also want to consider rendering your skybox appropriately. Papers such as Preetham/Shirley/Smit's's Practical Analytical Model for Daylight are a good place to look at for reference and inspiration. You can also check out this repository of sky-rendering-related links.
> 6 votes

# Answer
At midday, RGB of (1,1,1) or plain white light.

At sunrise, a little more blue looks pretty good. Tweak until you have good results.

At sunset, a lot more red looks good. Tweak as above.

At evening or night, go with a dark blue. This isn't really based in reality but it's common enough.
> 6 votes

---
Tags: color, lighting
---


# Question
Title: Best way to allow a user to Control Body in Box2D
I am working on a simple game and I am deciding how I should let users interact with the world. I really have 2 options,

1.) When the user moves an object I apply a force to the body

2.) With each move iteration I "move" the body by setting position.

Which is "better" or am I looking at this wrong entirely and should I be doing something different?

Also, does it matter if I want to keep the object stationary when it is hit by another body (I am assuming this means I will need to use static body which leads me back to #2)?

Thanks

# Answer
I wouldn't recommend the static body solution, what I've done is something very similar to this answer, but when you apply horizontal forces reduce the ground friction.

Now you have to think carefully what are the types of objects you will have in your world, because you said:

> I want to keep the object stationary when it is hit by another body

Well the terrain is a body, and you want that your character interact with the floor, if you want your character not be affected by dynamic objects, you can set its weight with a very high number, which isn't the same that set it static, because the kinematics will still apply, but other objects will bounce on its surface.

Another more advanced solution, without change the weight, is that you can detect the character collisions and change its output, so you character won't react to collisions with other objects.

In any case, if you want to check if the character is in contact with the floor, you need to detect the character collision.
> 2 votes

---
Tags: box2d
---


# Question
Title: Deciding when to switch focus between UI elements
I've been coding a simple logic game recently and there is a UI decision that has been bothering me.

Since certain blocks of logic are going to be used across many levels (e.g. logic to reverse the input queue) I decided to add a template feature, allowing the user to name and save blocks of logic.

As it stands, I simply have a text field in which to enter the template name. While the game is primarily played with the mouse, some keys are used as controls (w, a, s, d, space, delete). This creates the requirement of deciding when to take focus away from the text field. Some decisions are obvious (e.g. when the user presses the `New Template` button and the template is created) but others, not so much. For example, the user clicks the text field, then decides not to create a template.

While one option is to simply pop up a dialog and remove the text field from the main UI altogether, I was trying to avoid this. Does anyone have any thoughts on what would be a good trigger for taking focus away from the text field? Or do you think I should just drop the field and go with the dialog?

# Answer
> 3 votes
I find it's typically best to go with what people expect.

In this situation I think the typical user would expect the text field to activate when clicked, take any keyboard input given (including the controls you use in game), then loose focus when the user clicked somewhere else or pressed enter to submit the changes.

If the user wanted to cancel the action, they could hit ESC or you can present a cancel button when the text field is active.

---
Tags: java, gui
---


title: GLSL light coloring blocked surfaces

text:
# Question
Title: GLSL light coloring blocked surfaces
I have created a very simple lighting shader. It currently only supports point lights, but it lights up surfaces that are completely blocked from the light. I know why, but I want to know how I can fix it. I was thinking of using a form of shadow mapping to darken those areas, but shadow mapping is difficult for me to understand and has very major performance issues. I was hoping for a more elegant and efficient version, even if it is not as nice.

Until something like that exists, I need a nice, efficient way of checking to see if a fragment or vertex is visible and computing things from there. I would also like to add that I intent to support semi-transparent objects, which should block light based on and alpha value.

The things I want:

* Fast (25+ fps with the modified shaders, I currently run at 82)
* Easily modified to incorporate more lights (three or four at most, probably).
* Support for edge smoothing (user can enable it, but will lose performance)

The things I do not want:

* Pulling information from the GPU during rendering (view stuttering is always visible when that happens)
* Visible/noticeable moving of lighting when scene is stationary (like the light is moving when it really isn't, due to randomizing)
* Expensive operations when the scene first renders.

I do not expect anybody to implement these things - just to leave room and maybe a comment where these would be done. I know this is the "holy grail" of rendering when combined with bump maps and such, but if you tone down the quality a bit, I hope it is possible. I may have to do some extra work on the CPU, but that is acceptable.

Now for the shaders I currently have working:

Vertex shader

```
varying vec4 color;
varying vec3 normal;
varying vec4 position;

void main (void) {
    color = gl_Color; // pass color to the fragment shader
    normal = normalize(gl_NormalMatrix * gl_Normal); // calculate useable normals from the basic normal data.

    gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; // set position
    gl_TexCoord[0] = gl_MultiTexCoord0; // set texture coordinates
    position = gl_Vertex; // pass gl_Vertex to the fragment shader for light calculations.
}

```

Fragment shader

```
varying vec4 color;
varying vec3 normal;
varying vec4 position;

uniform sampler2D texture;
uniform vec4 light; // position of the light, same coordinate system as non-transformed objects

void main (void) {
    vec3 vector = light.xyz - position.xyz; // get the vector needed to determine length
    float distance = sqrt((vector.x * vector.x) + (vector.y * vector.y) + (vector.z * vector.z)); // determine length
    vec4 final = color; // set color

    final.xyz *= (1.0 / distance); // calculate light intensity on pixel

    gl_FragColor = final * texture2D(texture, gl_TexCoord[0].st); // multiply by texture color
}

```

I can do a lot of extra cool things with this current code, such as giving lights their own colors and giving objects their own material properties, but that is not the point now. I just want basic code, preferably without needing more buffers and shaders, to determine visibility. From my research, it sounds like the stencil and depth buffers may be of use here, and they already setup, so they may be a better way to do it.

I can not stress enough that I only need the bare essentials here - nothing overly fancy. Thanks in advance for your help.

# Answer
Shadow mapping is the way to go. There is no way to have shadows without adding some more shaders and passes to rendering. GPU rendering works by taking a list of triangles to render, and it does not have a list of the other triangles/occluded in the scene; even if you added them in a buffer, querying them would be much slower than shadow mapping on today's GPU hardware. You aren't going to find a simpler method of shadow generation that actually works than shadow mapping.

Some good tutorials are at:

http://fabiensanglard.net/shadowmapping/index.php

http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-16-shadow-mapping/
> 1 votes

# Answer
You do not use the normal at all, so nothing will tell the light calculation that the current fragment is facing away from the light. Instead of this:

```
final.xyz *= (1.0 / distance);

```

You can try this, using Lambert’s cosine law:

```
final.xyz *= max(0.0, dot(normalize(vector), normalize(normal))) / distance;

```

Also note that `length(vector)` will do exactly what your `sqrt` call does.

**Edit**: another problem is that `vector` is computed in object space, whereas `normal` is in view space. This page has more information. I suggest doing the light calculations in view space (as the fixed-pipeline OpenGL does), therefore multiplying `position` by the view matrix **and** providing `light` in view space. Instead of:

```
position = gl_Vertex;

```

You need:

```
position = gl_ModelView * gl_Vertex;

```

You should also multiply `light` with the *view matrix*, but that is more easily done in the C/C++ code. You will need to change a lot of things in the client code anyway, because most of the `gl_*` builtin variables are deprecated and you need to send them yourself.

It seems to me that you can find the kind of information you are looking for in the book “OpenGL 4.0 Shading Language Cookbook”. As the name suggests it targets GL 4.0, but most of the shaders, especially the ones covering lighting, only use backwards-compatible language features. It’ll also teach you to do shadows, which isn’t as difficult as you appear to think, and to get rid of deprecated features such as `gl_TexCoord`.
> 1 votes

---
Tags: opengl, collision-detection, glsl, shadows, depth-buffer
---


# Question
Title: Why do MMORPGs still use multiple servers?
MMORPGs, some MOBAs like League of Legends or even StarCraft 2 usually force you to pick a server. Usually they are US, EU and SEA, in MMORPGs many per location. I can see that that was necessary a few years ago, but now with the advent of AWS and similar offerings that allow you to seamlessly scale your "server-power", why are there still separate servers?

My train of thought is like this (using Star Wars: The Old Republic as an example): - You are always on one planet, an isolated "instance" from other planets. - If there are too many people on one planet, SW:TOR creates a new instance of the world and puts players in there. - If you leave the world / switch instances you have a loading-screen

So why can't the game create an instance for this planet. This instance (and only this one) has your current data in its database and manages x players. As soon as x-50 players are on this instance, a new server will fire up and new people will spawn on that instance. The 50 spots are reserved for switching to your group, etc.

There could be an instance for all three major regions to keep the latency low, but it would allow you to still play with other players from i.e. SEA if you can live with a 140ms delay (which is still nothing imho).

Whenever you switch an instance or travel to another world, your current server gives all your data to the next server, making sure you don't need one big centralized database. You could still have one that gets updates periodically for analysis purposes.

When you log off or the servers loses connection, the data could then be transferred into a massive database that is optimized for storing the data. The instance servers can then be optimized for high throughput.

Is there any particular reason this will not work? Are there other problems I am missing?

# Answer
> 13 votes
> MMORPGs, some MOBAs like League of Legends or even StarCraft 2 usually force you to pick a server. Usually they are US, EU and SEA, in MMORPGs many per location. I can see that that was necessary a few years ago, but now with the advent of AWS and similar offerings that allow you to seamlessly scale your "server-power", why are there still separate servers?

AWS is not as obvious a solution as it seems. It can be expensive, in some cases more so than using in-house data centers (for a publisher the cost of these may be amortized across multiple products, for example). Additionally, there could be concern about storing sensitive binaries and logs on hardware outside of one's control. Finally, actual computation power is not always the reason for segregating the "server" population in MMOs.

> My train of thought is like this (using Star Wars: The Old Republic as an example): - You are always on one planet, an isolated "instance" from other planets. - If there are too many people on one planet, SW:TOR creates a new instance of the world and puts players in there. \- If you leave the world / switch instances you have a loading-screen

Guild Wars 2, in fact, does something very similar to this. Maps are simulated by individual server processes, and overflow instances are created as needed based on the map population cap and some heuristics for the performance of the map.

Guild Wars 2 has two major data centers, one in the US and one in Europe -- there is some cross-chatter between those data centers (primarily for the trading post and commerce systems) but in general they exist in that configuration so players in Germany, France, et cetera don't have to suffer the higher latency to the US game servers. Within the data center players are sorted into "home worlds" (or "shards" in vernacular terms); but one of the reasons this is done is to minimize the number of players that a client can see and need reported to them. The client side aspect of that problem won't be solved by scaling out to more server hardware. The server-side combinatorial explosion of additional reporting paths might be, but not cheaply (and consequently it tends not to be worth it since the client-side performance is still a problem).

> Is there any particular reason this will not work? Are there other problems I am missing?

You're missing quite a few things, but they're mostly details (and I won't explain how we handle them anyhow since they're considered trade secrets) not relevant to such a high-level, overview-type of question. I think the biggest flaw in your proposal is trying to hand off player data to the new server when a player transfers. That is a complex problem that won't scale well, it is probably better in practice to actually have that player data on a centralized system of servers. It's quite doable if you don't use those databases and the primary runtime record store for the data.

# Answer
> 7 votes
Mostly it's about latency.

Firstly, having a server geographically near to you cuts down on latency. If the server is on the other side of the world then you'll see more latency than if the server is just a few hops away.

Secondly, services like AWS are not designed for real-time work. They're designed for high throughput at the expense of a bit of latency. If your web page takes 250ms longer than usual to load on one occasion, nobody cares, but if your game takes 250ms longer than usual to process a message, gameplay can be seriously affected. This is why MMOs are almost always hosted on dedicated hardware.

But it's also about game design. If you make it seem like everybody is in the same world but have to split a zone when it gets too full, people get frustrated that they can't find their friends in the designated meeting spots. This sort of problem would extend to guilds, mass PvP battles, etc. Players are used to instances these days but there are certain areas that are expected to be shared. If you have completely separate servers then at least there are no surprises here.

Finally, there are other technological issues to consider. Even if each instance is fairly isolated from the others, there are usually still various services that need to communicate across them. Cross-server communication is difficult to do well in real time software and has led to various exploits and bugs on MMOs in the past. In particular handing off authoritative player data from one to the other is risky. Therefore developers often err on the side of caution and have clearly delineated boundaries between servers, reducing the amount of traffic that needs to cross them.

# Answer
> 3 votes
actually I believe the answer is *not* network or architecture related but rather game related, usually in this type of games there are events, and these events are timed according to the most comfortable timeframes for the people who play on the server, and that is usually related to the timezone where people live, hence EU and US, etc.

Another reason is to create a separation between worlds so that if there's a group that's too strong they won't mess up the game for everyone playing, and you can always move to a world less "challenging".

On the server CPU capability side, although today's machines are quite strong, there's always a limit to what one machine can handle, and so creating a separation between worlds is necessary to protect the game from overloading, and let people choose which world they want to play in so they can play with their friends. Scaling horizontally is not just a matter of having machines, you need your application to be able to work in a horizontally scaled architecture, and that's not so easy when you have thousands of "actions" going on concurrently with possible influence on each other, and need to synchronize everything. I think it would be very difficult to do that across several machines.

# Answer
> 2 votes
What's wrong with auto-instancing? When a location gets too populated, you just put the 1000 players into 10 different instances.

The problem with that is that online games are all about the community. Imagine you arranged a meeting with people you met before, and when you are all there at the given time you don't see each other because you are all in different instances? That's annoying and it breaks immersion.

How can this be prevented? It could be done by putting each players in the same instance at all times, so that when you meet another player once, you can be sure to meet this player again when you are both in the same location. You will never meet those players who are assigned to other instances.

But what when you want to meet someone from outside the game? Like a real-life friend you invited to play the game with you? In order to allow that to happen, you would need the ability to choose the instance when creating your character. Like from a list of instances with easy to memorize names. Unfortunately, the name "instance" seems confusing to the average user. They aren't used to that word. Wouldn't it be better to use a term they are used to? A term like... **Server**?

---
Tags: architecture, mmo
---


title: Non-square Isometric tiled maps

text:
# Question
Title: Non-square Isometric tiled maps
I'm beginning to make a tile-based 4x game, but I ran into a conceptual issue: My inspiration for this game are the Civilization games, particularly Civ 2, and I noticed something I was interested in mimicking, but I was wondering how it was done.

This is that while the map is isometric, it is not square. I was wondering how it does this. My first thought would be to use an array, but then you have the corners being basically unused space.

To give an example of what I'm talking about:

One idea I have is that there are really two arrays, and whenever a diagonal is made (which would be up, down, left, and right to the player), it moves on one array, and any non-diagonal movement (which to the player is diagonal) moves to the other array.

This is illustrated by this picture (the mountains are one array and the hills are another array):

# Answer
I would follow this guide which works exactly the same for isometric as hexagonal.

To summarize. You want to treat the map like a traditional square map and offset the tiles visually. Then account for the different movements with a simple switch based on if the tile is even/odd.
> 2 votes

---
Tags: tiles, isometric
---