# Question
Title: XNA Framework Reach profile does not support separate alpha blend
Yesterday I released my app 'Pic Words' to the windows phone store. It is an Silverlight/XNA app that runs on Windows Phone 7.1 & 8. I have BugSense incorporated into my app. Today I started receiving a lot of crash reports emanating exclusively from the **8.0.10211.0** version of Windows Phone 8. I could not replicate the issue since I do now currently own a Windows 8 phone and the emulator is running OS version **8.0.9903.0**, which I don't think can be changed. The error from BugSense is as follows:

**XNA Framework Reach profile does not support separate alpha blend. BlendState.ColorDestinationBlend and AlphaDestinationBlend must be set to the same value.**

Stack Trace:

at Microsoft.Xna.Framework.Graphics.ProfileCapabilities.ThrowNotSupportedException(String message, Object arg1, Object arg2) at Microsoft.Xna.Framework.Graphics.BlendState.Bind(GraphicsDevice device) at Microsoft.Xna.Framework.Graphics.GraphicsDevice.set\_BlendState(BlendState value) at Microsoft.Xna.Framework.Graphics.SpriteBatch.SetRenderState() at Microsoft.Xna.Framework.Graphics.SpriteBatch.End() at GlobalEngine.Base.SpriteBatchManager.ResumeSpriteBatch() at GlobalEngine.Base.SpriteBatchManager.Begin(SpriteBatchParams spriteBatchParams) at GlobalEngine.Base.SpriteBatchManager.Begin(Rectangle scissorArea) at GlobalEngine.Base.SpriteBatchManager.Begin() at FourWords.Screens.GameScreen.Draw(Color tint) at GlobalEngine.ScreenUtils.ScreenManager.Draw(Color tint) at GlobalEngine.Base.Engine.Draw() at FourWords.GamePage.OnDraw(Object sender, GameTimerEventArgs e) at Microsoft.Xna.Framework.GameTimer.RaiseDraw(GameTimerEventArgs gameArgs) at Microsoft.Xna.Framework.GameDispatcher.RunFrame() at Microsoft.Xna.Framework.GameDispatcher.OnTick(Object sender, EventArgs e) at MS.Internal.DirectRendering.OnGameUpdate(Object sender, EventArgs e) at MS.Internal.JoltHelper.RaiseEvent(IntPtr target, UInt32 eventId, IntPtr coreEventArgs, UInt32 eventArgsTypeIndex)

GlobalEngine is just my library of basic classes like screen management and so on. SpriteBatchManager is a class I created also for managing the spritebatch.

I Begin the spriteBatch with the following parameters:

SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None

Additionally, I manipulate the graphic device as follows in the GamePage.xaml:

```
protected override void OnNavigatedTo(NavigationEventArgs e){
    // Set the sharing mode of the graphics device to turn on XNA rendering
    SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);
    SharedGraphicsDeviceManager.Current.PreferredBackBufferFormat = SurfaceFormat.Color;
    SharedGraphicsDeviceManager.Current.ApplyChanges();
    //other unrelated code....}

```

I could not find any help from searching online about this issue and would appreciate any advice on fixing it. Thanks.

# Answer
I think the issue is possibly a bug in the older versions of Windows Phone 8.

The blend state seems to be borked so you need to create a custom one that you know works.

```
private BlendState alphaBlend = new BlendState()
{
    AlphaBlendFunction = BlendFunction.Add,
    AlphaDestinationBlend = Blend.InverseSourceAlpha,
    AlphaSourceBlend = Blend.One,
    ColorBlendFunction = BlendFunction.Add,
    ColorDestinationBlend = Blend.InverseSourceAlpha,
    ColorSourceBlend = Blend.One,
    BlendFactor = Color.White,
    ColorWriteChannels = ColorWriteChannels.All,
    MultiSampleMask = -1
};

```

This is a direct copy of a functioning BlendState.AlphaBlend from a working Reach profile Silverlight application I have.

You should declare it in the class that needs it, in the constructor or Initializer as it only needs to be done once. Then change your function from this ...

```
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None)

```

... to this ...

```
spriteBatch.Begin(SpriteSortMode.Deferred, this.alphaBlend, SamplerState.LinearClamp, DepthStencilState.None)

```

This way you avoid using the built-in one that seems to have issues, and instead you use one that has been tailored to work. This is definitely a workaround but unless you want to force your players to update, it's the only solution.
> 1 votes

---
Tags: xna, c#, xna-4.0, windows-phone-7, windows-phone-8
---


# Question
Title: How complex should enemy AI be in a dnd-alike?
I'm writing a text-mode (python + ncurses), turn-based rpg based loosely on 3rd edition D&D and Neverwinter Nights (the PC game) rules. It's not going to be a full implementation, but 'in the spirit' of them. I already have quite a bit of the basics in place; movement, a few base classes and races, rule-based encounters (shop/npc/monster X shows up when condition Y is true), dynamic generation of monsters, player and enemy stats and random, levelled equipment etc. It's enough to start moving around a basic world, talking to people, examining objects and location and now I'm moving on to (melee) combat.

I'm interested in what people would expect of an algorithm that co-ordinates the computer-controlled attacks of an enemy party against the player. How smart should the computer controlled enemy be (in my implementation the player will take control of each of his own characters in turn, and they wont be AI controlled, but the enemy party will - attacking, spell casting etc at-will).

For example; if an enemy character initially chooses a random pc from the players party on round 1, should that enemy continue to attack the same target in subsequent rounds. How about if another pc then attacks that enemy? What if the enemy is unable to cause damage to that pc (ie say the pc has something crazy like damage reduction 100/+5 - should the programme know in advance?), should they switch to another in the players party?

Has anyone implemented anything similar and would be able to provide any pointers?

# Answer
So what I've decided to do is a combination of the suggestions here and from Strategies for monster targeting AI in a turn-based combat system.

What I will do is have each enemy character scan the available player characters and calculate three scores:

Target Threat Rating

* Difference in level between the target and the enemy character
* Melee targets get extra points for two handed or dual-wielded weapons, weapon level and STR bonuses
* Spellcasters get extra points for their highest spell level and INT bonuses
* Bonus points for the number of extra attacks per round
* Bonus points for every N levels of armour class
* Bonus points for every N% of HP remaining

Target Value

* Points scored for being a party leader
* Points scored for every N% of HP lost
* Points scored if this character is actively providing buffs to the party

Target Difficulty

* This will represent how potentially difficult the target will be to damage from either melee, magic, ranged or touch attacks.

In addition, I plan on using the INT/WIS rating of an enemy creature to decide if it can take advantage of the three ratings; creatures with lower intelligence may only use target value, for example, whereas more intelligence will bring target threat and target difficulty in to the mix. Therefore more intelligent creatures should be able to decide if a more threatening player with a high value is worth attacking (and which attack type to use).

Changes in the ratings between rounds may affect which character the enemy attacks - though some element of 'stickyness' will be used to prevent flip/flop between characters on every turn.
> 3 votes

# Answer
One thing to consider is how "smart" the unit is. You seem to be framing the question as if the AI is the dungeon master, and he is playing the NPCs verses the player's party. A good DM wouldn't always play an NPC's combat up to the ability of their character sheets.

For example a brutish orc might attack the first thing it sees even when that's not the best battle plan. All unit's in an opposing battle might not have line of sight on each other or reliable communication. In your example, an attacking fighter wouldn't know about the damage reduction effect (as he hasn't detected the magic auror granting the effect). A rule like, if my attacks aren't working, I should fall back seems reasonable.

Having DMed quiet a few games of DnD I can tell you that enemies don't need much AI to seem realistic and challenging. Even something as simple as compound actions like pulling back to reapply a buff seem much more complex to the player who tends to have his mind on what his battle plan is more then what the opponents could be.
> 2 votes

# Answer
Since it is a DnD game I would suggest going for a bit of randomness. I have implemented a turn based rpg battle system (1 player vs N monster and something the player has to defend) and the algorithm I thought of was the following:

1) Store different strategies in an array (For example focus on hero with physical attacks, focus on spell-caster, attack different targets, fall back, use special abilities)

2) Every N turns change the behavior of all units to one of the options in the array. That way you give the idea that they work as a team.

3) Every turn change the behavior of one of the enemies (that way they will look more "alive")

4)Change the behavior of all units before half of them have gone through point 4 so they don't look like they are acting on their own.

Hope it is useful to you.

Ps if you are going to implement difficulties, just add more elements of the array which have the worse choices for the player, for example add 3 times 'focus on the fragile part of the team' instead of one.
> 1 votes

---
Tags: game-design, ai, rpg
---


title: How to create a text-based game?

text:
# Question
Title: How to create a text-based game?
I would like to create a text-based game. As simple as that.

I have some understanding of the coding that needs to go into it as I do know a fair amount of JavaScript and I can do it in the JavaScript console in Google Chrome. But I would like to create a stand alone game that once it has been downloaded, that's it. It doesn't need a connection to the internet or anything. But I honestly don't have any idea on how to make a 'Start Screen' or anything like that.

Any links or guides that you guys have found/made to make text-based games would be grateful as all the things I've found have helped me in absolutely no way.

Sorry if this is the wrong website to ask this in, but it seems to be the best one for game dev. questions! ;)

# Answer
# Short answer

Asking how to make a text-based game is essentially asking how to program. Learn to program.

# Long version

## Learn programming

Writing text-based games is a good way to learn.

This is the hard part. This is going to take time.

The first thing any game needs is a loop, input, output and something that converts input to output. This is what that would look like in Lua:

```
-- Process input into output
function process(i)
    if i == "hi" then return "Hi to you too, player." -- Player greets
    elseif i == "exit" then return -1 end             -- Player wants to quit

    -- ...add more cases here...

end

-- Main loop
while true do                     -- loop over these things
    local input = io.read()       -- read input
    local output = process(input) -- process it
    if output == -1 then          -- if it was a quit instruction
        os.exit()                 -- quit
    else
        print(output)             -- show output
    end
end

```
1. Figure out what that is doing and why.
2. When you realise you need *state*, look into variable assignment.
3. When you realise you need *collections of things* like an inventory, look into *data structures* like arrays and lists.
4. By then, you essentially know how to program.

Good luck!

For making a full game, you may want to write Python or JS instead. By the time you know how to program, it shouldn't matter much. Their syntax is very similar and the ideas always matter more than the syntax.

## Same in JS

Since you know JS, here's a similar seed for a JS-based text adventure:

```
<html>
<head>
<title>Sample game</title>
</head>
<body>
<form onSubmit="go();return false;">
<input id="input-textbox" type="text" />
<input type="submit" />
</form>
<textarea id="output-textbox" rows="20" cols="50"></textarea>
<script>

textIn  = document.getElementById("input-textbox");
textOut = document.getElementById("output-textbox");

function process(input) {
    if (input == "hi") { return "Hi to you too, player."; }
    else if (input == "exit") { return "No."; }
}

function go() {
    var input = textIn.value;
    textIn.value = "";
    var output = process(input);
    textOut.value += output + "\n";
}

</script>
</body>
</html>

```

JSFiddle is handy for developing HTML/CSS/JS sketches and sharing them around. MDN and WebPlatform are my favourite web-dev resources.
> 3 votes

---
Tags: graphics, javascript, software-engineering, text-based
---


# Question
Title: How can I determine an appropriate frame count for various fighting game animations?
I am currently starting to outline a fighting game I'm doing with a friend. The biggest obstacle for me now is determining frames for every move.

How can I determine how many frames should a quick jab have, a grapple, combination, how many frames of no-action should be allowed between one and second button input for a combo, et cetera? Below is basically the only thing I found:

> Startup frames (also called Impact frames) are the time before the move actually makes contact with your opponent, Active Frames are the frames that a attack would occur, and Recovery frames are the time after the hit. You cannot block during all the time intervals, but getting hit during the Impact frames hurts more and can put you in more funky stuff like stuns or even a juggle, depending on the move that hit you.

# Answer
> 2 votes
Haikukane from the discussion I posted on /gamedev on reddit posted a brilliant answer, the whole discussion there is nice, but I'm not sure wether linking to gamedev SE is allowed so I wont do that. Here is his answer tho:

> Fighting game player here. For your FASTEST CHARACTERS, The "jab" should have a 3 frame start up, 1 or 2 frames of active time, and 2 frames of recovery. Slower or longer range characters should have incremental increases by 1 or 2 frames on one of those quantities (sometimes two quantities if the move's qualities are strategically advantageous).
>
> Also note you will need to calculate frames for on-hit and on-block. That goes into coding more so than animation, but its important to match the look of moves with the composition of their frame animations (I.e. strong moves have "heft," fast moves have little impact). Please refer to the animations of Darkstalkers 3 for some of the best 2d animations in fighting game history.
>
> If you strictly want to look at frame data (and you really should to understand that the frames are literally how the characters feel) start with Street Fighter IV data. Ryu is a balanced character and is often used as the median for comparison with other characters. Chun Li is a character with both fast moves and hefty moves, due to her limited combo potential (sometimes she is referred to as a zoning character). Cammy has almost all fast moves, but limited range, due to her high combo potential. Lastly I would take a look at T. Hawk for a stereotypical grappler (aka slow) set of frames ( I would avoid coding around zangief's data, because his moves would easily make him over powered depending on the systems in your game).
>
> Grapples: between 3-5 frames of startup for throws, depending on what other moves you want them to counter in your game engine (3 = super strong, should be low range; 5 = medium range, easier to escape. SFIV uses 4 frame startup, but adjusts the throw escape times depending on the character). Active I suppose would be the throw animation, which is at your discretion. Dynamic is best! Use up to a full second and a half if you think of something really cool! Recovery should be long, around 10-14 frames, again depending on how powerful you want them to be. Combo's: The frames are entirely dependent on the frames and hit stun of the individual moves used within the combo. Basic combo systems emphasize low numbers of slower moves that have more individually powerful effects (SFIV), while faster combo systems emphasize high numbers of moves that easily chain into each other. To successfully understand how combo's work (and sorry if this is redundant) please look up the following terms: cancels, links, chains. Frames of action between the moves of a combo: This is essentially automated as it is the blank time created between the intersection of one move's recovery time, the next move's start-up time, and the hit stun the opponent is experiencing. If you try to pre-program static time into your characters, they will feel extremely stiff.

Additionally, this resource was extremely helpful.

# Answer
> 0 votes
It can actually be a mistake to put too many frames into a punch- or kick animation. Just having two phases - limb-drawn-back and limb-extended, works surprisingly well.

Animating the punch with multiple phases between these would make it look smoother, but also slower and will make it lack impact. When you feel you need to improve the quality, add some in-between frames between the normal standing pose and the prepare pose, and then some between the extended-pose and back to the standing pose.

For further reading, here is a tutorial about how to animate attacks. It focuses on pixel art while flash is usually more vector-oriented, but most of it is transferable.

Another recommendation: don't just improvise, work with references. Look at some martial arts videos to get a feeling for posture and balance when martial artists perform their kicks and punches.

---
Tags: game-design, animation, graphics, flash, fighting-game
---


# Question
Title: Precalculate the position of a rotating Aircraft
To start honestly, this question is probably mostly handling math. But thats only the road I tried to go and failed miserably, so maybe theres a much more simple way to do.

Ok the game situation is pretty simple: A 3D space game with nearly no constraints. I don't care about physics in this game, besides from collision.

There is an aircraft (or actually more of them) that gets moved forward every frame according to it's speed and the delta time. The movement of the aircraft occurs according to its own z-Axis. Before the translation the aircraft gets rotated, too. First around it's y-Axis and then around it's x-Axis. The result is a simply controllable aircraft.

Here some code for you:

```
void Update()
{
  //Rotate left/right
  float h = HORZ_SPEED * paramX * Time.deltaTime; //HORZ_SPEED is a fixed property of the aircraft, paramX an input value
  Quaternion deltaRotation = Quaternion.Euler(Vector3.up*h);,
  rigidbody.MoveRotation(rigidbody.rotation * deltaRotation);

  //Vertical rotation
  float v = VERT_SPEED * (-1.0f) * paramY * Time.deltaTime;
  deltaRotation = Quaternion.Euler(v,0,0);
  rigidbody.MoveRotation(rigidbody.rotation * deltaRotation);

  //Translation
  rigidbody.velocity = this.speed * transform.TransformDirection(Vector3.forward);
}

```

I simplified it a bit, but it's not really much more to that. The problem now is: I want to predict this movement.

For different AI issues like collision avoidance and pattern recognition, I would like to calculate with constant parameters `v` and `h` and `speed`, where my aircraft would be at a point in time X seconds in the future.

What I tried is calculating it the hard way, starting with a start position of object axes, speed and rotation per second and constructing transformations and positions for a few frames progress, hoping it would collapse to a simple pattern. But I didn't find it.

If got the strong feeling that this kind of movement should form a simple pattern like a circle (ok, not soo simple) or an ellipse that I can calculate through a few variables. But I can't seem to make my mind up what that pattern should be and how I can calculate it's characteristics out of the data I have.

EDIT: What I managed to calculate is the transformation the local unit vectors take each frame:
e\_z -\> e\_y * sin(a\_y) + \[e\_z * cos(a\_x) + e\_x * sin(a\_x)\]\*cos(a\_y)
e\_x -\> e\_x * cos(a\_x) - e\_z * sin(a\_x)
e\_y -\> e\_y * cos(a\_y) - \[e\_z * cos(a\_x) + e\_x * sin(a\_x)\]\*sin(a\_y)

On the right all unit vectors are used in their state of the last frame. a\_x and a\_y are the rotation parameters for the x resp. y axis:
a\_x = VERT\_SPEED * paramY
a\_y = HORZ\_SPEED * paramX

# Answer
Provided your aircraft speed is constant, you can "easily" compute a closed form trajectory.. but you have to renounce quaternions and think in terms of spherical coordinates. Since the aircraft velocity vector (when normalized) lies on a sphere, its orientation is thus describable by a parameterization of the sort:

`x(t) = sin(t0 + k1 t) sin( f0 + k2 t)`

`y(t) = cos(t0 + k1 t)`

`z(t) = sin(t0 + k1 t) cos( f0 + k2 t)`

When you know the tangent field of moving particle, mathematically you are assured you can recover the trajectory (see the fundamental curve theorem). you do know this field since the assumed parameterization is the above one. Just substitute `k1` and `k2` for your `HORIZ/VERT_SPEED` constants and `t0/f0` for an angular offset (what were the two airplane angles when you started your AI trajectory estimator).

You ended up with a parameterization of the velocity vector in terms of *time* `(t)`. You need to integrate this velocity field from `t_start` to `t_end` and get the exact location of your airplane, provided the speed is constant. (You, of course, need to multiply the velocity by that speed scalar to account for higher or lower speeds - this is unit velocity as given above!). Integrating `∫(x(t),y(t),z(t)) dt` can be done component wise and for that, if you're lazy like me or forgot much of the calculus tricks, you can use http://integrals.wolfram.com/. Once you get the primitive expressions, use those to find the position (via the fundamental thm of calculus ...)
> 1 votes

---
Tags: mathematics, algorithm, movement
---


# Question
Title: Visual artifacts on long distance on plane
I'm making a voxel game in XNA, and have filthy visual artifacts on long distances.

I use 2048\*2048 atlases.

I'm already using mipmaps and 16x anisotropic filtering.

I've read this blog post, but I'm not quite sure that this is the problem.

This is how it looks like:

**UPD:**

The atlas I'm using looks like this:

The topmost left square is used on the screenshots. I'm using XNA Content Processor mipmap compiler to generate mipmaps.

Every cube on the screen is separate, there is no gigantic cubes.

Does anybody have a clue what might it be?

# Answer
This problem happens because you're mixing atlasing with mipmapping. Don't (naively) do this.

I've previously explained it in here, and with more detail in here.

In most cases, you either mipmap, or you atlas. For your case, you most likely want to mipmap instead of atlasing (which is most useful in 2D, not 3D)

If you *must* atlas, then be prepared to build your mipmaps manually, and do filtering and wrapping manually like it's explained on the article you showed.
> 3 votes

---
Tags: xna, textures, voxels
---


# Question
Title: Is there a way to write a camera class without matrix-transformation?
I have a problem with a camera class I got from the internet. It does a transformation like this:

```
public Matrix get_transformation(GraphicsDevice graphicsDevice)
    {
        _transform =
          Matrix.CreateTranslation(new Vector3(-_pos.X, -_pos.Y, 0)) *
                                     Matrix.CreateRotationZ(Rotation) *
                                     Matrix.CreateScale(new Vector3(Zoom, Zoom, 1)) *
                                     Matrix.CreateTranslation(new Vector3(ViewportWidth * 0.5f, ViewportHeight * 0.5f, 0));
        return _transform;
    }

```

Later the spritebatch is called like this:

```
spriteBatch.Begin(SpriteSortMode.BackToFront,
                    BlendState.AlphaBlend,
                    null,
                    null,
                    null,
                    null,
                    cam.get_transformation(device));

```

The problem is that at this point the mouse coordinates are not relative anymore to the other sprites I draw. This is a problem because I try detect which sprite has been clicked. I understand that this issue can be solved by considering the following picture:

This was posted in a very good awnser before, here. But somehow this does not really help me. So my question is:

Is there a way to create a Camera class which does not use transformation, can be moved with keys and keeps the viewport coordinates relative?

Thanks in advance!

# Answer
A matrix simply applies some transformation on the coordinates of the object in order to send them to another coordinate system. In this case, the camera matrix converts world coordinates to screen coordinates. You can revert the process (that is, convert screen coordinates back to world coordinates) by transforming the screen coordinates with the **inverse** of the camera matrix.

Suppose `mouseVector` holds the coordinates of the mouse in screen space. Then the coordinates in the world will be:

```
worldMouse = Vector2.Transform(mouseVector, Matrix.Inverse(camera.getTransformation()));

```

Now that you have the world coordinates of the mouse, you can test for clicks on top of objects as usual.
> 5 votes

---
Tags: xna, camera, mouse
---


# Question
Title: How to determine range of possible movement in turn-based, distance-based strategy game?
I'm creating a 2-dimensional, turn-based strategy game using c++ and SFML-2.0. Movement is distance-based rather than grid-based, with several different triangle-shaped pieces that, on a given turn, each may either rotate in place or move forward.

Movement will work in such a way that the player selects a location for the piece to move to, which generates a potential path for the piece to take. Once the player confirms his or her decision, the piece will move along that path to the desired location. Paths are limited by two factors: distance, how far a piece is able to go, taking into accounts any turns (so if there is a curve, it will be the length along the curve, and not directly from point to point); and steering angle, how far the piece can rotate at any (and up to every) point while moving (for example, from -30 to 30 degrees).

My question is, how should I go about determining the range of potential locations that the player can select to have the piece move to?

I'm not entirely sure what equations and/or algorithm to use here. My original plan was extremely over-complicated, to the point where it was near impossible to implement, let alone explain, and I am at this point totally lost with the project stalled.

**How can I determine the range a unit can move, taking into account its turning radius?**

For example, in the below image. The red, blue and green lines would all be the same length. The purple circle denotes the movement range the unit can move. (The shape is probably inaccurate and the lines probably aren't *actually* the same length, but you get the idea)

# Answer
> 4 votes
Generate a flow or distance field, using Dijsktra's.

Essentially, fill in a grid using the Dijkstra algorithm with no destination (probably a different name for that; don't know it). Just take each open node, compute reachable neighbors, push them on the open list, set on the closed list, update parent node's "next" path as appropriate, etc. When determining the cost to reach a new node, consider the turning limitations.

The result will now be that you have a network of all your nodes on how to get back to the start. Nodes which cannot be reached will not have been touched by the first step. Nodes that can be reached will have a "next node along best possible path to parent" element computed so you can both highlight all nodes and then also use this information to show or execute the movement path as the user hovers or clicks on highlighted areas.

# Answer
> 4 votes
A brute force solution would be:

1. Create a circle of vertices around the unit, with the unit at the center. The radius of the circle is the maximum movement distance. The density of the vertices can change depending how detailed you want the final result to be.
2. For each vertex position, simulate the movement of the unit steering towards that position. This is done in a tight loop without rendering.
3. When the maximum distance is reached in the steering simulation, move the vertex to the point of the simulated unit. This point is the closest the unit could get to that vertex before the current turn was over. This has the effect of shrinking the circle to the size of actual movement.
4. Use those vertices, along with a vertex centered on the unit to create a rendered circle to draw the possible movement distances.

So, starting with the blue circle, you'd process your paths, ending up with the purple circle. Then you can use those points with a center point on the unit to make the red triangles required to display the shape. (Just making that image makes me realize that that shape is not correct, but it'll be interesting to see what's actually correct)

# Answer
> 3 votes
I'm going to expand on Sean's solution in a separate answer, as it represents a different approach from what I was initially proposing.

This solution probably represents the most accessible method. It requires partitioning your environment into nodes. Yes, this is re-introducing a grid-based approach, but it can be made relatively fine, or used for broad pathfinding with finer positioning handled within the node. The more coarse the node structure, the faster the pathfinding.

The big issue here is that you are actually dealing with ship facing, so many traditional pathfinding solutions can't be used without modification. These usually are path-agnostic, in that they don't care how you got to the node you're in. That works fine when acceleration, deceleration, and turning are instant and free. Unfortunately for you turning is not free. However, since there is really one extra piece of information that gets dropped in this simplification, we can encode it as another variable. In physics, this would be known as phase-space.

Assuming 2-dimensions for now, you can extrapolate for 3:

Ordinarily, you would need one node for each allowable, discrete coordinate position. For example:

```
(0,0) - (1,0) - (2,0)
  | \  /  |  \  / |
(0,1) - (1,1) - (2,1)

```

Etc. You'd construct a nodegraph of adjacent points and connect them by spacial adjacency. Then you'd use Dijkstra's algorithm, killing nodes which exceed the movement value allowed for the turn, until there are no unexplored, living nodes remaining connected to explored nodes. Each node keeps track of the smallest distance required to reach it.

To expand this method to be usable with Rotation, imagine this same nodegraph in 3 dimensions. The Z-direction corresponds to rotation/facing, and is cyclical, meaning if you keep traveling in the +Z direction you get back to where you started. Now, nodes corresponding to adjacent positions are only connected across the facing that corresponds to that direction. You iterate over the nodes connected to already explored nodes as usual. I would recommend restricting to N, NE, E, SE, S, SW, W, NW in this scheme.

This solution can tell you all the accessible regions of space, as well as the best path to get there, how much rotation you have when you arrive there, and all of the orientations you could have when you arrive there.

Then, when actually executing the pathing, you're free to interpolate/cubic spline your way into making it look more authentic.

# Answer
> 1 votes
It sounds like you may need to first decide on how exactly you would like the turning on-the-go to work. Options like:

* If they move within the cone, first rotate, then start moving. This is the easier solution to implement and path for. It is also less interesting so I wouldn't want to use it.
* Continuous turning while moving, up to a total of 45 degrees. This one is a lot trickier, and hopefully the one you're after. Numerically integrating over the path using a *fixed* timestep is probably the easiest way to approach this one. Your cone will be bounded by the maximum (+X degrees every step) and minimum (-X degrees every step) turning.

How best to path through space with the second of these requirements depends largely on the environment they'll be moving in. If there are a lot of obstacles you have to traverse around, then things can get really tricky and really expensive. However, if there's not, then you can front-load (and even taper-off) the rotation to end up in the desired location.

I have a feeling that I may have only partially covered the topics you had a question about, so feel free to add more in the comments and I can expand the discussion.

---
Tags: c++, architecture, path-finding, sfml
---


# Question
Title: How would I go about programming atmosphere for a game?
I've recently started making a 2D game, and I want to implement an atmosphere.

My plan is to include many in-game compartments, such as tubes and ventilation. If I open an airlock from a room with zero pressure to a room with high pressure, I should feel a heavy knock back. If I mix gases in a room, and players both human and alike would not be able to breath, they would die.

I have idea of how to do it, but it won't be that sufficient and real. I don't need an real atmosphere; it just needs to feel real.

This is the small list of what I want to implement:

* Gas pressure that effects the environment, such as moving objects and causing damage to objects.
* Simple gas mixing, where I would like to implement 4-5 different gasses.
* Some sort of in-game device to affect atmosphere and check its state.

How would I go about programming atmosphere for a game?

# Answer
It depends on what kind of game you are making. For example, a smallish 2D game might require a different approache than a large 3D one.

My initial suggestion would be a kind of fluid simulation. A grid with values for density, pressure and velocity for each gas. A very good resource for this is a stable fluid solver from Jos Stam. It even has code. The fluid solver can be 2D or 3D, but I would suggest solving a 2D system even if your game is 3D (if possible).

A 'cellular automata' is another approach, similar to a fluid system but can be a quite a bit simpler. Perhaps look into "lattice gas"

If your world is particularly large, you might consider and even more simplified system, such as running the fluid simulation on a very simple waypoint like graph. Although again, this highly depends on your game.
> 4 votes

# Answer
I would make each room a node, (or break each room into nodes for finer granularity) and create a simple Cellular automaton to move gases around. Nodes of equal pressure exchange different gas types at a slow rate, until equalized. Otherwise, gases will move from high to low pressure. Movement between nodes can easily be determined and forces applied to anything inside of those nodes.

I would keep a simple table for each node that contains the percentage of each type of gas that's in that node. Keep it simple and deal with percentages, trying to calculate the density of different gases and how much of some other type of gas they should replace gets too complicated. Nodes only go below 100% when there's vacuum. So a node in space would be 0%.

With this percentage based approach, it's easy to define triggers for the units within the nodes. Say humans need x% of gas y and no more than i% of gas j.
> 2 votes

# Answer
For every environment (like rooms), you can keep an info of gas pressure. High value for room with high pressure etc.

Then, you can apply a force through windows and doors (you know where they are). You can omit walls since nothing will come through it.

The formula of this force might depend on 3 things. Pressures of 2 different environments and distance to border (where these two environments meet).

If you have just opened the door, the pressures are different and you are exposed to maximum force. So something like:

```
Force (you, pressure1, pressure2, distance){

```

`force = absolute(pressure2-pressure1) * 1;` `applyforce(you, force);}`

if you are just at border, you can keep distance 1, and if you are away, you can decrease the distance up to 0. This way, when you are far enough (which you will decide), multiplication will be zero and no force will be applied.

Meanwhile, you should also make the pressure stable within a certain amount of time, since gases will mix and there will be no force (except gas pressure to objects, which is not important, they are from all directions and likely to cancel each other in the end)

After a while, when pressures are equal, the pressure2-pressure1 thing will be zero and again no force will be applied as expected.

For the unit moving thing, it is the same. When this force is applied onto something, depending on weight and shape of object and friction, it will move accordingly. These should be specified by you for different type of objects.

Basically you need to know where such affects occur (enterance to rooms) and define static force vectors for it.

My idea might be wrong though, just to help you
> 1 votes

---
Tags: physics, software-engineering
---


# Question
Title: How can I actually understand Instanced Geometry Rendering - so that I can implement it the way I need it
I'm stuck trying to implement instanced mesh rendering in my project. Particularly because I am failing to understand how certain components actually function - and how the drawing routine is actually associating an effect with the instanced geometry. Being new to 3D devlopment this is turning into a pain in the ass for me - all of my previous experience had never expanded beyond 2D until now.

Although I understand C# Syntax - VB.net is a bit of a sentimental preference for me , so anything written in VB below is my code, and C# are sample references.

Before I carry on - I have tried to use http://www.float4x4.net/index.php/2011/07/hardware-instancing-for-pc-in-xna-4-with-textures/ as reference. However I am stuck trying to understand the 'InstanceBuffer', Vertex Bindings, and how I pass the effect I want to use - as im trying to do the same thing - but not with an atlas texture. I only want the transforms to be passed to my shader - and not with the generated cube geometry from the example - but instead copied from a model.

As seen in the above link - the author demonstrates instancing using generated cubes and "atlas' textures. I am trying to generate instanced geometry by first initializing from an existing model.

Firstly: Most examples I have found - always use a custom model importer , including Microsoft's sample - which in my case - I don't need or want - I instead have a class named **InstancedModel** \- which contains a list of **InstancedMeshPart** objects - and is initialized from a **Microsoft.XNA.Framework.Graphics.Model** using the following methods:

```
    Friend Shared Function G_GET_MODEL_VERTICES_AND_INDICES(Model As Model, ByRef Out_InstancedMeshParts As List(Of InstancedMeshPart)) As Integer
        Dim Parts As Integer = 0

        Out_InstancedMeshParts = New List(Of InstancedMeshPart)

        For Each Mesh As ModelMesh In Model.Meshes
            For Each Part As ModelMeshPart In Mesh.MeshParts

                Dim Part_Vertices As List(Of VertexPositionTexture),
                    Part_Indices As List(Of Integer)

                G_GET_PART_VERTICES_AND_INDICES(Part, Part_Vertices, Part_Indices)

                Out_InstancedMeshParts.Add(
                    New InstancedMeshPart With {
                        .m_VERTICES = Part_Vertices.ToArray,
                        .m_INDICES = Part_Indices.ToArray,
                        .m_OriginalVertexDeclaration = Part.VertexBuffer.VertexDeclaration
                    }
                 )

                Parts += 1
            Next
        Next

        Return Parts
    End Function

    Friend Shared Sub G_GET_PART_VERTICES_AND_INDICES(Part As ModelMeshPart, ByRef Out_Vertices As List(Of VertexPositionTexture), ByRef Out_Indices As List(Of Integer))
        Dim verticeslist As New List(Of VertexPositionTexture)
        Dim indiceslist As New List(Of Integer)

        Dim OffsetInBytes = Part.VertexBuffer.VertexDeclaration.VertexStride * Part.VertexOffset

        Dim PartVertices(Part.NumVertices) As VertexPositionNormalTexture
        Dim PartIndices(Part.PrimitiveCount * 3) As UShort

        Part.VertexBuffer.GetData(OffsetInBytes, PartVertices, 0, Part.NumVertices, Part.VertexBuffer.VertexDeclaration.VertexStride)

        OffsetInBytes = Part.StartIndex * SizeOfShort

        Part.IndexBuffer.GetData(OffsetInBytes, PartIndices, 0, Part.PrimitiveCount * 3)

        indiceslist.AddRange(PartVertices)
        verticeslist.AddRange(PartVertices)

        Out_Vertices = verticeslist
        Out_Indices = indiceslist
    End Sub

```

After Vertices and Indices are copied from a model , in my **InstancedMeshPart** object I then initialize my Vertex buffer, Index Buffer and my Vertex Declaration

```
    Friend Sub InitializeGeometry(GraphicsDevice As GraphicsDevice)
        m_VertexCount = m_VERTICES.Length
        m_IndexCount = m_INDICES.Length

        m_GeometryBuffer = New VertexBuffer(GraphicsDevice, VertexPositionTexture.VertexDeclaration, m_VertexCount, BufferUsage.WriteOnly)
        m_GeometryBuffer.SetData(m_VERTICES)

        m_IndexBuffer = New IndexBuffer(GraphicsDevice, New Integer().GetType, m_IndexCount, BufferUsage.WriteOnly)
        m_IndexBuffer.SetData(m_INDICES)

        Const SizeOfFloat = 4

        Dim StreamElements As VertexElement() = {
            New VertexElement(0, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 1),
            New VertexElement(SizeOfFloat * 4, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 2),
            New VertexElement(SizeOfFloat * 8, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 3),
            New VertexElement(SizeOfFloat * 12, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 4),
            New VertexElement(SizeOfFloat * 16, VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 5)
        }

        m_VertexDeclaration = New VertexDeclaration(StreamElements)
    End Sub

```

My **StreamElements** array is initialized the same way as the example in the link I mentioned above - however im not exactly sure if this is right since I don't want to pass the atlas texture stuff. I only need the transforms for the instances, so I assume I need to remove something - but im not sure how many elements I actually need.

Instead of using the "InstanceInfo" structure the article describes - I only want to pass the World Matrices in my instance buffer - so I am totally brainmashed on what I should be changing in my StreamElements arrray.

```
'  Positions is an array of matrices - not a structure.
m_InstanceBuffer = New VertexBuffer(GraphicsDevice, m_VertexDeclaration, Positions.Length, BufferUsage.WriteOnly)
m_InstanceBuffer.SetData(Positions)

```

I am also struggling to understand exactly how the VertexBufferBindings work :

```
// from sample:

VertexBufferBinding[] bindings;
bindings = new VertexBufferBinding[2];
bindings[0] = new VertexBufferBinding(geometryBuffer);
bindings[1] = new VertexBufferBinding(instanceBuffer, 0, 1);

```

Why am I passing the transormation matrices stored in the InstanceBuffer to the bindings and not through an EffectParameter? Were or How are the parameters being passed to my shader (eg the transforms for each mesh instance)?

In his example - im not sure how the graphics device knows that it has to use the effect specified below: I can't see any relation to the effect object and the DrawInstancedPrimitives. How is his code assigning this effect to the instance mesh he is rendering? Especially since there is no Meshpart.Effect property? Were am I telling the graphics device that *I want to draw this instanced geometry with "MyEffect"?*

```
// from sample:

GraphicsDevice.Clear(Color.CornflowerBlue);

effect.CurrentTechnique = effect.Techniques["Instancing"];
effect.Parameters["WVP"].SetValue(view * projection);
effect.Parameters["cubeTexture"].SetValue(texture);

GraphicsDevice.Indices = indexBuffer;

effect.CurrentTechnique.Passes[0].Apply();

GraphicsDevice.SetVertexBuffers(bindings);

GraphicsDevice.DrawInstancedPrimitives(PrimitiveType.TriangleList, 0, 0, 24, 0, 12, count);

```

and similarly from http://blogs.msdn.com/b/shawnhar/archive/2010/06/17/drawinstancedprimitives-in-xna-game-studio-4-0.aspx

```
// from sample:

instanceVertexBuffer.SetData(instanceTransformMatrices, 0, numInstances, SetDataOptions.Discard);

graphicsDevice.SetVertexBuffers(modelVertexBuffer, new VertexBufferBinding(instanceVertexBuffer, 0, 1));
graphicsDevice.Indices = indexBuffer;
instancingEffect.CurrentTechnique.Passes[0].Apply();

graphicsDevice.DrawInstancedPrimitives(PrimitiveType.TriangleList, 0, 0,
                                       modelVertexBuffer.VertexCount, 0,
                                       indexBuffer.IndexCount / 3,
                                       numInstances);

```

In the above - It is obvious we are setting common EffectParameters for the effect and then applying it, but the issue being that I have no idea how or were the GraphicsDevice instance would know to use my effect.

Basic overview of what i cannot understand:

1. How are my transforms ( in InstanceBuffer ) being passed to the shader?
2. How or were does the graphics device know that I want to draw using a specific effect when trying to draw instanced geometry? It was easy when I was just looping ModelMeshParts before... but now my brain has been sucked into a black hole the moment I need to render several thousands of identical objects.
3. Exactly what should I be removing from my 'VertexElements' variable - what happens to each element? Are they being passed to a shader? Am I right to assume I dont need the 5th element?

When I began trying to implement instancing I wanted to implement my instanced draw routine that accepts parameters like this. However because of what im stuck on - I cant fill this routine.

```
DrawInstanceModel(GraphicsDevice as GraphicsDevice, Model as InstancedModel, Effect as Effect , Positions as Matrix() )

```

# Answer
> 0 votes
Q: How are my transforms ( in InstanceBuffer ) being passed to the shader?

A: By binding an additional instance stream.

In the example you referred to it's these lines:

```
VertexBufferBinding[] bindings;
bindings = new VertexBufferBinding[2];
bindings[0] = new VertexBufferBinding(geometryBuffer);
bindings[1] = new VertexBufferBinding(instanceBuffer, 0, 1); // <- instance data
...
GraphicsDevice.SetVertexBuffers(bindings);

```

Q: How does the graphics device know that I want to draw using a specific effect when trying to draw instanced geometry?

A: By biding the effect to the device, setting up shared parameters before the draw call and passing per-instance effect parameters in the instance data stream.

Q: Exactly what should I be removing from my 'VertexElements' variable - what happens to each element? Are they being passed to a shader? Am I right to assume I dont need the 5th element?

A:

Let's have a look how you would go about rendering the same mesh twice without instancing:

1. Bind the vertex and index buffers to the device
2. Bind the effect (shader) to the device
3. Set the world matrix for the effect to the first instance's world matrix
4. Draw the mesh
5. Set the world matrix for the effect to the second instance's world matrix
6. Draw the mesh

If you wanted to draw 100 instances of the same mesh at different world transforms, you would thus have to repeat steps 4 and 5 for each instance.

What's so bad about that?

Well, you have to issue at least one shader constant switch and a draw call per model and minimizing these numbers usually helps improving performance.

Now, wouldn't it be nice if we could just fill some buffer with the 100 world space matrices we'd like our meshes to be rendered to and just pass that buffer to a single draw call?

Instancing does just that.

It allows you to issue a single draw call that will repeat the rendered primitives a given number of times while advancing and addional vertex stream only every Nth primitive (once after each mesh).

In our sample case the code would go like this:

1. Bind the vertex and index buffers to the device, containing the mesh geomtry
2. Bind the effect (shader) to the device
3. Bind an additional vertex buffer to the device, containing 100 world space matrices
4. Draw the mesh 100 times with instancing

In the shader you then receive the geometry data (the mesh vertex in its local space) and the instance data (the world space matrix) and can use both to render the instance.

This means we can now render 100 identical meshes at different world positions in one go.

What if you'd like the models to use different textures?

We can do that as well by filling our additional (per-instance) vertex buffer with structs where the world space matrix is just one field and some other field might indicate which texture to use.

In the sample you refered to that's called InstanceInfo.

# Answer
> 0 votes
I don't know XNA, so I'm going to just talk like we're doing OpenGL. This all translates relatively easily into D3D, and should hopefully thus translate into XNA easily as well.

Instanced rendering is basically taking this:

```
glDrawArrays()

```

And turning it into this:

```
for i = 0 .. numInstances:
  __glSetInstanceId(i)
  glDrawArrays()

```

Except done in hardware/driver instead of the application, of course.

In your shader, you get a new uniform called `glInstanceID` which is the number of the instance being drawn. All of your other uniforms in the single case now need to be in an array of some kind that you can index with `glInstanceID` or be part of a new vertex stream that is automatically updated once per model.

When you call `glVertexAttribDivisor` you can specify that a particular vertex attribute in a bound VBO is only updates once every `N` instances (usually you set this to `0` for attributes shared by all instances and `1` for attributes that vary per-instance).

If you're rendering 10 models and need 10 positions, you create a VBO holding 10 positions and then bind it with `glVertexAttribPointer`. You can then use `glVertexAttribDivisor` to set its instance update rate to 1. Now this attribute in your vertex shader will be sourced per instance; that is, the attribute won't change for each vertex, but it will change whenever a different instance is being drawn.

An alternative, which is necessary for OpenGL implementations that don't yet support `glVertexAttribDivisor`, is to store your per-instance information in either a uniform buffer object or a texture buffer object. With a uniform buffer you just acess it like a regular array. With a texture buffer you use `texelFetch` in your shader to access them. Use `gl_InstanceID` as the index.

With D3D, you don't use a separate call to set the divisor, it's part of the `D3D11_INPUT_ELEMENT_DESC`. The shader calls to access texture buffers are different and you use *constant buffers* as the analog to a uniform buffer. Otherwise, same thing.

---
Tags: xna, c#, 3d, xna-4.0, graphics-programming
---


# Question
Title: Which part of MVC should be responsible for selecting a unit
Imagine a turn-based tile game, that generally looks like Heroes' combat view. Except for the fact a player can choose any of his units to command.

Our team is implementing the game according to MVC paradigm.

Some logic needs to be defined in order to allow selecting only allied units, for instance. And the selected one should be highlighted by the View.

For now we have made a Controller responsible for this. But to me it feels strange when the View is rendering data that comes from the Controller itself instead of the Model.

Is there any common practice to put such logic in Model or Controller?

# Answer
I'd warn against MVC for games in the first place, but putting said logic in the controller is fine. You can also put a small bit in the model if you want to be really pure. The Model contains a selection state and the Controller modifies this. Then the View uses this state to do its rendering.

Something like:

```
Model:
  bool selected = false

Controller:
  on click:
    old_unit.selected = false
    new_unit.selected = true

View:
  on draw model:
    if model.selected:
      render selected mesh/sprite/effect
    else:
      render regular mesh/sprite

```

You can use more intricate state than just a boolaen if you need for better effects, such as timers to smoothly animate selection effects, or states for active player unit, active enemy unit, select for combat, select for movement, whatever.
> 4 votes

---
Tags: selection, mvc
---


title: Sending entities to connecting player

text:
# Question
Title: Sending entities to connecting player
When a player connects to a game, he needs to be sent all the entities currently on the map. This is done by creating entities one by one. Three ways of implementing this come into my mind. Which one them is the best?

1) Implement sending entities in the game engine: Game engine listens to "connected" event from a player object and send all the entities to the player when this happens.

2) Implement sending entities in the entity class: Entity listens to "player connected" event from the game engine and when this happens, it sends itself to the connecting player.

3) Implement sending entities in the player class: When a player connects, it gets list of entities from the game engine and sends each of them to itself.

# Answer
> 1) Implement sending entities in the game engine: Game engine listens to "connected" event from a player object and send all the entities to the player when this happens.

While none can say what is the best, this is indeed a good way to do it. Server listens for connections and when it receives new connection, it sends "The Data" packet, that contains all the necessary info, that client needs to be able to start rendering the world.

---

Semi-Pseudocode to demonstrate Option 1:

```
while((msg = netStream.Receive()) != null)
{
     if(msg.Type == PacketTypes.NewConnection)
         SendStartPacketTo(msg.Sender);
}

```

For me ( my opinion ), this approach gives better control, on when to send and what to send.

---

If you are using component based programming, like in Unity3D, then you might want entities to send data independently. ( Option 2 ).
> 2 votes

---
Tags: architecture, multiplayer, server
---


# Question
Title: How to create a character animation where the parts of the sprite change?
Let's say I'm creating a game (in Java or C++). In this game I have a character that can do a sword swing animation, but the character can equip different swords.

Do I have to make an animation for each individual sword, or is there another way? I Like if a character can equip different armors, do I create a new sprite for each armor, or is there a way to have, say a base character that can perform all the animations with different swords and can have different armors on the same image?

# Answer
> 8 votes
### Yes, you can do it in a fairly simple way using transparency.

What you'd need to do would be to make a few layers of sprites instead of one, prepared in such a way and order that when they were displayed, they would form a whole person.

I've attached a sample image showing how that might look.

1. Shows the base image I was working on
2. I've removed parts that are not going to change
3. I've made one isolated sword image
4. That's how sword (gold one this time) looks when drawn over the image from 2. *Smooth!*

Now you can easily replace steel sword with gold sword, and you don't have to create a whole new set of sprites.

### If you feel more like an artist at this point

Then simply draw a few (5-10) sword positions (precomputed). This has an additional benefit of allowing you to change the sword shape during movement and might produce overall better results.

The number of animation frames is of course up to you. What's important in this method is that with a proper sprite delay engine (not that hard to write), you can have more frames for parts that move faster and less for ones that move slower.

Simple pseudocode implementation might look like

```
// calculating each subpart
foreach(sprite_part in parts)
    // first_not_less_than is usually called "lower_bound"
    sprite_num = time_data[sprite_part_num].first_not_less_than(time)
    sprite = spritesheet[sprite_part[sprite_num]];

```

### If you feel more like a programmer

Notice how I've removed the whole arm from the base. You could easily rotate the sword to simulate the movement. This will produce a very smooth animation and requires only sprite drawn in basic position, but can feel a bit less natural.

Forgive me for not preparing a `.gif` comparing the two, but I am *not* an artist :)

While this is only an example, there's of course more to it. From a top-view game or isometric game different approach can make sense. This answer only aims to illustrate the general idea.

---
Tags: 2d, animation, sprites
---


title: Seperate draw calls

text:
# Question
Title: Seperate draw calls
What I want to implement next in my game is frustum culling. The issue that I'm having is creating a draw method that I can check which cubes in my vertex buffer I draw or not. What I want to do is loop through my list "cubes" and check for each bounding box that the cube has. I've done this before when I had each cube have a separate vertex buffer, but now when I try it with a chunk of cubes, it crashes my computer. I know why this happened so I won't bother explaining it.

```
      cubes.Add(new Cube.Grass(device, new Vector3(x, map[x, z] - y, z), grass));
      cubeBoundingBox(some Vector3s here);

```

So with these two lines I add the cube to the list and create a bounding box based on the position and size of the box. I'm sure there's a better way to do this.

```
    public void DrawMap(GameTime gameTime)
    {
        ContainmentType CurrentContainmentType = ContainmentType.Disjoint;

        foreach (Cube block in cube.cubes)
        {
            CurrentContainmentType = cam.frustum.Contains(cube.cubeBoundingBox);

            //some more stuff here

            if (CurrentContainmentType != ContainmentType.Disjoint)
            {
               cube.Draw(effect);
            }

```

This is my old method that almost worked. But now that I have all cubes stored in a single vertex buffer, this won't work. I'm kinda lost here. How can I loop through all the cubes in my list "cubes" in order to check if they need to be culled or not? Or would it make more sense to make a list of bounding boxes and loop through that list?

# Answer
Just iterate through the vertices with offset to the next first vertex of the next cube. Like this:

```
point[] linevertices = new point[6]; // line is made of 2 points

// Iterate through all lines
for(int i=0; i<6; i=i+2){
    // code
}

```
> 1 votes

---
Tags: xna, c#
---


# Question
Title: Do GLSL 4.x subroutine variables cause any performance overhead?
There's not too much deep information about them on the web.

How are they implemented and how they work under the hood? I'd like to know that they cause any performance overhead or not, especially in the case of multiple subroutines to decide what's the best practice to create different versions of shaders: subroutines or separate shaders.

Any info or advice?

# Answer
> -1 votes
Meanwhile I get a nice detailed answer from the OpenGL Forum here.

I think it will be useful for others too.

---
Tags: opengl, 3d, glsl, gpu
---


# Question
Title: Entity-System Architecture; Pools and Factories
I'm creating a 2D game based on entity-system architecture using C++, the C++ port of Artemis, and SFML. I've had to jump through a few hoops, but it's been fairly smooth until now.

In this game, I have an `EntityFactory` class which basically just makes `artemis::Entity` objects, does some processing (such as creating sprites or setting the position of the entity) and returns that `artemis::Entity`. This is represented by a static class, something like this:

```
class EntityFactory {
public:
    //Creates the player, should only be called once
    static artemis::Entity CreatePlayer(artemis::World& world, sf::Vector2f pos);
    //Creates a bullet, can be called many times
    static artemis::Entity CreateBullet(artemis::World& world, sf::Vector2f pos);
    //Creates a static image
    static artemis::Entity CreateStatic(artemis::World& world, sf::Vector2f pos, std::string imgLoc);

    //Some more entities...
}

```

It's fairly essential that I call these functions to create the entities; the class does a lot of boilerplate stuff, like adding all the necessary components to the entity.

Lately, I've been thinking about implementing a particle system in the game as well. In addition, I'd like to be able to reuse my bullet entities instead of creating & destroying them all the time. To this end, I figured I'd create a `Pool` class that holds entities, and disables/enables entities as needed - a common pattern. Here's the basic layout that I was thinking of:

```
class Pool {
public:
    //Enables/returns a disabled entity, or creates a new
    // one and returns it if there are none available.
    artemis::Entity& get(/*Some data about the object*/);
    //Disables an entity, and marks it as reusable.
    void disable(artemis::Entity&);
private:
    //Data structures for holding the active/disabled entities...
    Function_of_some_sort createEntity;
}

```

Alright, that's all well and good, except for the one sore spot - that ambiguous `Function_of_some_sort`. I'd like to let the `Pool` create its own `Entity` objects in `Pool::get()` . Obviously, I want to use the `EntityFactory`, since it does a bunch of work; however, to do so, I'd need to be able give the `Pool` a function with an arbitrary number of arguments and be able to pass `Pool::get()` the same number of arguments.

As I see it, I have these options:

1. Limit my functions to a single signature and use a function pointer, eliminating possibilities like `EntitySystem::CreateStatic` (above).
2. Implement arbitrary, generic callbacks as described here, sacrificing some typesafety.
3. Give up the idea of an arbitrary-entity `Pool`, and make a `Pool` class for each entity I need. Might be ok, since I don't really have that many classes that need a `Pool`, but I'm only changing a single function call in each `Pool` class...
4. Refactor `EntityFactory` somehow so that I don't need function callbacks. Probably the best solution, but I haven't been able to come up with a good way to do it.

I feel like there *has* to be some elegant way of pulling this off, as these are two fairly common patterns that I'm sure have been used in conjunction before. I'm stuck in analysis paralysis; does anyone have examples or experience to offer on the subject, or just some suggestions?

# Answer
> 6 votes
Use data to define these things, not code.

Also, if you're using a real ECS, you don't pool individual objects, you pool components. More generic component-based design will have you pool both separately. You definitely don't need to pool `Player` objects separate from `Bullet` objects, though, since all an object is is a collection of component and a few bits/flags/metadata. Creation of these (grabbing a new empty entity and adding all the necessary components) should be *cheap* or you need to rethink how you're managing your components.

You should have an "archetype" or "blueprint" that defines which components a particular object has. Your level or game logic can specify additional overrides during object initialization, like position. You can make multiple sub-archetypes for your different types of static objects.

Hard-coding a `CreatePlayer` defeats half the purpose of component-based design the way I look at it. You should be able to easily compose new types of objects with minimal fuss, preferably from an editor (or at least a text file) without needing to recompile the whole app. Good for modders, too.

---
Tags: c++, architecture, entity-system
---


# Question
Title: How do I make my camera follow a Box2D object?
I'm implementing a camera in my game. It worked for regular objects, but I began using Box2D and obviously things changed a bit. I have a `Body` object that I want to draw at the center of the screen. Basically what I'm doing is subtracting the `viewportX` and `viewportY` from the `Body`'s position.

The relevant code:

```
public void paint(Graphics2D g, int viewportX, int viewportY) {
    Transform xf = new Transform();

    // m_body is the Body object
    xf.set(m_body.getTransform());

    // Here I attempt to take the transform and alter it by the viewportX and
    // Y, which are something like (-240, -150). It's negative because an
    // object at (500, 300) would be displayed at (160, 150) after the
    // subtraction. DrawUtils.toScale(), is just how I convert units from
    // JBox2D units to my units.
    Vec2 v = Transform.mulTrans(xf, new Vec2(DrawUtils.toScale(-viewportX),
        DrawUtils.toScale(-viewportY)));

    // Set the new transform to the new vector. Keep the old angle.
    xf.set(v, xf.q.getAngle());
    g.setColor(Color.white);

    // I know the following method works correctly. It displays my object,
    // just doesn't follow it.
    for (Fixture f = m_body.getFixtureList(); f != null; f = f.getNext())
        DrawUtils.drawShape(f, xf);
}

```

I don't want to alter the actual physics position of the object, just its graphical position such that it's displayed it in the center.

# Answer
Apparently my method wasn't too far off. Here is the adjustment:

```
Vec2 n = xf.p.sub(new Vec2(DrawUtils.toScale(-viewportX), DrawUtils
            .toScale(-viewportY)));
xf.set(n, xf.q.getAngle());

```
> 1 votes

---
Tags: java, mathematics, physics, box2d, transformation
---


# Question
Title: How to import character from Blender to Unity?
I am trying to import a character into Unity from Blender. I exported the model (which has actions/animations) from Blender as a FBX file and dropped in into my Unity project’s Assets folder. The model with all of its components (mesh, armature, animations) appears in the project window; however, Unity doesn’t immediate associate the animations with the model when I drag an instance of the model into my scene.

I have also imported a Blender default model (“Constructor” - a man with red overalls and a wrench), and have been comparing the settings of my model to the Blender model in order to find discrepancies.

**3 observations I have made:**

1. Blender’s model is automatically assigned an “Animation” window in the Inspector panel (image #1), while mine is assigned an “Animator” window (image #2). Since the former window is the one where the animations are listed and you assign the default animation, it seems like this one is crucial. How do I import my model such that the “Animation” window appears in its Inspector window? (I’ve tried adding an “Animation” window myself, but it doesn’t recognize the model’s animations as the Blender model’s “Animation” window does.
2. In Unity, my model’s animations all begin at -1.0 (even though they begin at keyframe 0 in Blender) (image #3). For each animation, I get the message, “The clip range is outside the range of the source take.” I get this message even when I move the animation forward several keyframes in Blender and re-export the file to Unity as a FBX.
3. I compiled several of my actions into an animation that I then exported as a .mov file, and this is the sequence of actions that begins when I press “Play” in Unity. When I deleted this animation from Blender (as I thought this was the issue), my model now does nothing when I press “Play.”

I am using:

Blender 2.67 and Unity 4.1.5f1

My actual question: How do I import my character into Unity such that it is automatically assigned an “Animation” window?

I have been struggling with this issue for several hours now, and none of the online tutorials or forums seem to address it.

# Answer
> 3 votes
I could make it a long answer but it would be a waste of time to write it, taking into consideration the fact that unity has made a great tutorial covering every step.

> http://www.youtube.com/watch?v=Xx21y9eJq1U

Quick steps to animating a character:

* Watch the Mecanim tutorial video I would have never figured out how it works before trying to figure it out yourself and asking on any website. It is just 20 min for what you are asking, don't quit.
* Drag and drop the rigged character into the project folder
* Create a mecanim avatar for the character http://docs.unity3d.com/Documentation/Manual/CreatingtheAvatar.html
* Create an animation controller for your character

## The Mecanim 4.0 tutorial covers EVERYTHING (in 48 minutes)

---
Tags: unity, blender
---


title: Pinhole matrix problem

text:
# Question
Title: Pinhole matrix problem
I made a program to represent a 3D world. I use the projection matrix we can find on wikipedia. For viewing a scene it's very nice but when I straff in the scene, everything behind the camera go on the screen.

Comparaison image:

Can you tell me how I can fix it, just the main idea ? Is it the frustum ?

```
Point2D Point3D::convertPerspective(){
    // camera pin hole
    // translation
    Point3D newPoint = *this-camera;
    // rotation
    Point3D d(cos(theta.y)*(sin(theta.z)*newPoint.y+cos(theta.z)*newPoint.x)-sin(theta.y)*newPoint.z,
              sin(theta.x)*(cos(theta.y)*newPoint.z+sin(theta.y)*(sin(theta.z)+cos(theta.z)*newPoint.x))+cos(theta.x)*(cos(theta.z)*newPoint.y-sin(theta.z)*newPoint.x),
              sin(theta.x)*(cos(theta.y)*newPoint.z+sin(theta.y)*(sin(theta.z)+cos(theta.z)*newPoint.x))-sin(theta.x)*(cos(theta.z)*newPoint.y-sin(theta.z)*newPoint.x));
    //projection
    return Point2D((viewerPos.z/d.z)*d.x-viewerPos.x,
                   (viewerPos.z/d.z)*d.y-viewerPos.y);
}

```

# Answer
I will assume you are trying to write your own software renderer or something like that.

From how you describe it, it appears you don't do any clipping. But since you seem to only draw lines, this can be easily fixed, just only draw the part of the lines that are in front of the camera:

1. For every line, check on what side of the clipping plane the vertices are.
2. If both vertices are behind the plane, don't draw anything.
3. If both vertices are in front, draw them normally.
4. If only one of the vertices is behind the camera, replace it with the intersection point of the line and the clipping plane, then apply projection matrix and draw the vertices.

You might want to apply this check for all clipping planes of your frustum, depending on how complex your scene will be, as clipping also helps performance.

Also if you are going to draw polygons, be aware that clipping those is a bit more complicated. Have a look at these clipping algorithms for information on how to do it.
> 1 votes

---
Tags: camera, matrix, projection
---


# Question
Title: Node.js/V8 as a Platform for High End Local PC Game Development?
As a Web/UI dev rapidly expanding into more wide-open generalist territory, the more I learn about how its done in other languages, the more I love JS for architectural and basic messaging/event-driven concerns. For the record I am most certainly not a full-blown game-dev (although I did once write for a major gaming mag which is like saying I pretended to be friends with game devs on TV, although you guys were always my favorite folks to talk to).

Anyway, since it's fairly easy to bind C and C++ to JavaScript via Node (or perhaps more specifically V8), how reasonable would it be to assume you could write a decent 3D engine that exposed outcomes of things like collision calculations as events to the JS with the intention of getting the dynamic first-class-function party language benefits (assuming you see such things as benefits - I do) to higher level architecture and AI logic concerns without a crippling loss in performance?

Node, as I understand it, basically exposes a C event loop to JavaScript handled by V8. The JS is single-threaded, meaning any attempt to do anything calculation/IO-intensive with the JS would be foolish, but you get the advantage of not really having to sweat threads, queuing etc... since you're ideally never trying to muck with the same data at the same time. Most code would of course be heavily event/callback driven. All the file I/O concerns and other processor intensive stuff is basically C or C++ under the hood telling you when its done. Not to mention handling UI concerns directly out of the JavaScript via a webkit layer slapped on top of everything.

I'd be delighted to hear why you love/hate the idea but the core question is: is it feasible and why/not? And no, I seriously doubt my own ability to do this all by myself, although plugging an existing 3D engine in might not be outside of the realm of possibility but I'd still be learning a lot of new stuff to make that happen I'm sure.

# Answer
> 3 votes
Yes, it's quite possible. In essence, this would just be extensive scripting, and scripting is very common in game development. You can do whatever you can in JS, and use C/C++ for the stuff you can't get to behave with JS.

I wouldn't bother with Node.js and go straight for V8, which is not that hard to integrate. V8 has recently added isolates, which make it possible to run multiple threads on a single context, but you'll probably be fine with a single JS thread, resource loading and such can be handled by threaded native code.

Depending on how much you script, there'll be some tricky issues, even on the PC which has a relative abundance of memory. On mobile, these issues would be greatly amplified. But I'm mostly thinking about garbage collection related issues here, which affect Java and C# games all the same.

My preferred approach to scripting is to only use it for descriptive stuff, that doesn't cause any such issues. I use JS or Lua to describe worlds, UIs, dialogs and all that, run the scripts once to get the data into memory and then operate on that data from native code. My suggestion would be to start with something like that, and see how far you want to take the scripting.

---
Tags: javascript, c, node.js
---


# Question
Title: How to prevent clipping when moving through a tunnel?
I'm developing for Android using OpenGL ES 2.0.

It's going to be a game where you have to fly through a tunnel without hitting the walls.

However, the tunnel wall gets clipped as the player approaches. This is especially annoying with the rings as they suddenly disappear, causing an uncomfortable flashing effect.

How can I make sure that the tunnel fills the entire screen?

# Answer
> 1 votes
Try depth clamping. There are some drawbacks but it could potentially solve your problem.

Also, see this question for how to define your own rendering frustum:

https://stackoverflow.com/questions/4792952/how-to-ensure-that-a-plane-perfectly-fills-the-viewport-in-opengl-es

---
Tags: android, camera, opengl-es2, clipping
---


# Question
Title: OpenGL get the outline of multiple overlapping objects
I just had an idea for my on-going-game made with opengl in c++: I'd like to have a big outline (5-6 pixel) on multiple overlapping object when the player win something.

I thought the best way is to use stencil buffer but it's few hours that I' trying to do some off-screen render of the stencil buffer and I can't achieve any kind of result so probab. there are some other techniques!

This is what I want to get:

Any ideas?

# Answer
> 4 votes
1. Enable and clear the stencil buffer.
2. Draw the objects, setting the stencil buffer. Objects can be semi-transparent etc.
3. Now set the stencil mode to only write pixels where the stencil is not set.
4. And draw each object again, slightly scaled up, in the desired border colour and without textures.
5. Disable the stencil buffer.

Here is the code adapted from some webGL stencil code that I have working:

```
// drawing will set stencil stencil
    gl.enable(gl.STENCIL_TEST);
    gl.stencilFunc(gl.ALWAYS,1,1);
    gl.stencilOp(gl.KEEP,gl.KEEP,gl.REPLACE);
    gl.stencilMask(1);
    gl.clearStencil(0);
    gl.clear(gl.STENCIL_BUFFER_BIT);
// draw objects
for(var object in objects)
  objects[object].draw();
// set stencil mode to only draw those not previous drawn
    gl.stencilFunc(gl.EQUAL,0,1);
    gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP);
    gl.stencilMask(0x00);
// draw object halo
for(var object in objects)
  objects[object].drawHalo(1.1,red); // each mesh should be individually scaled e.g. by 1.1
// done
    gl.disable(gl.STENCIL_TEST);

```

I think I've used this approach in RTS games to draw halos around selected units, but it was a long time ago and I don't recall if there are any gotchas and all the nuances.

# Answer
> 2 votes
Start by finding all groups of objects, where a group of objects is a collection of objects which overlap. Standard collision detection should do the job. Assign to each group a unique colour. Any colour would do.

Render all your objects as solid colours, using the group colour, to a texture.

Create a new outline texture with the same dimensions as the render target. Scan through each texel of the render target and determine if it's a different colour to any surrounding texels. If it is, change the corresponding texel in the outline texture to the line colour you want.

Finally, take this outline texture and render it over the top of the image you want to draw on the screen (you could of course do this at the same time as the edge detection in a fragment shader and avoid creating the edge texture in the first place).

If you perform this step on the cpu by using a for loop to go through the render target's texels, then this will be pretty slow, but probably good enough to test and even use in some cases. To use this in real time you would be best to handle this in a shader.

A fragment shader to do this edge detection might look like this;

```
precision mediump float;

uniform sampler2D s_texture;

varying vec2 v_texCoord;

void main()
{
    gl_FragColor = vec4(0.0);

    vec4 baseColor = texture2D(s_texture, v_texCoord);
    gl_FragColor += baseColor - texture2D(s_texture, top);
    gl_FragColor += baseColor - texture2D(s_texture, topRight);
    gl_FragColor += baseColor - texture2D(s_texture, right);
    gl_FragColor += baseColor - texture2D(s_texture, bottomRight);
    gl_FragColor += baseColor - texture2D(s_texture, bottom);
    gl_FragColor += baseColor - texture2D(s_texture, bottomLeft);
    gl_FragColor += baseColor - texture2D(s_texture, left);
    gl_FragColor += baseColor - texture2D(s_texture, topLeft);
}

```

Where the second value in the texture2D look up is a 2d coordinate relative to v\_texCoord. You would apply this by rendering the first render target as the texture on a full screen quad. This is similar to how you would apply full screen blurring effects such as a guassian blur.

The reason to use the first render target with solid colours is simply to make sure that there is no perceived edge between different objects that overlap. If you simply performed edge detection on the screen image you would probably find that it detects edges at the overlaps as well (assuming the objects have different colours/textures/lighting).

---
Tags: opengl, outline
---


# Question
Title: generating random block-based worlds with 3D noise
I want to create a 3D block-based infinite world.

For any block, I want to be able to compute its block type.

3D perlin noise is the usual building block of such a world. If you ask the 3D noise function the value for a 3D point, it'll give you a value between -1 and 1.

How do you turn this number into a block type?

I want blocks on the surface to be turf, and different minerals to have different probabilities based on depth. I want sprawling caves and caverns and lava flows but not small ones. And so on.

So how do you turn noise into block types into a coherent subterranean world? Particularly how do you make things like coal appear in seams and crystals only appear in caves and any other rules that can be invented that make the type of a block dependent upon its neighbours?

And how to do this efficiently, in an oracle function rather than by having to create large 3D arrays to store the decided outcomes of some terraforming?

# Answer
Use many layers of perlin noise (or better simplex noise) differing in scale, range and dimensionality. There is a nice post on gamedev.net. And its continuation.

For the basic shape, use a combination of 2d and 3d noise. Using just the 3d part wouldn't result in noticeable distinction between a solid ground and free air. Using only the 2d part wouldn't allow for overhangs like any 2d heightmap. Therefore combine both.

Then use additional layers of noise to define block types. For example, use 2d noise for area properties like biomes, which might result in defferent ground types.

For special features like minerals in the ground use 3d noise with a very high threshold and clamp the range. Say, you want ores to be found in the range of 5 to 20 blocks from down, sample this noise only if the current block is of this height. Then only if the noise exceeds say 0.9, place ore instead of stone.

Moreover, calculating all blocks directly and independently is a good aim but wasn't practically for me. At least for forms that grow over time in nature. For this it is useful to first generate the basic terrain shape and iterate over the world to modify it based on adjacent blocks. For example you need that to cover an area with a 1 block thick layer of grass blocks.

It may also help you to look over my world generation code at Github. Here is an example of how my procedural generated world looks like.
> 6 votes

---
Tags: procedural-generation, perlin-noise
---


# Question
Title: How to change dynamically vertices during call "draw" method?
I'm new in openGL world and I try to figure out followed problem:

How can I change size/zoom dynamically for my spritesheet.

This class represents some creature fetched from spritesheet and animate it.

```
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import javax.microedition.khronos.opengles.GL10;

public class DevQuestSpriteBase {

private static final String LOG_TAG = "Fess";//DevQuestSpriteBase.class.getSimpleName();

protected int mFrame = 0;
protected int mSwitcher = 0;
private int textureCount = 1; // frame animation
protected int[] textures = new int[textureCount]; // frame animation

// texture and verts
protected FloatBuffer vertexBuffer,
textureBuffer1,
textureBuffer2,
textureBuffer3,
textureBuffer4;

ByteBuffer bb1;

protected float verticesZoom[] = {
        0f,0f,0.0f,
        0f,0.5f,0.0f,
        0.6f,0f,0.0f,
        0.6f,0.5f,0.0f
};

/** 1 frame */
protected float texture1[] = {
        0.0f, 1.0f,
        0.0f, 0.0f,
        0.25f, 1.0f,
        0.25f, 0.0f
};
/** 2 frame */
protected float texture2[] = {

        0.25f, 1.0f,
        0.25f, 0.0f,
        0.5f, 1.0f,
        0.5f, 0.0f
};
/** 3 frame */
protected float texture3[] = {
        0.5f, 1.0f,
        0.5f, 0.0f,
        0.75f, 1.0f,
        0.75f, 0.0f
};
/** 4 frame */
protected float texture4[] = {
        0.75f, 1.0f,
        0.75f, 0.0f,
        1.0f, 1.0f,
        1.0f, 0.0f
};

public DevQuestSpriteBase(){
    // vertices buffer
    bb1 = ByteBuffer.allocateDirect(verticesZoom.length * 4);
    bb1.order(ByteOrder.nativeOrder());
    vertexBuffer = bb1.asFloatBuffer();
    vertexBuffer.put(verticesZoom);
    vertexBuffer.position(0);

    // texture buffer
    bb1 = ByteBuffer.allocateDirect(texture1.length * 4);
    bb1.order(ByteOrder.nativeOrder());
    textureBuffer1 = bb1.asFloatBuffer();
    textureBuffer1.put(texture1);
    textureBuffer1.position(0);

    //#########################################################

    // texture buffer
    bb1 = ByteBuffer.allocateDirect(texture2.length * 4);
    bb1.order(ByteOrder.nativeOrder());
    textureBuffer2 = bb1.asFloatBuffer();
    textureBuffer2.put(texture2);
    textureBuffer2.position(0);

    //#########################################################

    // texture buffer
    bb1 = ByteBuffer.allocateDirect(texture3.length * 4);
    bb1.order(ByteOrder.nativeOrder());
    textureBuffer3 = bb1.asFloatBuffer();
    textureBuffer3.put(texture3);
    textureBuffer3.position(0);

    //#########################################################

    // texture buffer
    bb1 = ByteBuffer.allocateDirect(texture4.length * 4);
    bb1.order(ByteOrder.nativeOrder());
    textureBuffer4 = bb1.asFloatBuffer();
    textureBuffer4.put(texture4);
    textureBuffer4.position(0);
}

private void update() {

    if(mSwitcher == 5){
        mFrame = ++mFrame % 4;
        mSwitcher = 0;
        // Log.e(LOG_TAG, "DevQuestSpriteBase :: " + mFrame);
    }
    else{
        mSwitcher++;
    }

}

public void draw(GL10 gl){

    gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);

    gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);

    if(mFrame == 0){
        gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, textureBuffer1);
    }
    else  if(mFrame == 1){
        gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, textureBuffer2);
    }
    else  if(mFrame == 2){
        gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, textureBuffer3);
    }
    else  if(mFrame == 3){
        gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, textureBuffer4);
    }

    //gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);

    //Log.e(LOG_TAG, "DevQuestSpriteBase :: draw");

    update();

    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
    gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, verticesZoom.length / 3);

    gl.glDrawElements(GL10.GL_TRIANGLES, 1, GL10.GL_UNSIGNED_SHORT, vertexBuffer);

    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
}
}

```

You can see from code that i change texture every 5 calls:

```
if(mSwitcher == 5){
 mFrame = ++mFrame % 4;
...
}

```

I want to change dynamically vertix to change zoom to my creature.

So every 5 calls on `draw` to increase zoom to texture by 1%.

I saw many examples how to do it for static image but not during the `draw`.

**comment**

I have 10-20 these objects and create them in different times. Therefore I need change size per object differently.

Can someone help me,

Thank you

# Answer
> 1 votes
The common practice to do this (in modern OpenGL) is using **shaders**. Specifically vertex shaders. Usually by using some kind of transformation matrix.

Here is a tutorial about doing what you did, and also how to do it using shaders. The tutorial is in c++ and using OpenGL and not OpenGL ES, but should be quite straightforward to understand as the difference between modern OpenGL and OpenGL ES is small.

**Edit:**

Shaders are basically some code run on the GPU in parallel. It is executed for each Vertex and then each Fragment(pixel).

**The Vertex shader's usual inputs are:**

* Vertex's Parameters:
    + Position
    + Texture Coordinates
    + Normals
    + etc.(Tangent, Bitangent, Vertex Color....)
* Textures
* Uniforms

**The Vertex shader's usual outputs are:**

* Vertex Position(always)
* Any parameters passed to the fragment shader

**The Fragment shader's usual inputs are:**

* Any parameters passed down from the vertex shaders (usually interpolated across the triangle)
* Textures
* Uniforms

**The Fragment shader's usual outputs are:**

* Pixel color data

As seen, both vertex and fragment shaders accept uniforms as inputs. These are variables set by your program to the shader and stay constant for each draw call. For the method I propose, you could use an `uniform mat4` type uniform, to pass a transformation matrix to the Vertex shader, and multiply the input vertex position with the matrix.

Here is a Vertex shader in GLSL version 420 to do this:

```
#version 420

layout(location=0) in vec3 in_Position;

uniform mat4 u_TransformMatrix;

void main()
{
    gl_Position = vec4(in_Position, 1.0) * u_TransformMatrix;
}

```

# Answer
> 2 votes
Well, didn't think that will find proper answer by myself,

I added to `update` method:

```
verticesZoom[4] = verticesZoom[4]*1.05f;
verticesZoom[6] = verticesZoom[6]*1.05f;
verticesZoom[9] = verticesZoom[9]*1.05f;
verticesZoom[10] = verticesZoom[10]*1.05f;

vertexBuffer.clear();
vertexBuffer.put(verticesZoom);
vertexBuffer.position(0);

```

Thank you anyways,

---
Tags: android, opengl-es
---


# Question
Title: Methodologies for deciding the number of characters a design should have?
I need to identify a maximum number of characters in a game so that I can provide a high number of choices without overwhelming the player. How do I determine the optimum set of characters to use in this case? Every set I come up with is either overwhelming for players or have too few choices.

# Answer
A simple litmus test: does this new character add anything to the game or is it just fluff?

As a broad guideline on what feels bloated and confusing versus short and under-featured, I use the following:

The magic number 7 plus or minus 2. This is the sweet spot of human short term, working memory capacity. More than this number of fundamental choices at any one time will confuse and frustrate a player. For a character this would be the core archetypes like plate tank, melee dps, ranged healer, etc...

The magic number 3. As a side effect of the 7 rule, combinations of up to 3 elements/features will get you from 1..9 (i.e. within the 7 +- 2 range) end results. Any more than 3 features on any given character will similarly confuse and frustrate a player because choice suddenly blossoms to 16 and up, breaking the rule of 7. For a character this would be the core play style choices like weapons, shield, mobility, or fire, ice, earth.
> 2 votes

# Answer
You have to ask yourself, "Is there an optimum set of characters?"

The answer is maybe. The optimum number will be different for every game, genre and developer. This decision is very specific to the design of the game. There are a few ways to go about finding what you believe to be the optimal number, I've ordered them based on the time/effort required to acquire your optimal number:

1. **Random guess, based on what you feel is right.** Likely the fastest approach. And once a decision is made, the actual development can get started.
2. **Use the average number of characters found in similar games.** A little more research oriented approach. First make a list of similar games, then count the total number of characters in all of those games added together. Finally, divide that sum by the number of games in the list. For non-whole numbers, round up or down, to decide see #1.
3. **Develop a prototype with a variable number of characters and playtest with a various groups of beta testers.** The empirical approach. It's a useful one, and will give you hard data about *your* game. As can be expected, this is probably the most accurate approach, but will take the most time. It can arguably be the best approach as well. Since it uses your game as the testing platform, it handles the situation where there aren't really any other games out there just like yours.

Unfortunately, there's not hard and fast rule for this. The number of characters you require to be optimal depends a number of things, including:

* The niches they fill (damage, defense, healing, etc)
* The gameplay strategies your players will use (kiting, tanking, dps, etc.)
* The gameplay strategies your game allows for (potentially different than the ones players use)
* If there are restrictions on duplication of characters in a game (a fighting game where characters can't fight themselves)
* The genre of your game (moba, mmorpg, single player rpg, fighting game, etc.)
* The skills and abilities of each character (balancing issues galore)
* What kind of gameplay there is (PVP, PVE)
* If there are factions or realms (now you might need to fill niches on both or multiple sides)
* The expected play time per character (if it takes a day to unlock all the skills a character has, vs weeks/months you might need a different number of characters)
* The price of the game (if the number of characters is a selling point, people want what they pay for)

If you decide the number of characters is 10, here's a question you can use to decide their color.
> 3 votes

---
Tags: game-design, character, balance
---


# Question
Title: What strategies can I use to update the visuals of my game to be more modern?
I'm making a browser strategy game.

Now my problem is that I have a feeling that my design is dated. For now I have only used background colors and borders to make things look nice, but I have planed to add some pictures later.

Here is what it looks like now:

*<sub>(Click for larger)</sub>*

You will see that the game has a top and bottom bar and has the main section in the middle. My main concern is that this may not be best idea, because not full width and height of the window is used.

What strategies can I use to update the visuals of the site to a more modern look?

# Answer
> 1 votes
Let the important content take as much space as possible. Show utility buttons (like add/remove) only when needed. Replace the wall of text with images where possible. Where not, keep the text short. Take example from the design of good browser-based games.

If you are having a hard type designing the page take a look at those UI libraries that can make your life easier:

JQueryUI

Bootstrap

Metro UI

Kendo UI

If those don't fit your design, use your favourite search engine to find more such libraries.

---
Tags: browser-based-games, php, graphics-design, html, css
---


# Question
Title: Whats the point of this LPDIRECT3DDEVICE9 reference?
I'm going through the DirectX 9 MSDN documentation

Which lead me to something rather peculiar, do you need a class reference in DirectX 9?

Can someone tell me what the point of the class reference:

`LPDIRECT3DDEVICE9 d3ddev;`

I don't see anything using it.

Also maybe point me in the direction to some decent documentation for DirectX 9 that explains this stuff like this:

```
LPDIRECT3DDEVICE9 pDevice = NULL;

D3DPRESENT_PARAMETERS d3dpp;

ZeroMemory( &d3dpp, sizeof(d3dpp) );
d3dpp.Windowed   = TRUE;
d3dpp.SwapEffect = D3DSWAPEFFECT_COPY;

```

in little bit more detail then slapping some code in your face with no actual description of what it's for.

# Answer
`LPDIRECT3DDEVICE` is a "long pointer" (common Win32 prefix LP) to a `Direct3D9Device`.

This is a handle to the driver context. It is what is responsible for issuing commands to the driver. There may be multiple drivers (if you have multiple cards), or an app may have multiple handles (if it needs to completely separate data), so the context is not implicit. This handle is also part of the COM interface to Direct3D, which requires a COM object instance.

`D3DPRESENT_PARAMETERS` is a set of data that informs Direct3D how to copy the back buffer and how the actual window is displayed. The lines you reference set the Direct3D display to windowed mode, which has some different characters to full-screen mode (in windowed mode, Direct3D cannot acquire ownership of the entire screen, so it must "play nice" with other apps). It sets the "swap effect" to copy, which means that the back-buffer is copied onto the front buffer whenever you *present* the backbuffer (usually at the end of each frame).

The call to `ZeroMemory` sets all the fields of `d3dpp` to 0, which are generally good default values. Remember that variables of POD (plain old data, like most primitive types and any C-style structs) are uninitialized when declare. You could manually set every field of `d3dpp`, but you'd just be setting most of them to 0 anyway, so the call to `ZeroMemory` is just more convenient. It's not bad practice in general for your own code since it helps protect against unintentional use of uninitialized fields if you add a new field to a struct. I tend to use `memset` instead for portability.
> 2 votes

---
Tags: 3d, directx, directx9
---