# Question
Title: Moving from A(x,y) to B(x1,y1) with constant speed?
I currently have something like:

```
float deltaX = point0.getX() - point1.getX();
float deltaY = point0.getY() - point1.getY();

```

And every 0.01 seconds I refresh my objects position like this:

```
object.setPosition(object.getX()-deltaX/100,object.getY()-deltaY/100);

```

So this moves my object from point0 to point1 in 1 second. What I need is having the 2 points, to be able to move the object from point0 ,facing(in the direction of) point1 with a constant speed. Thus, when I have a point closer to my initial point the object will move towards it with the same speed it does if I would have a farther point. Any suggestions are appreciated. Thanks.

# Answer
I'll use some linear algebra structures since it's easier to describe the operations that way. In case you don't know how to implement these vector operations I'll give a quick explanation at the end.

So let's say you start with these values: `start`and `end` mark the end points of the movement, `speed` is how many pixels it should move by second, and `elapsed` is the rate at which you'll update your object's position (some engines already provide that value for you):

```
Vector2 start = new Vector2(x1, y2);
Vector2 end = new Vector2(x2, y2);
float speed = 100;
float elapsed = 0.01f;

```

The first thing you'll want to calculate is the distance between both points, and a normalized vector containing the direction from start to end. Also, you should "snap" the object position to the `start` point. This step is done only once, at the beginning:

```
float distance = Vector2.Distance(start, end);
Vector2 direction = Vector2.Normalize(end - start);
object.Position = start;
moving = true;

```

Then on your update method, you move the object by adding a multiplication of `direction`, `speed` and `elapsed` to its position. After that, to check if the movement is over, you see if the distance between the start point and the object's current position is *greater* than the initial distance you calculated. If that's true, we snap the object's position to the end point, and stop moving the object:

```
if(moving == true)
{
    object.Position += direction * speed * elapsed;
    if(Vector2.Distance(start, object.Position) >= distance)
    {
        object.Position = end;
        moving = false;
    }
}

```

---

**Quick Vector Operations Reference**

*Representation*

```
Vector2 A = float aX, aY;

```

*Sum / Subtract*

```
A+B = a.x + b.x; a.y + b.y;
A-B = a.x - b.x; a.y - b.y;

```

*Multiply by Scalar (float)*

```
A*float = a.x*float; a.y*float;

```

*Length / Distance*

```
length(A) = sqrt(a.x*a.x + a.y*a.y)
distance(A,B) = length(B-A)

```

*Normalize*

```
normalize(A) = a.X/length(A); a.Y/length(A);

```

That should be enough to convert the above code into regular operations if you don't have a `Vector` class available to you.

---

**Example of Conversion**

```
// Your Variables
float startX, startY, endX, endY;
float speed = 100;
float elapsed = 0.01f;

// On starting movement
float distance = Math.sqrt(Math.pow(endX-startX,2)+Math.pow(endY-startY,2));
float directionX = (endX-startX) / distance;
float directionY = (endY-startY) / distance;
object.X = startX;
object.Y = startY;
moving = true;

// On update
if(moving == true)
{
    object.X += directionX * speed * elapsed;
    object.Y += directionY * speed * elapsed;
    if(Math.sqrt(Math.pow(object.X-startX,2)+Math.pow(object.Y-startY,2)) >= distance)
    {
        object.X = endX;
        object.Y = endY;
        moving = false;
    }
}

```
> 33 votes

# Answer
Copied and pasted from my answer to: Get points on a line between two points

In Pseudocode:

```
speed_per_tick = 0.05 //constant speed you want the object to move at
delta_x = x_goal - x_current
delta_y = y_goal - y_current
goal_dist = sqrt( (delta_x * delta_x) + (delta_y * delta_y) )
if (dist > speed_per_tick)
{
    ratio = speed_per_tick / goal_dist
    x_move = ratio * delta_x
    y_move = ratio * delta_y
    new_x_pos = x_move + x_current
    new_y_pos = y_move + y_current
}
else
{
    new_x_pos = x_goal
    new_y_pos = y_goal
}

```
> 5 votes

# Answer
Create a Vector and normalize it. Warning, some pseudo-code with wrong numbers ahead:

```
Vector = new Vector(point0.getX() - point1.getX(), point0.getY() - point1.getY());

```

This will give you a Vector like:

```
25.96; 85.41

```

Now normalize the vector, and you'll receive this:

```
0.12; 0.75

```

From here it's the same movement as with your delta.
> 3 votes

---
Tags: game-mechanics, movement
---


title: Texture swapping and 2d Drawing in Xna

text:
# Question
Title: Texture swapping and 2d Drawing in Xna
Usually in 3d drawing you want to ideally have fewer larger textures rather than lots of smaller ones, and make sure you render the same kinds of textures at the same time. So there is less texture swapping going on behind the scenes.

This is not a difficult thing to do as most textures are purely used for models or terrains/structures. So you may have a terrain texture, a structures texture and a couple of player/enemy textures. Then just draw the terrain, the structures and any enemies and the player, only requiring a few texture swaps there, and if you are also using some sort of model instancing for the enemies you can get away with some other improvements there.

Anyway now enter the 2d drawing world, rather than applying a texture and then drawing lots of vertices using it you are giving a texture to each draw command. So I am wondering how XNA handles this behind the scenes.

Take for example a top down 2d game, you have a tileset for the level containing many ground sprites, an enemy sprite sheet which may contain anywhere from 10-20 enemies sprites and animations, then possibly a player/equipment sheet which contains anything for them.

Now in this instance if I were to draw my level which was lets say 64x64 tiles (a tile being an x,y,tileSetIndex), and I have a tileset with 8x8 sprites (lets say 32x32 each):

```
var tileSetSourceRect = someTilesetEntity.GetSourceRectForIndex(tile.tileSetIndex);
mySpriteBatch.Draw(someTilesetEntity.TilesetTexture, tileSetSourceRect , tile.Position, Color.White);

```

assuming no real optimisations and just looping through every tile would this just retain the tilesetTexture in memory, or is it going to keep removing/adding the texture after every Draw() call? As I do not know how it can manage this unless it keeps some state under the hood between draw calls (maybe thats what Begin/End is for on spriteBatches).

So will I be getting 4096 (64x64 tiles itterated) texture swaps, or will it only do 1 texture swap in this instance?

# Answer
**Short Answer**

In that example, only one texture swap.

**Long Answer**

Since there was no actual texture change between `Draw` calls, only source rectangle changes, it would retain the texture and you would only get one *set texture* operation in total. Also, because there was no texture change, you would have the added benefit that all the vertices generated for the sprites would be batched into the *same* vertex buffer and submitted only once.

If on the other hand you did change textures between `Draw` calls, then the result would depend on the SpriteSortMode you chose when calling `Begin`.

By default it uses `SpriteSortMode.Deferred`, which has the implication that every time you change a texture it needs to stop batching, render the previous batch contents, and then start batching the new values. This of course requires a texture swap and a new vertex buffer too, but note that this *only* happens when you call `End` (hence being called *deferred*). So in sum, the more texture changes you make, the more it has to work behind the scenes.

On the other hand you can also use `SpriteSortMode.Texture` which works just like `SpriteSortMode.Deferred` but *sorts sprites by texture before drawing*. This will result in the minimum possible amount of draw operations, but can also mess up your draw order.

Finally if you choose `SpriteSortMode.Immediate`, sprites are drawn immediatly after you issue the `Draw` call. In this case I'm actually not sure about the details, but I am guessing you'd also get as many texture swaps as there were draw calls, since there's no batching taking place.

Check this answer for more insight on how `SpriteBatch` works.
> 1 votes

---
Tags: xna, 2d, textures
---


title: Efficient Isometric 2.5D Game Engines?

text:
# Question
Title: Efficient Isometric 2.5D Game Engines?
I want to make a game (turn-based RPG) that looks very similar to Bastion.

Here is what I need to implement:

-\> The overworld is 2d, with an isometric view. The graphics would in no way be rendered in 3D, but rather drawn in 2d.

-\> The characters would be rendered in 3d, moving about in the 2d isometric world. (Even if the characters are in 3D in a 2D environment, its not much of an issue since a 3D character may actually be rasterized in a series of 2D images, in other words, this isn't much of a problem I feel)

I have looked at several game engines, but I find it very difficult to know which would be best to implement this sort of look and feel. Which game engine do you guys feel could be best for me so that I would have the least amount of coding to do for purely the isometric view aspect?

# Answer
2D isometric is just a 3D orthographic projection, with a little camera work you could use almost any 3D engine really. The screenshots that I find of Bastion look like they **are** 3D rendered, but built simply and angular like it was built on a 2D grid.

Note that similar games like Diablo3 or Wakfu that look like they are 2D are really built and rendered in 3D.

The key words and features you need to look for when considering engines now is whether the camera is is programmable and it can do an orthographic projection. Also you will need to change the character controller to gracefully handle diagonal movement.
> 7 votes

# Answer
It could be any 2D engine, but you need to design your tiles somewhat diferent. Also remember that you need to draw your tilemap from top-left to bottom-right to paint the nearest tiles in the last time, so nearest tiles are always painted over the other tiles.

You can refine your algorithm by making semitransparent or not drawing tiles when these tiles are painted over sobre important tiles (your player, enemies, etc)
> 4 votes

---
Tags: isometric, rpg, 2.5d
---


title: Grid/cell based light system

text:
# Question
Title: Grid/cell based light system
I am working on a top-down, 2d cell-based RPG game. I would like to implement a cell based lighting system, something like this and this.

I basically have several light sources and light deteriorates on every cell in every direction. Something like the below (numbers represent the level of light in each cell):

```
1 1 1 1 1 0 0 0 0 0 0
1 2 2 2 1 0 0 1 1 1 0
1 2 3 2 1 0 0 1 2 1 0
1 2 2 2 1 0 0 1 1 1 0
1 1 1 1 1 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 1 1 1 0 0 0 0
0 0 0 0 1 2 1 0 0 0 0
0 0 0 0 1 1 1 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0

```

So basically I insert a source of light of "strength" `x` at a given spot. I then set the surrounding cells' light strength to `x-1` and so on until I reach zero (or a set global minimum value). I am looking for an efficient algorithm to implement and generate such a lightning grid based on my light sources and any tips regarding such implementation.

I am currently **not** looking into field of view algorithms, just an efficient way of generating the above. Any help will be much appreciated.

EDIT: Just to clarify, this should handle movement of light sources (e.g. player walking with a torch).

EDIT2: Ok, I've solved my problem myself based on the simple distance suggestion by Jari (thus I'll accept his answer although I'm still looking for a more efficient way of generating such array). If anyone's interested here is a demo of what I came up with (multiple light sources with alpha compositing)

# Answer
> 4 votes
I'd probably just create a 256x256 (or some such) pre-calculated array and scaled that as needed; that way you can do all sorts of special lights if you want as well.

Going procedurally, the easiest way would probably be to just calculate the distance.

```
xd = posx-centerx
yd = posy-centery
dist = sqrt(xd*xd+yd*yd)
pow = maxpow - dist
if (pow < 0) pow = 0

```

and then just draw a (maxpow\*2)-1 square around the light center..

Something like that. Doesn't give exactly the results you mentioned, because this one generates a more round light (yours are rather square).

# Answer
> 0 votes
You could treat the light as a fluid that flows outwards from the light source and is blocked by certain blocks. You could then model this using cellular automata

---
Tags: 2d, lighting, grid
---


# Question
Title: suggestion for a “strategy game” like platform to test AI algorithm
I wrote a piece of tricky AI algorithms that simulates animals living in an environment and their food seeking, interacting with each other and especially learning new patterns of lifestyle.

now I want to add some graphics to it. so instead of a form with colored dots I would see a 3d environment with different objects moving on it, just like an strategy game.

my code is in VB.net and it uses lots of advanced oop techniques and dynamic nested classes. so changing code to another platform like python, c++ or java is not and option for me. also I am not a trained graphic programmer so which graphic platform I get is what I use as graphic output. If I could only have source of a simple strategy game it would be enough for me.

also any link to opensource .Net strategy games or any source code that can hemlp me in this concept is appreciated.

# Answer
> 4 votes
Check out Mogre (Managed Ogre), its a Graphics rendering engine (not a game engine), which seems ideal for your situation. Mogre is a .NET binding for Ogre, so it works with C# and VB.NET. There are tutorials for both on the wiki: http://www.ogre3d.org/tikiwiki/MOGRE

It is quite simple and fun to use, and should be easy to incorporate into your project.

An alternative is XNA - I know it is mainly used in C#, and im assuming it also works in VB.NET, but im not sure. XNA is a pretty well established game engine, so if you get it working that is also a great choice.

Something else that you might be interested in is a decent physics engine to help your simulation: There are many good ones (check the mogre wiki/forums), but the one I find best and am using currently is BulletSharp (http://code.google.com/p/bulletsharp/)

If you need any help with Mogre/BulletSharp, let me know :)

Good luck!

---
Tags: graphics-programming, .net, strategy
---


title: Giving the illusion of speed

text:
# Question
Title: Giving the illusion of speed
I'm making a racing game that feels a lot like xtreme g 64 or fzero.

Making the player feel like they are moving extremely fast is important for this game. Actually moving them fast enough to give them that feeling is out of the question. Collision detection and a few other aspects of the physics engine prohibit it.

My current solution is the following:

* Map the speed to the field of view for the projection matrix so that the FOV is 30 at speed x and 100 at speed y with a linear increase for the FOV inbetween x and y. This will probably be some polynomial once I test it out some.
* Trail render any light sources on the vehicle. I am just adding a trail rendered blurred object of the same color as any light source: tail lights, jet flames, etc.
* slight camera shake when you are above 3y/2 speed
* your max speed without a boost is y/2, when you have a boost the max speed is y and these effects all become pretty noticeable

**My Question: I can't do any post processing effects on the iphone. I'm limited to poor mans solutions like the one I did. Is there another approach that is more common or better? My solution seems like what they would have done back in the N64 days so I'm wondering if there's a better way. The problem with this solution is that it makes it seems cheap to stretch the FOV like I am. It's a cool effect, but still feels cheap when you play it.**

Here's a link to a very limited version of my effect

The speed they are simulating is supposed to be 400kph, I'm simulating about 2000 meters per second, about 18 times their speed. so my effects are very exaggerated.

Note: I'de give you a screenshot but setting up a test scene that doesn't display the art assets would be hard. Setting up one with the art assets would get me sued. My object is on the ground so I'm avoiding effects that are used more for aircraft. There is no wind or dust so that is a little more limiting in using those elements.

# Answer
Place the camera closer to the ground. The closer you are to the ground, the faster it appears to zoom past you.
> 9 votes

# Answer
Just thinking out loud: If your road texture includes dashed lane lines, you can send a texture coordinate offset to the shader each frame that will effectively scroll the road's texture backwards under the car. The change in offset amount each frame would be a relationship of speed.
> 1 votes

---
Tags: graphic-effects, special-effects
---


# Question
Title: What basic non-games related computer knowledge should a games programmer possess?
So the question will very likely need re-phrasing. I thought about asking this for a while, but held off because it's a tad vague.

To explain - I have been a programmer for 4 years and only begun doing it when I took a university course. Now that I'm working as a programmer, I find that often people assume you know a number of things that I feel people who have been messing around with computers know by default, and I don't.

Things like shell commands, how to use subversion, stuff about how websites work at their base level, how to use databases and so on.

What I would like to know is some of the basic stuff, the nitty gritty that people in a programming job are expected to have encountered and know how to do.

Also, I'm sorry if people feel this question is not a perfect match for the Q and A format - please let me know how I can improve it - or just edit it heavily.

Thank you in advance.

# Answer
> 1 votes
I'de say the following is important:

* Algorithm efficiency (knowing which algorithms are more efficient for which problems and what heuristics to apply for which problems is very important in AI, graphics, and a few other parts of game programming). I'm a hobby interviewer and have encountered this more than anything else I'll mention.
* Heavy object oriented knowledge (beyond the basics of object oriented design with polymorphism, inheritance, generics (in languages where applicable), and other abstractions, you really need to know how to design an object oriented program. If you're going for entry level game programming, knowing how to design it atleast in concept, will help you navigate your peers code at the very least.)
* Know different design patterns (In commercial game code I've seen, you tend to run into a lot of versions of the common patterns like observer, monitor, facade, etc)
* know SVN, shell, other stuff you mentioned. These are essentials and can easily be learned in a week if you dedicate some time. Using them right comes with practice, so I'de use them for all personal projects no matter how trivial for a while.
* It's not computer specific, but the more advanced your game, likely the more you will need linear algebra. Knowing what types of transformations will do what to matrices and what these matrices represent proved to be a great help. Once I learned this stuff, working with vectors, image effects, and projection matrices became really easy.

# Answer
> 3 votes
I wouldn't stress out too much about not knowing stuff in advance. I've spent years hearing people talk about stuff I didn't already know (I didn't study computer science in school) and it used to intimidate me, but the pattern I eventually started to notice is that people almost always talk like they knew it forever and everyone should already know it, but that's rarely actually true and it's not a big deal for me to simply make a note "someone mentioned X; learn about that" and then figure it out.

You may have heard that a programmer needs to learn new stuff constantly and one of the most important skills a programmer needs is the ability to learn new stuff quickly. Well here's why.

---

For example, to address the exact list you gave, here is how I learned that stuff:

I first learned to work with shell commands because I started using computers back in the days of DOS. Obviously I was only doing the simplest command-line stuff, but the point is I got comfortable working that way and have no problem picking up other stuff on an as-needed basis.

I learned about SVN at a job a few years ago. This was the clearest case of what you described, where other programmers at that job behaved as if everyone should just know stuff by default, but it wasn't hard to learn SVN and that is just one of several really useful things I learned at that job.

I started learning how websites work back when I made my first website in highschool, and I've been gradually adding bits and pieces of knowledge over time. There's no clear moment of learning I can point to.

I still don't know much about how databases work, because I'm mostly a client-side programmer. When I once needed to query a database directly I learned a few SQL commands on an as-needed basis, but beyond that I don't know much. *shrug*

---
Tags: software-engineering, jobs
---


# Question
Title: How can I animate a colour change over hue/saturation/value instead of RGB in Blender?
If I create a keyframe for a colour in Blender (I'm using 2.6) it always seems to traverse the RGB values for the animation, even if I set the colour using HSV values.

I do this by setting the colour, using HSV, then pressing `i` over it.

How can I animate the HSV values rather than the RGB values?

# Answer
> 2 votes
It is possible by using material nodes. If you use a `Hue Saturation Value` node in your node setup, you can animate any of the `HSV` values with the same method as you described (pressing `i` key over the field that should be animated).

In the screenshot you can see a possible setup. I'm using a `HSV` node as the input for the materials color. I set the base color-value of the `HSV` node to `0.5, 1.0, 1.0` (cyan blue), as this seems to produce correct output colors then (eg. a hue of 0.0 or 1.0 is red).

---
Tags: graphics, blender
---


# Question
Title: Giving points to users - how can I make it interesting?
I have a website where users can choose the winner of a sporting event. If they guess correctly they get 1 point, otherwise they receive zero points. At the end all users are ranked based on their score, which is computed like this:

```
score = points * (number_of_guesses / number_of_misses)

```

It's a rudimentary system but it works alright. However I am looking for a points system that's more interesting to the user, that makes the game more engaging. For example giving more points for picking the underdog in an event might make the game a bit more interesting.

Can you offer me some suggestions?

# Answer
> 6 votes
This is pretty much what normal betting is about, so checking out what bookmakers do is certainly good research.

**Stating percentages**
One game that force players to consider the chances of the underdog is having them state the chance of each possible outcome instead of just choosing one. So if GreatTeam is playing against NotSoGreatTeam a player might put 95% on GreatTeam and 5% on NotSoGreatTeam.

The trick to making this work is to have a scoring rule that on average pays the most when you guess the right percentages. Here is a simple formula that does the job:

```
Score = 1 - (1 - [dictated chance of outcome])^2

```

So in the example the player would score 0.9975 points if GreatTeam won and 0.0975 points if NotSoGreatTeam won, averaging 0.9525 points if the 95/5 split is correct, which is more than any other guess.

The weakest point of this system is that it relies on the players trusting that the formula actually works as advertised, since there is no way you are going to be able to explain it to the majority. There will from time to time be a simpleton claiming that it's all a lie and the best option is to put 100% on the most likely outcome, but I'd consider that part of the fun.

The formula by the way still works if there is more than 2 possible outcomes.

**Greater score for minority bets**
A simple way of giving more points for betting on outsiders is to distribute the same number of points per participant no matter how many or few players hit the right answer. So for each winning player:

```
Score = [Participants] / [Correct guesses]

```

Alternately written as:

```
Score = [Fraction of players who guessed correctly] ^ -1

```

This should make it advantageous for a small part of the players to take the side of the underdog, though if too many do so the advantage will be too low. Thus how much information on the other players choices you disclose will make a big difference, players might want to move their bets if too many bet like them.

# Answer
> 1 votes
You could map the points distribution to an asymptotic curve (like dividing by the exponential function, for example).

In other words, you could define a point cap on the award, and then calculate it as follows:

```
score = max_points * (number_of_guesses / number_of_misses) / exp(player_rep)

```

Where **player\_rep** is some form of metric indicating the player's likelihood of success or overall reputation.

---
Tags: game-design, web, competition, ranking
---


title: 2D overlays in 3D environments

text:
# Question
Title: 2D overlays in 3D environments
For a 2D overlay in a 3D environment using DirectX, is the 2D overlay still coded as a surface in 3d always positioned in front of the camera?

I haven't tried this yet but I imagine that technique would lead to small jitters as a scene moves, plus lighting weirdness. It would help me to know the correct way before I struggle in the wrong direction.

I'm very new to DirectX and game programming and I have limited experience with the paradigms of unmanaged APIs. I'm using C# with SlimDX. I have a re-organized version of the SlimDX Triangle tutorial working well.

What I read on this site and others regarding DirectX is that DirectX *only* draws/shades triangles and the rest is up to me.

SlimDX seems to have some stuff in the DirectX2D namespace - RenderTarget, which has a DrawText() method, but I can't figure out how to get such a 2D RenderTarget hooked to my scene to play with it.

Thanks!

# Answer
> 3 votes
When drawing 2D overlay disable any lighting and depth test. And set camera projection matrix to orthographic, so no jitter will be present - and you will be able to achieve pixel-perfect mapping.

Not sure which version of Direct3D are you using (9/10/11) but here's nice explanation for Direct3D11: http://www.rastertek.com/dx11tut11.html

# Answer
> 1 votes
The key to rendering a UI and it's windows is to use textured quads (two triangles) in screen space (or transformed to screen space using an orthogonal projection instead of your standard perspective projection).

However, to properly do this you will need to disable your depth buffer and render your UI last on top of everything else. This way your quads won't potentially be depth clipped or overwritten in the output merger stage of the pipeline.

And since it's a UI, I expect you want to use it for displaying text too. This is achieved in the same way however it takes a bit more work. First you will need a texture of all your characters. Then for each character, render a quad to the screen and adjust it's UV coordinates in order to have it sample the right character.

I believe DirectX11 has no built in rendering support for text but earlier versions and the DXUT library do. (I think!)

---
Tags: directx, slimdx
---


# Question
Title: How to interpolate a height-map with normals
### My Task

I want to interpolate a heightmap by using the normal of each nearby point of the heightmap which is calculated before. When having 4 Points before i gonna have 9 points after it. ( See this question to get a image of it how it's working ).

### My Approach

I want to interpolate the height of two points by using the normal of them. To do this i need the tangent of both. When having the tangents i want to interpolate this way:

```
float resultHeight = Interpolate(TangentVector0, TangentVector1, 0.5f);

public float Interpolate(float p0, float p1, float amount)
{
    amount = Math.Sin(x* Math.PI - Math.PI/2) / 2 + 0.5;
    // Move vectors along tangents
    p0 = p0 * (amount - 1f);
    p1 = p1 * amount;
    return (p0 + p1) / 2f;
}

```

### Problem ( Question )

I'm a little bit stuck with the math behind. How to i get the tangent of the x or z axis when having a 3D normal.

# Answer
> 2 votes
It sounds like you might want bicubic splines. In particular, since you have two endpoints and a tangent vector at each endpoint, Hermite splines would be appropriate.

To expand, if you have the heights of two adjacent points, `h0` and `h1`, and the normal vectors of the heightfield at those points, `n0` and `n1`, here is how you'd do the interpolation. This assumes that we're interpolating along the X axis and `h1` is to the right of (at a greater X value than) `h0`.

```
public float InterpolateHeight(float h0, float h1, Vector3 n0, Vector3 n1, float amount)
{
    // Calculate slopes along X axis (this incorporates rotating 90 degrees
    // to get the tangent and then taking the y/x slope of the tangent vector)
    float s0 = -n0.x / n0.y;
    float s1 = -n1.x / n1.y;

    // Interpolate using cubic Hermite spline
    float amountSquared = amount * amount;
    float amountCubed = amountSquared * amount;
    float a = 2.0 * amountCubed - 3.0 * amountSquared + 1.0;
    float b = amountCubed - 2.0 * amountSquared + amount;
    float c = -2.0 * amountCubed + 3.0 * amountSquared;
    float d = amountCubed - amountSquared;
    return a * h0 + b * s0 + c * h1 + d * s1;
}

```

# Answer
> 1 votes
If you have 3D normal, you can compute tangent in X direction as the cross product of normal and vector heading to Z direction, so `tangent_x = cross(normal, VectorToZ)`, and `tangent_z = cross(normal, VectorToX)`. I'm now not sure about the order of vectors in brakets - it depends on right or left handed system (which one you are using).

If you don't want to use normals, you can calculate slope and then tangent vector. You can use derivation of surface. You can do it for example this way:

```
slope_in_x = f(x + 1, z) - f(x - 1, z)
slope_in_z = f(x, z + 1) - f(x, z - 1)

```

where x and z are your x and z coordinates and function f returns height in point (x, z). From this, you can calculate tangent as this:

```
tangent_x = (1, slope_in_x, 0)
tangent_z = (0, slope_in_z, 1)

```

And then just normalize these vectors.

---
Tags: 3d, mathematics, normals, heightmap
---


# Question
Title: Relative and absolute position with sprites in libgdx
In libgdx, can i add a sprite as children of another an set it with the relative coordinates of the father and not the stage?

Like in HTML when you add controls they are relative to its parent, but here i want it with sprites, i add the children in a Group class but the coordinates are absolute (relative to the stage)

# Answer
> 2 votes
I've never worked with libgdx and only briefly checked its documentation. I'm not aware if it has support for what you're asking out of the box, but even if it doesn't have, you can still emulate it yourself with a bit of work. I've written about a related topic before here. It's written for XNA but the concepts are universal, so hopefully it will give you a starting point if you really need to implement it yourself.

Basically you'd want to start by encapsulating the sprite class in a new class of your own, by adding a list to hold the children sprites, and optionally a link back to the parent sprite.

After that, I'm not going to go into much detail because I've already described the procedure in the other question, but basically it consists of creating a world matrix from each sprite's "relative" position/rotation/scale. To transform from "relative" to "absolute" you need to multiply that sprite's "relative" matrix by the parent's "absolute" matrix. This is done all the way to the top of the hierarchy, i.e. at the top level there's no difference between "relative" or "absolute".

Finally, after you have the "absolute" matrix calculated, you decompose it to get back the correct position/rotation/scale to set your sprite to.

You can probably also do it without matrices too but I've never figured the calculations out.

---
Tags: android, sprites, libgdx
---


title: Starting my own development company

text:
# Question
Title: Starting my own development company
I completed my postgraduate education, and I am interested in starting my own game development company.

I have a team of six members consisting of animators and artists.

I'd like you to suggest all the requirements for starting a new company and suggest whether it would be good for me to start it or not. I have a few game concepts, and I am really passionate about it.

# Answer
> 12 votes
**Today's markets** are literally flooded with both products and startup companies struggling to get their share, especially in game development. As I see it, the days when it was enough to be passionate about doing something to be successful are over, not only in game development.

Not that I want to discourage someone, but being passionate and having great ideas is just not enough. Success of startups now more than ever depends on how they can sell their products and themselves. Therefore the entrepreneurship/business/economy/financial/marketing/PR/... skills and knowledge are more important for success than the quality and greateness of the product itself and more important than the skill you want to sell in the first place.

-

**For me**, this is a sad situation. As a passionate programmer, I always did want to have a small programming shop, make things small but great. And I still do. But this would now require me to keep most of my focus on the business side of things, which do not interest me at all, and leaving very little room for what actually matters the most to me - doing the programming, making great products. So I waver around the option of starting a company for some time now and I don't see this changing soon.

-

**Regarding your situation**, having a great team ready up front will definitely spare you a lot of hassle. I know it is hard to get people to your cause, even if they are a long time friends and great in their profession.

As for what you should focus on next, I would say those business and enterpreneurship topics, especially if you haven't considered these things yet. Not only it is really important, but most of it can't be avoided somewhere along the way, so better start with it right now.

Whether you should start the company or not depends on how you will feel after you take the business things into account. I think this is not a bad indicator when you are up to something.

* Will you still be confident about it after you know all what it takes?
* Will you not mind keeping up with a lot of stuff, that may not have anything to do with games or development?
* Or will you have this unease feeling in your guts just by picturing the situation? (my case)

Of course you don't have to be the person in charge of all this. In that case:

* Do you have people in your team, who will take this over and who you trust will do it well?

Game development may be a unique industry in many ways, but it is still the same business as any other and the same business rules apply when you aim for success, so treat it appropriately.

I also recommend you to take a look at **OnStartups exchange**, in case you didn't yet.

-

I hope I at least provided another perspective on the subject.

# Answer
> 4 votes
I think you should have really good strategy how to get your games to people. There are tons of games in these days and it's really hard to push your games through.

Maybe you should think about some publisher.

# Answer
> 4 votes
I'm not sure what 'pg' is, but can I assume it's educational related? If so, then are you and your other team members currently working full time in other jobs? If not, then you may have a great opportunity to start a game development company.

I work full time as a computer programmer, but not in the gaming industry. I make great money and I'm very grateful for my job. I just wish I could switch to a game programming role, but without any portfolio or industry experience, I would start at a very low wage (I assume a 50%-75% pay cut!). My current monthly expenses prevent that.

Me and my three nephews (we're ALL programmers and NO artists!) started our company a year or so back. I can only work after my day job and other commitments, and same as my nephews. We can't even work on the same project, as we're never together, so we have 3 projects on the go. If LUCKY, we'll have two games done by summer.

You on the other hand have two options.
Get an industry position, if you can find one. Or, start your own company, but expect to wait 6+ months (and that's not guaranteed either) before expecting any payments to start coming in. Can you last that long without an income? As a recent student, maybe you can. Can ALL of you?

If you need a regular job, you could try working after working hours, like we are. You may find life gets in the way, or your other partners aren't all at the same enthusiasm level.

How are you going to split / distribute the profits? What if 4 people do 99% of the work? Who's going to pay for the initial expenses? The start up costs could be minimal. You all probably have your own computers. You would need to purchase development software, so keep than in mind. Plus other misc fees and licenses.

Be warned, when you are finally 90% done your game, you'll realize that you still have the last 90% remaining! There are so many fine details to take care of.

Ideally your team should have somebody dedicated to programming, art, music/sound, marketing/promotion/PR, business/managing. Game assets can be purchased / licensed by other companies, but having a team member dedicated means your final product (and future products) will have a consistent look and feel, and ambiance.

If you still are considering it, I'd say go for it, the experience could be very rewarding. If you finish a product, then AT LEAST you have something for your portfolio. Something to set you apart from the other hiring candidates if you end of looking for an industry position.

Just don't EXPECT to make money. If you expect money, then maybe a regular job may be better. My priorities would be to actually finish a game, gain peer and public recognition, then perhaps make a profit. That may take you 2 or 3 games. It may never happen. There's a big risk you'll dedicate 6-12 months on a game, and never realize any profits. What's your motivation? What is your other team members' motivation?

# Answer
> 3 votes
It is the same for any Industry... It is Hard out there.

It will never get easy so now is as good time to jump in and try as any. You are young and full of energy and will gain much experience from it.

The older you get, the harder it becomes to recuperate from a failed risk... So risk big while your young, learn from everything, don't look back and go succeed!

---
Tags: publishing
---


# Question
Title: What are the drawbacks of this messaging system implementation?
So I've just been thinking about component and messaging systems recently for simple C# XNA games and came up with this. How extensible would this implementation be and what are the drawbacks? Example below:

## Score

```
class Score
{
    public int PlayerScore { get; set; }

    public Score()
    {
        EnemySpaceship.Death += new EventHandler<SpaceshipDeathEventArgs>(Spaceship_Death);
    }

    private void Spaceship_Death(object sender, SpaceshipDeathEventArgs e)
    {
        PlayerScore += e.Points;
    }
}

```

## EnemySpaceship

```
class EnemySpaceship
{
    public static event EventHandler<SpaceshipDeathEventArgs> Death;

    public void Kill()
    {
        OnDeath();
    }

    protected virtual void OnDeath()
    {
        if (Death != null)
        {
            Death(this, new SpaceshipDeathEventArgs(50));
        }
    }
}

```

## SpaceshipDeathEventArgs

```
class SpaceshipDeathEventArgs : EventArgs
{
    public int Points { get; private set; }

    internal SpaceshipDeathEventArgs(int points)
    {
        Points = points;
    }
}

```

Basically, the idea uses the built in events system in C#. When something interesting happens to an object, it raises a static event. Then, anything else in the game that wants to know when that happens subscribes to that static event and does something in response. In this case, the Score class subscribes to the static Death event of a Spaceship and when it dies, it uses the EventArgs to adjust the score accordingly.

Would this kind of architecture start to crumble and get quite confusing as the development of the game progressed? Thanks for reading.

# Answer
> 6 votes
That is a perfectly reasonable approach, and is quite common. I do it myself and find it makes for really clean and powerful code. Do watch out for strong references created by event listeners though, here's an article on that: http://www.codeproject.com/Articles/29922/Weak-Events-in-C

---
Tags: xna, c#, architecture, entity-system
---


# Question
Title: How do you split indices and vertices if their quantity goes over the limit?
I want to draw a flat surface of 500x500 squares which are built out of four vertices by two triangles.

There are 1,000,000 vertices and 1,500,000 indices.

The Reach profile of xna, limits primitives to 65535 per draw call.

My thought was to split whole data twice, first for indices using the same baseVertex, and second to stay beyond 65535 (ushort.MaxValue).

```
static class Painter
{
    public struct IndexedPrimitives
    {
        public PrimitiveType Type;
        public int baseVertex;
        public int minVertexIndex;
        public int numVertices;
        public int startIndex;
        public int primitiveCount;
    }
    public struct IndexedPrimitivesList
    {
        public VertexBuffer vb;
        public IndexBuffer ib;
        public IndexedPrimitives[] primitives;
    }
    public static IndexedPrimitivesList GenerateIndexedTirangleList(GraphicsDevice GraphicsDevice, VertexBuffer vb, int[] indices)
    {
        IndexedPrimitivesList ret;
        List<int> breaks = new List<int>();
        breaks.Add(0);
        List<int> levels = new List<int>();
        levels.Add(0);
        ushort[] inds = new ushort[indices.Length];

        for (int i = 0; i < indices.Length; i++)
        {
            if (indices[i] / (ushort.MaxValue + 1) != levels[levels.Count - 1])
            {
                levels.Add(indices[i] / (ushort.MaxValue + 1));
                breaks.Add(i);
            }
            inds[i] = (ushort)indices[i];
        }
        indices = null;
        ret.ib = new IndexBuffer(GraphicsDevice, IndexElementSize.SixteenBits, inds.Length, BufferUsage.None);
        ret.ib.SetData<ushort>(inds);
        inds = null;
        for (int i = 1; i < breaks.Count; i++)
        {
            if ((breaks[i] - breaks[i - 1]) % 3 != 0) throw new Exception("Triangles are using to far away vertices, or bad placed indices, foreach index of a triangle it needs index/65536 to be equal");
        }
        List<IndexedPrimitives> prims = new List<IndexedPrimitives>();

        for (int i = 1; i < breaks.Count; i++)
        {
            int r = breaks[i] - breaks[i - 1];
            while ((r / 3) / (ushort.MaxValue + 1) > 0)
            {
                IndexedPrimitives ip = new IndexedPrimitives();
                ip.Type = PrimitiveType.TriangleList;
                ip.baseVertex = levels[i - 1] * (ushort.MaxValue + 1);
                ip.numVertices = ushort.MaxValue + 1;
                ip.startIndex = breaks[i] - r;
                ip.primitiveCount = ushort.MaxValue;
                prims.Add(ip);
                r -= (ushort.MaxValue + 1) * 3;
            }
            if (r != 0)
            {
                IndexedPrimitives ip = new IndexedPrimitives();
                ip.Type = PrimitiveType.TriangleList;
                ip.baseVertex = levels[i - 1] * (ushort.MaxValue + 1);
                ip.numVertices = ushort.MaxValue + 1;
                ip.startIndex = breaks[i] - r;
                ip.primitiveCount = r / 3;
                prims.Add(ip);
                r -= r;
            }
        }
        int rr = ret.ib.IndexCount - breaks[breaks.Count - 1];
        while ((rr / 3) / (ushort.MaxValue + 1) > 0)
        {
            IndexedPrimitives ip = new IndexedPrimitives();
            ip.Type = PrimitiveType.TriangleList;
            ip.baseVertex = levels[levels.Count - 1] * (ushort.MaxValue + 1);
            ip.numVertices = ushort.MaxValue + 1;
            ip.startIndex = ret.ib.IndexCount - rr;
            ip.primitiveCount = ushort.MaxValue;
            prims.Add(ip);
            rr -= (ushort.MaxValue + 1) * 3;
        }
        if (rr != 0)
        {
            IndexedPrimitives ip = new IndexedPrimitives();
            ip.Type = PrimitiveType.TriangleList;
            ip.baseVertex = levels[levels.Count - 1] * (ushort.MaxValue + 1);
            ip.numVertices = vb.VertexCount-ip.baseVertex-1;
            ip.startIndex = ret.ib.IndexCount - rr;
            ip.primitiveCount = rr / 3;
            prims.Add(ip);
            rr -= rr;
        }

        ret.vb = vb;
        ret.primitives = prims.ToArray();
        return ret;
    }
    public static void DrawIndexedPrimitivesList(GraphicsDevice GraphicsDevice, IndexedPrimitivesList ipl)
    {
        GraphicsDevice.SetVertexBuffer(ipl.vb);
        GraphicsDevice.Indices = ipl.ib;
        foreach (IndexedPrimitives ip in ipl.primitives)
        {
            GraphicsDevice.DrawIndexedPrimitives(ip.Type, ip.baseVertex, ip.minVertexIndex, ip.numVertices, ip.startIndex, ip.primitiveCount);
        }
    }
    public struct SplittedBuffers
    {
        public IndexBuffer[] ibs;
        public VertexBuffer[] vbs;
    }
    public static SplittedBuffers GenerateSplittedBuffers(IndexedPrimitivesList ipl)
    {
        SplittedBuffers sb=new SplittedBuffers();
        List<List<byte>> vbs = new List<List<byte>>();
        List<List<byte>> ibs = new List<List<byte>>();
        List<int> baseVertices = new List<int>();
        byte[] vb = new byte[ipl.vb.VertexCount * ipl.vb.VertexDeclaration.VertexStride];
        ipl.vb.GetData<byte>(vb);
        byte[] ib = new byte[ipl.ib.IndexCount * ((ipl.ib.IndexElementSize == IndexElementSize.SixteenBits) ? 2 : 4)];
        ipl.ib.GetData<byte>(ib);
        foreach (IndexedPrimitives ip in ipl.primitives)
        {
            int i = baseVertices.IndexOf(ip.baseVertex);
            if (i < 0)
            {
                vbs.Add(new List<byte>());
                ibs.Add(new List<byte>());
                baseVertices.Add(ip.baseVertex);
                i = vbs.Count-1;
            }
            byte[] tmp = new byte[ip.numVertices * ipl.vb.VertexDeclaration.VertexStride];
            Array.Copy(vb, ip.baseVertex * ipl.vb.VertexDeclaration.VertexStride, tmp, 0, tmp.Length);
            vbs[i].AddRange(tmp);

            tmp = new byte[ip.primitiveCount*((ip.Type==PrimitiveType.TriangleList)?3:1) * ((ipl.ib.IndexElementSize == IndexElementSize.SixteenBits) ? 2 : 4)];
            Array.Copy(ib, ip.startIndex * ((ipl.ib.IndexElementSize == IndexElementSize.SixteenBits) ? 2 : 4), tmp, 0, tmp.Length);
            ibs[i].AddRange(tmp);

        }
        sb.ibs = new IndexBuffer[ibs.Count];
        sb.vbs = new VertexBuffer[vbs.Count];
        for (int i = 0; i < vbs.Count; i++)
        {
            sb.ibs[i] = new IndexBuffer(ipl.ib.GraphicsDevice, ipl.ib.IndexElementSize, ibs[i].Count / ((ipl.ib.IndexElementSize == IndexElementSize.SixteenBits) ? 2 : 4), ipl.ib.BufferUsage);
            sb.ibs[i].SetData<byte>(ibs[i].ToArray());
            sb.vbs[i] = new VertexBuffer(ipl.vb.GraphicsDevice, ipl.vb.VertexDeclaration, vbs[i].Count / ipl.vb.VertexDeclaration.VertexStride, ipl.vb.BufferUsage);
            sb.vbs[i].SetData<byte>(vbs[i].ToArray());
        }
        return sb;
    }
    public static void DrawSplittedBuffers(GraphicsDevice GraphicsDevice,SplittedBuffers sb)
    {
        for (int i = 0; i < sb.vbs.Length; i++)
        {
            GraphicsDevice.SetVertexBuffer(sb.vbs[i]);
            GraphicsDevice.Indices = sb.ibs[i];
            GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, sb.vbs[i].VertexCount, 0, sb.ibs[i].IndexCount/3);
        }
    }
}

```

---

## Edits:

I thought up to now vertices and indices are limited to 65535, but the primitives are.

There's other strange behavior of the parameter numVertices, it can be set to a bigger Value then the actual number of vertices in the buffer without throwing an exception or aborting.

The code above now works for me. But it is a bit too slow.

---

## Further edits:

I improved my code to prepare all the values only once. During draw call only the values are inserted, now I'd like to redefine my Question as follow: Is switching Buffers faster then the drawing method above?

I suppose it's not, because the same number of draw calls are needed by both methods, as both methods can't draw in one call triangles with different baseVertex or more then 65535 primitives. May switching the buffers will also slow down a little bit and I think using the offsets baseVertext and startIndex should not slow down the drawing method. What are your thoughts and experiences?

---

## Tested

I tested both drawing methods. For the same data both need the same number of draw calls (in my tests 22 per draw). Drawing the SplittedBuffers is up 3 times slower then using the IndexedPrimitivesList. I will now do some changes in the generation to allow overlapping vertex ranges.

# Answer
> 1 votes
In DirectX there is a method:
`ID3D11DeviceContext::DrawIndexed(UINT IndexCount,UINT StartIndexLocation, INT BaseVertexLocation);`

Which allows you to specify where in the buffer to start drawing and how many to draw. If there is anything similar in XNA, wouldn't it be as simple as splitting it into several draw calls, without having to split the buffer?

```
void draw_big_mesh(ID3D11DeviceContext *devcon, ID3D11Buffer *vertexBuffer, int numIndices)
{
    int limit = 65535;
    int numPrimitives = numIndices/3; //assuming your primitives are triangles
    int numSegments = numPrimitives / limit;
    int rest = numPrimitives % limit;

    for (int offset=0; offset < numSegments;offset++)
    {
        devcon->DrawIndexed(limit*3, offset*limit*3, vertexBuffer);
    }

    //draw rest
    if (!rest)
        devcon->DrawIndexed(rest*3, numSegments*3, vertexBuffer);
}

```

---
Tags: c#, xna, 3d, index-buffer
---


# Question
Title: Creating graphics at different angles for sprites
I am developing a Java game that uses sprites for the graphics. It's just a top down shooter and our ship sprites look like the following:

These work fine, but they're hard to create and the artist who created them is no longer working on the game. I could easily create a top down view of a ship in Photoshop myself, but I'm not sure how to get all the angles.

What do you think would be the best program or approach would be for me to create more?

# Answer
It's a bit of a hassle to do it this way (I'm guessing there might be a simpler way to do it), but one suggestion is this.

Use any 3D rendering program that allows you to apply a texture to a surface. Even a tool for modding 3D games/content would work, as long as it allows you to view a model with your custom textures.

Make the simple top-down view, and apply it to an appropriately shaped surface of a 3D object. Adjust the position/angle of the object (or camera), and capture what you see.

Again, kind of a roundabout way to generate the shots, but the upside is they will look realistic (since they will be shots of that texture actually facing that way, instead of an artistic estimation of what that would look like).
> 9 votes

---
Tags: graphics, sprites
---


# Question
Title: Rotate an existing quaternion around an axis?
I have an existing quaternion (Java Quat4f). I would like to rotate this quaternion around an axis (i.e. 90 degrees around the x axis, 25 degrees around the y axis, 10 degrees around the z axis, 180 degrees around the y axis, etc.)

How can I rotate the existing quaternion around an axis?

Thank you!

# Answer
> 1 votes
To combine rotations, I believe you canjust multiply that quaternion with a quaternion for each of the other axis rotations you require.

For example, in this simple (extension) method I wrote, I get the final quaternion by combining 3 quaternions for X, Y and Z rotations.

```
    //Takes in angles in degrees
    //Useful wiki page: http://www.ogre3d.org/tikiwiki/Euler+Angle+Class and http://www.ogre3d.org/tikiwiki/Euler+Angle+Class+Mogre
    public static Quaternion ToOrientation(this Vector3 vec)
    {
        Quaternion xRot = new Quaternion(Math.DegreesToRadians(vec.x), Vector3.UNIT_X);
        Quaternion yRot = new Quaternion(Math.DegreesToRadians(vec.y), Vector3.UNIT_Y);
        Quaternion zRot = new Quaternion(Math.DegreesToRadians(vec.z), Vector3.UNIT_Z);
        return xRot * yRot * zRot;
    }

```

I must admit my knowledge of quaternions is not amazing, so any expansions on this answer would be appreciated.

Good luck! :)

---
Tags: java, rotation, quaternion
---


# Question
Title: Is there a universal method to send key or mouse input to any application from C#?
I need method or group of them to send signals to any application (browsers, games, et cetera) about mouse movement or key input.

I can easly retrieve an IntPtr to any process, but I don't know what library or function I must use next.

I know only about SendMessage/PostMessage functions from user32.dll, but these functions can send messages only to applications with standard message loops and it doesn't work with DirectX applications. And I've noticed that something like this:

```
PostMessage(pFoundWindow, WM_KEYDOWN, (IntPtr)VK_RIGHT, (IntPtr)0);
Thread.Sleep(150);
PostMessage(pFoundWindow, WM_KEYUP, (IntPtr)VK_RIGHT, (IntPtr)0);

```

sends messages slower than DirectInput in and does not allow player to send, for example, left arrow and space, even in threads.

# Answer
> 1 votes
I am not sure what you can do about mouse movement. But for the keyboard, have you tried SendKeys?

I have a friend using SendKeys with speech recognition to do voice commands in StarCraft2. But I am not sure if it works with every game.

# Answer
> 0 votes
**You can create a simple script in like 2 minutes with AutoHotKey\_L or AutoIt...<br>and then call the script in your C# project.**

Both have support for almost any mouse/key movement or simulation you can think of.

---
Tags: c#, input, mouse, keyboard
---


# Question
Title: Rendering 3D out of layers - optimizing fillrate?
I'm rendering a city of several million cuboids that are all axis-aligned, touching each other and same-sized. They only differ in height.

Rendering them as real geometry is vertex-bound and too slow, so I've went with another approach: render them as several flat layers of a single, big texture. The more layers, the better the buildings look. This is similar to how a 3D printer works. Also I've seen it used for rendering hair, grass and snow. In my case, I'm using nearest-neighbor filtering to make the buildings square-shaped, and alpha-testing to control the building heights.

Here's a very zoomed-in screenshot so the individual layers are visible:

This works great, but when I use a higher number of layers, it gets too slow due to the fillrate. The cuboids are opaque so I tried optimizing this by enabling z-testing, but it hardly helped, because my shader is cheap (fixed-function, actually), and it's the only thing z-testing helps to skip. Or maybe it's because on my dev machine I have an Intel GPU and it doesn't do early-z discard.

So now I'm out of tricks. What could be used to optimize this? Also, any common names for the technique?

Notes:
\- I'm aiming for OpenGL 1.4-level hardware, which is pretty restrictive when it comes to optimizing.
\- I'm additionally using multitexturing with alpha-modulation to make arbitrarily-shaped, antialiased buildings (not enabled in the screenshot)
\- Usually the city is viewed from a RTS-style viewpoint, all of it is visible, and it fills the screen, so fog or LOD techniques wouldn't work

# Answer
> 3 votes
There are a handful of possibilities that don't require major changes that *might* help the fill rate. For example: draw your texture layers front-to-back, use low-bandwidth texture formats. Depending on your bottleneck, you might get some advantage from storing an 8-bit single-channel height map, and rendering that several times with different alpha test thresholds.

However, I would expect that you'd need to do some sort of adaptive rendering. Fully zoomed-out, you would have almost unnoticeable occlusion, so it would make sense to render a single layer (a mipmapped height map). As you zoom in, you'd need to switch to real geometry (using an index buffer to reduce vertex processing load).

Depending on your access to pixel shaders, relief mapping might also be a solution—you would render a single pixel only once, which might alleviate the fill rate.

And if you used an orthographic projection with a constant viewing angle when zoomed out too far for geometry, you could render to a texture and only need to process smaller areas of the screen as the player scrolls around.

# Answer
> 0 votes
First optimization - If your buildings are the same color (as on the picture), can't you use just colors instead of textures?

Second optimization - if you are looking from far away, you can render less layers.

Third optimization - render your buildings from up to bottom. Not one building from up to bottom and then other one, but take highest layer from all building and render this one, then second layer etc.

Fourth: If you are rendering big building (with a lot of layers, so many vertices), wouldn't it be better to render just one cube (8 vertices) instead?

*//EDIT: Calsbeek was quicker.*

---
Tags: opengl, rendering, optimization
---


# Question
Title: Making an object swing from one rope to another
I am trying to make a Tarzan like game with Cocos2D and Box2D. I am having issues with the physics - making an object swing from one rope to another. I am not really sure how to do this. Could anyone please help me.

# Answer
Hey I dont know the exact answer to your question but I think you will find more code in the below link that you can look into for your project.

See the snapshots, I think the developer has used the same project that you have listed in the comments of your question.

http://muhammedalee.wordpress.com/2011/08/21/cut-the-rope-like-rope-shooter/
> 1 votes

---
Tags: physics, box2d, cocos2d-iphone, rope-physics
---


# Question
Title: Is there a way to calculate a good population per distance for enemies in a side-scroller game?
I would like to know if there is a formula to calculate how much distance should I leave between enemies, or how many to put on the screen at the same time in a side-scroller game.

I feel like if I leave too few the game is going to get boring, but if I leave too many at some spot the game is going to get way too hard.

# Answer
> 2 votes
No. There is no such generic formula.

My experience in the professional game industry has been that tuning game elements (such as the density and placement of enemies) usually constitutes about 80 to 90 percent of the total work required to create a fun game. Most people would probably agree that it is also the most difficult part of the process to get right, and the most important to the final feel and success of the game.

Honestly, this is something that you shouldn't even want to delegate to the computer to do for you; too much rides on the decisions that are made in this area to ever trust them to a generic algorithm.

---
Tags: game-design, side-scroller
---


title: Locomotion-system with irregular IK

text:
# Question
Title: Locomotion-system with irregular IK
Im having some trouble with locomtions (Unity3D asset) IK feet placement. I wouldn't call it "very bad", but it definitely isn't as smooth as the Locomotion System Examples.

The strangest behavior (that is probably linked to the problem) are the rendered foot markers that "guess" where the characters next step will be. In the demo, they are smooth and stable. However, in my project, they keep flickering, as if Locomotion changed its "guess" every frame, and sometimes, the automatic defined step is too close to the previous step, or sometimes, too distant, creating a very irregular pattern.

The configuration is (apparently)Identical to the human example in the demo, so I guessing the problem is my model and/or animation. Problem is, I can't figure out was it is =S

Has anyone experienced the same problem? I uploaded a video of the bug to help interpreting the issue (excuse the HORRIBLE quality, I was in a hurry).

# Answer
Check the "Use Fixed Update" checkbox in *CharacterMotor*, as shown in this image.
> 1 votes

---
Tags: unity, assets
---


title: XNA Multiplayer Gone Wrong

text:
# Question
Title: XNA Multiplayer Gone Wrong
I'm trying to add multiplayer to my XNA platform game, and have just failed miserably.

The idea behind my method is that the client knows what tick the server is at, and knows how long it takes to get to the server and back. It sends it's input and position to the server with how long ago the input was put in, and then the server adds it to the list.

Each server tick, the server goes through it's list of updates and sends each player the most relevant input. Then when the client receives the update, it uses the information of how long it took for the player to send it to the server, plus how long it takes to get from the server. It uses this Tick amount to run the information through the player's update, and get a position.

Then it should look at where he is and where the server says he is, and average it out.

It sounds right in my head, but my execution went terribly wrong, and I don't like code dumping but this is a last resort: the important code is near the bottom in UpdateNetwork(), but I added some other parts that you can reference to if you need to

```
    /// <summary>
    /// Allows the game to run logic such as updating the world,
    /// checking for collisions, gathering input, and playing audio.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    public override void Update(GameTime gameTime)
    {

        keybState = Keyboard.GetState();
        //Keys are stored in enums which get translated
        //to a string I can pass over
        playerlist[multi.id].GetKeys(keybState);

         //Universal commands (respawn, quit, etc)
        globalKeyboard();

        //Each player, run through them updated
            for (int i = 0; i < playerlist.Count; i++)
            {
                Update_Player(i, 0);

                Update_Flags(i);

                Update_General(i);
            }

           //update network processing center
            UpdateNetwork();

            oldkeybState = keybState;

            //timer class, update based on
            //gameTime's milliseconds
            Trialtime.Count(gameTime);

            Update_Camera();

            Tick++;

            //ping
            Connection.clientSend("PING@" + Tick);

            //predicted servertime
            if (serveroffset < 0)
            {
                offset.Add(offset.getAvgTick() - serveroffset);
            }
            else if (serveroffset > 4)
            {
                offset.Add(serveroffset - 1);
            }
            else
            {
                offset.Add(serveroffset);
            }

            //random variables to display to scree
            int predict = ServerTick + latency.getAvgTick() + offset.getAvgTick();
            packin.Add(latency.getAvgTick() / 2 + offset.getAvgTick());
            packout = packin.getAvgTick() - offset.getAvgTick() * 2;

            //Sends position to the server, plus predict
            SendPosition(playerlist[multi.id].position, predict);

            //sends the predicted server time, which the server then calculates
            // if the guess is too high or too low
            Connection.clientSend("PREDICT@" + predict.ToString());

        base.Update(gameTime);
    }

    /// <summary>
    /// First thing that happens is the player updates his client position
    /// </summary>
    /// <param name="id"></param>
    /// <param name="tickloop"></param>
    void Update_Player(int id, int tickloop)
    {
        //If the sprintTimer is initialized,
        //update the timer
        if (sprintTimer > 0)
        {
            SprintTime(id);
        }

        //Checks player state and reacts
        //accordingly
        for (int i = 0; i <= tickloop; i++)
        {

            if (playerlist[id].state == DEAD)
            {
                deathTimer(id);
            }
            else if (playerlist[id].state == GROUND)
            {
                Control_Keyboard_Ground(id);
                Control_Update_Ground(id);
            }
            else if (playerlist[id].state == AIR)
            {
                Control_Keyboard_Air(id);
                Control_Update_Air(id);
            }
            else if (playerlist[id].state == WALL)
            {
                Control_Keyboard_Wall(id);
                Control_Update_Wall(id);
            }
        }
    }

    /// <summary>
    /// Here's an example of how the informationn is processed
    ///
    /// </summary>
    private void Control_Keyboard_Air(int id)
    {
        GamePadState currentState = GamePad.GetState(PlayerIndex.One);
        Vector2 ts = currentState.ThumbSticks.Left;

        //First Check if right is held down
        if (playerlist[id].KeysDown[(int)KeyType.Right] == 1)
        {
            List<blockClass> Details = Collision(new Rectangle((int)playerlist[id].position.X + 28, (int)playerlist[id].position.Y,
                20, 20), id);
            if (Details.Count == 0)
            {
                if (playerlist[id].velocity < 6)
                    playerlist[id].velocity += .25f;

                playerlist[id].orientation = SpriteEffects.None;
            }
        }

        if (playerlist[id].KeysDown[(int)KeyType.Left] == 1)
        {
            List<blockClass> Details = Collision(new Rectangle((int)playerlist[id].position.X + -18, (int)playerlist[id].position.Y,
                20, 20), id);
            if (Details.Count == 0)
            {

                if (playerlist[id].velocity > -6)
                    playerlist[id].velocity -= .25f;
                playerlist[id].orientation = SpriteEffects.FlipHorizontally;
            }
        }

    }

    ///<summary>
    ///Process for analyzing collisions mid air
    ///--Ground for gravity
    ///--Wall
    /// </summary>
    void Control_Update_Air(int id)
    {
        //update animation
        if (playerlist[id].prevstate != AIR)
        {
            playerlist[id].prevstate = AIR;
            playerlist[id].animJump();
        }
        if (playerlist[id].gravity < 0)
        {
            //p_type is a variable that initiates a boost
            if (p_type == 1 && playerlist[id].gravity < -3)
            {
                createBoost(playerlist[id].position, Color.DarkRed);
            }

            //Check collision above, if you hit a ceiling then stop
            List<blockClass> Details = Collision(new Rectangle((int)playerlist[id].position.X + 8, (int)playerlist[id].position.Y - 10,
                    24, 20), id);
            if (Details.Count > 0)
            {
                playerlist[id].gravity = 0;
                p_type = 0;
            }
        }

        //Update players vertical position
        playerlist[id].position += up * playerlist[id].gravity;

        //update gravity
        playerlist[id].gravity += 0.3f;

        //If player is moving right
        if (playerlist[id].velocity > 0)
        {
            //Check collision to the right
            List<blockClass> Details = Collision(new Rectangle((int)playerlist[id].position.X + 28, (int)playerlist[id].position.Y,
                20, 20), id);

            //If there is a collision
            if (Details.Count > 0)
            {
                //and one of the blocks is type WALL
                if (Details[0].type == 2)
                {

                    //Set the things to initiate wall controls
                    playerlist[id].position.X = Details[0].position.X - 30;
                    playerlist[id].gravity = 0;
                    playerlist[id].speed = playerlist[id].velocity;
                    playerlist[id].velocity = 0;
                    playerlist[id].state = WALL;
                    playerlist[id].orientation = SpriteEffects.None;
                    p_type = 0;

                }
            }
            else
            {
                //if there is no collision, move right
                playerlist[id].position += right * playerlist[id].velocity;
            }
        } //if player is moving left
        else if (playerlist[id].velocity < 0)
        {
            List<blockClass> Details = Collision(new Rectangle((int)playerlist[id].position.X + -18, (int)playerlist[id].position.Y,
                20, 20), id);
            if (Details.Count > 0)
            {
                if (Details[0].type == 2)
                {
                    playerlist[id].position.X = Details[0].position.X + 28;
                    playerlist[id].speed = -playerlist[id].velocity;
                    playerlist[id].gravity = 0;
                    playerlist[id].velocity = 0;
                    playerlist[id].state = WALL;
                    playerlist[id].orientation = SpriteEffects.FlipHorizontally;
                    outputDebug = "WALL LEFT";
                    p_type = 0;
                }
                else
                {
                    outputDebug = "wall type fail";
                }
            }
            else
            {
                //position
                playerlist[id].position += right * playerlist[id].velocity;
            }
        }

        //Now check for ground
        List<blockClass> cb = Collision(new Rectangle((int)playerlist[id].position.X, (int)playerlist[id].position.Y + 30,
            32, 20), id);

        if (cb.Count > 0)
        {
            if (cb[0].type == 1 || cb[0].type == 3)
            {
                p_type = 0;
                float displace = 27 - (cb[0].position.Y - playerlist[id].position.Y);
                playerlist[id].position.Y -= displace;
                playerlist[id].state = GROUND;
            }
        }

    }

    /// <summary>
    /// Now onto the ugly part that's messing everything up.
    ///
    /// </summary>
    public void UpdateNetwork()
    {
        //Run the networking input
        Connection.GetMessage();

        //incoming is a list<String> of all the messages
        //in the network buffer
        if (Connection.incoming.Count == 0)
        {
            //does nothing
            //correctPosition();
        }
        else
        {
            //For each message
            for (int i = 0; i < Connection.incoming.Count; i++)
            {
                //I'm using strings in this form:
                //COMMAND@INFORMATION
                String[] convert = Connection.incoming[i].Split('@');

                //if the command is "UP" which is UDPATE
                if (convert[0] == "UP")
                {
                    update = true;

                    //0 is UP
                    //1 is the server's TICK
                    //2 is all the players information

                    //this checks and sets what string
                    //is the latest one
                    if (seconds < Int32.Parse(convert[1]))
                    {
                        seconds = Int32.Parse(convert[1]);
                        packet = i;
                        update_str = convert;
                    }
                }
                else if (convert[0] == "TICK")
                {
                    if (seconds < Int32.Parse(convert[1]))
                    {
                        seconds = Int32.Parse(convert[1]);
                        tick = true;
                    }
                } //gets the latency round about
                else if (convert[0] == "PING")
                {
                    latency.Add(Tick - Int32.Parse(convert[1]));
                    serveroffset = Int32.Parse(convert[2]);
                }
                Connection.incoming.Remove(Connection.incoming[i]);
            }

            if (tick)
            {
                snapshots.Add(seconds - ServerTick);
                ServerTick = seconds;
                tick = false;
            }

            //Here's the part that's NEW:
            //vvvvvvvvvvvvvvvvvvvvvvvvv
            if (update)
            {
                if (update_str != null)
                {
                    String[] data = update_str[2].Split('$');

                    //0 = id
                    //1 = predicted tick
                    //2 = avg latency tick
                    //3 = position X
                    //4 = position Y
                    //5 = keystrokes
                    int id = Int32.Parse(data[0]);
                    float x = float.Parse(data[1]);
                    float y = float.Parse(data[2]);
                    String strokes = data[3];

                    //last position
                    playerlist[id].clientPosition = playerlist[id].position;

                    //set the players keys to what the server says
                    playerlist[id].SetKeys(strokes);
                    //reset the position to where it was at the server
                    playerlist[id].position = new Vector2(x, y);

                    //run the player through the Update through the amount of ticks
                    //it took to get through server and to player
                    Update_Player(id, latency.getAvgTick());

                    //If the distance is too big, try to average it out
                    if (Vector2.Distance(playerlist[id].position, playerlist[id].clientPosition) > 2) {

                        playerlist[id].position = new Vector2(playerlist[id].position.X + (playerlist[id].position.X - playerlist[id].clientPosition.X) / 2,
                            playerlist[id].position.Y + (playerlist[id].position.Y - playerlist[id].clientPosition.Y) / 2);
                    }
                }
                update = false;
            }
        }

    }

```

The result is the player flickering back and forth like a madman

# Answer
> 2 votes
Packet delivery times won't be consistent, you can't count on them. Thus any approach that uses them in the calculation is going to produce bad answers.

# Answer
> 0 votes
It's hard to tell from looking at this code but I had a similar problem in my networked game, where the player was jumping back and forth very quickly between two points. In my case this was caused by differences in the actual transfer time of packets from the server to the client. Even if you know the average server-client latency, you don't necessarily know the actual latency of an individual packet. So I wonder if something is getting out of sync here. You might want to create a class on the client that receives and stores the update packets, and then hands them out to your game loop on a smoothed-out basis.

# Answer
> 0 votes
I'm working in an app with XNA 4 too. I'm just thinking: Can we use a database to control things like that? Some flags to verify which turn is? I don't know if XNA work with databases..

---
Tags: xna, networking, multiplayer
---


title: Capturing a programs performance

text:
# Question
Title: Capturing a programs performance
I'm trying to capture the performance of the GPU, CPU, FPS and memory usage on a program I'm currently working with and want to avoid having to write my own performance capture stuff. Does anyone know of a good program/programs that can do 1 or more of the above?

Ideally something that is simple to use. I've googled a few, but getting them to work has been a right pain. The couple that I've tried out have given me my entire systems performance, as opposed to just my running program.

Any help would be appreciated. I'm currently using DirectX 9 and C++ for my program.

# Answer
> 4 votes
If you have an NVidia card, maybe take a look at PerfHUD. It's a bit complicated at first, but you can start by ignoring the advanced stuff if you want. It requires instrumenting your application (during device creation), but when I did it for our legacy 3D application at my previous job, it was just copy/pasting the example given by NVidia without any problem. And it gave me really valuable informations.

It's only for the GPU, for the CPU I used AMD CodeAnalyst (haven't tried the Intel equivalent, VTune, which isn't free). Quite simple to use and did a good job helping me to find bottlenecks.

---
Tags: directx, performance
---


title: Why do people use quaternions?

text:
# Question
Title: Why do people use quaternions?
I have been using them as a black box for a while, I'm just learning about of the maths but I'd just like some definitive answers to this question.

So far the only benefit I've come across personally is the ability to SLERP between two angles - to achieve the same effect with a vector you need quite an ugly work around (intrinsically linking 0 and 2PI together).

# Answer
Quaternions solve a few problems elegantly:

* They are as compact as axis-angle representations (4 scalar values)
* They are easily converted to and from matrix representations
* Interpolation works from any start to end angle without special casing
* They never exhibit gimbal lock

You can get around these issues with other representations, but quaternions are a good fit for their algorithmic simplicity and performance.
> 22 votes

# Answer
The SLERP usage you mention is a specific case of a more general attribute of quaternions: you can smoothly interpolate between different rotation values.

When interpolating the rotation values of euler angles you get weird looking movements, and there just isn't logically any way to interpolate the values of axis-angle rotations (well, aside from two different angles around the same axis).
> 3 votes

---
Tags: mathematics, quaternion
---


# Question
Title: How can I write a terrain into a .raw file?
I want to generate a terrain through Perlin noise and store it into a .raw file.

From Nehe's HeightMap tutorial I know the .raw file is read like this:

```
#define MAP_SIZE        1024

void LoadRawFile(LPSTR strName, int nSize, BYTE *pHeightMap)
{
    FILE *pFile = NULL;

    // Let's open the file in Read/Binary mode.
    pFile = fopen( strName, "rb" );

    // Check to see if we found the file and could open it
    if ( pFile == NULL )
    {
        // Display our error message and stop the function
        MessageBox(NULL, "Can't find the height map!", "Error", MB_OK);
        return;
    }

    // Here we load the .raw file into our pHeightMap data array.
    // We are only reading in '1', and the size is the (width * height)
    fread( pHeightMap, 1, nSize, pFile );

    // After we read the data, it's a good idea to check if everything read fine.
    int result = ferror( pFile );

    // Check if we received an error.
    if (result)
    {
        MessageBox(NULL, "Can't get data!", "Error", MB_OK);
    }

    // Close the file.
    fclose(pFile);

```

}

`pHeightMap` is one-dimensional, so I don't understand how I would write the x,y correspondence to a height value. I was planning to use either libnoise or the noise2 function on Ken Perlin's page, to make each value in a 1024x1024 matrix correspond to the height for the point, but the .raw file is stored in a single dimension, how can I make x,y correspondence work there?

# Answer
Depending on your map width, you can convert between (x,y) and pHeightMap\[index\] fairly simply:

```
int x, y, index; // assuming y is vertical, x is horizontal

// converting from x,y to index
index = y * MAP_WIDTH + x;
BYTE valueAtXY = pHeightMap[index];

// converting from index to x,y
for(index = 0; index < nSize; index++) {
    x = index % MAP_WIDTH;
    y = index / MAP_WIDTH;
    printf("We are at point %d, %d", x, y);
}

```

---

Alternatively, you can cast from a `BYTE*` to a `BYTE(*)[<width>]` . C is row-major, so the row-index will come first.
```
BYTE * pHeightMap;
BYTE (* pHeightMap2D ) [MAP_WIDTH] = (BYTE(*)[MAP_WIDTH]) pHeightMap;

for(index = 0; index < nSize; index++) {
    x = index % MAP_WIDTH;
    y = index / MAP_WIDTH;
    // y comes first, because the row-index comes first.
    assert(pHeightMap2D[y][x] == pHeightMap[index]);
}

```
> 2 votes

---
Tags: terrain
---


# Question
Title: Is there evidence that downloading assets on first use rather than bundled with a game download makes a mobile game more popular?
I've noticed quite a few mobile games on the Android platform recently that prompt you to download their assets package when you first run the game. As an example, The Sims 3 is available for iOS and Android devices (Android Marketplace, Apple App Store) but the iOS version seems to be much larger in size and as such probably doesn't use this system.

I can think of several advantages and disadvantages to doing this:

Advantages (to developer):

* The game's store page reports the size of the app as much smaller than it is.
* When a patch or update is released you don't need to download the entire application again. (Does the App Store release patches, or do you need to download the whole app again)?

Disadvantages (to developer):

* You need to provide your own bandwidth and ensure download availability.
* You need to poll your server for updates in the assets and ensure that you make assets available for old versions of the game.

Advantages (to a consumer):

* You don't need to ensure you have space for app+assets before installing. Downloading the package manually means you can install the libs/logic/executable on your device and the assets on eternal storage such as SD card, rather than installing all to the device and moving afterwards.
* It could be possible to download lower resolution versions of the assets depending on install device (somewhat unnecessary for Android as the market provides a way of supplying different packages to different devices)

Disadvantages (to a consumer):

* More difficult for app to enforce that download is done over wifi rather than using up their contract bandwidth.

While I understand that direct comparisons of the two methods are difficult, I'm looking for statistics/reports preferably of the same app with control and sample groups. If that's not available, **can anybody with experience with this method indicate whether users preferred not bundling assets? Does user opinion on this vary based on platform? Does the value to users outweigh the extra effort for the developer?**

# Answer
I have no such data, but you haven't mentioned another downside: For me at least, having to download assets separately is very annoying.

Also, while the marketplace can download large apps in the background, in my experience it is not always clear whether (or even the case that) I can do other things with my phone while the game is fetching assets, as this function is usually not coded very well.

Of course, I don't mean to imply that I think you will not implement an excellent asset download system- however, if so many people are not doing it, perhaps it's just hard to do right?
> 4 votes

---
Tags: marketing, user-experience, asset-management
---


# Question
Title: How to move a 3d object in 3d coordinate space
How can I move a 3d object in a 3d coordinate space? I have a coordinate output from a text file like this:

```
-0.420 , -0.329 , 2.953
-0.296 , -0.314 , 3.136
-0.296 , -0.314 , 3.136
-0.296 , -0.314 , 3.136

```

# Answer
Set the world matrix to Matrix.CreateTranslation(x,y,z) multiplied by the local transformations of your model. Note I haven't done 3D since 3.1 but I don't believe this bit of the framework has changed.

```
    Matrix[] transforms = new Matrix[myModel.Bones.Count];
    myModel.CopyAbsoluteBoneTransformsTo(transforms);

    foreach (ModelMesh mesh in myModel.Meshes)
    {
        foreach (BasicEffect effect in mesh.Effects)
        {
            effect.World = transforms[mesh.ParentBone.Index] *
                * Matrix.CreateTranslation(x,y,z);
            effect.View = cameraMatrix;
            effect.Projection = Matrix.CreatePerspectiveFieldOfView(
                MathHelper.ToRadians(45.0f), aspectRatio,
                1.0f, 10000.0f);
        }
        mesh.Draw();
    }

```
> 4 votes

# Answer
Suppose (a basic example) you are drawing the object `model` like so: `DrawModel(model, world, view, projection);`. Here, `view` and `projection` are naturally the view and projection matrices related to the camera, and are not relevant for us. `world` is the matrix used for locating the object in the game world. It can be obtained with `Matrix.CreateWorld(position, forward, up);` where the parameters are fairly obvious and well-documented. If you already have a world matrix for this object, you can change its position with `world * Matrix.CreateMatrix(newPosition)`. This is for telling an object to "instantly teleport" to a new location.

Your image implies that you are interested in creating an animation, where an object appears to the user to move on the screen, in the 3D space of the game world. AFAIK, the way to do this is to "teleport" it to a slightly different position at regular time intervals.

```
// Fields
Model model;

Vector3 position = new Vector3(0, 0, 0);
Vector3 velocity = new Vector3(0, 0, 1000);
Vector3 acceleration = new Vector3(0, 0, -1);

LoadContent()
{
    model = content.Load<Model>(@"Models\ball");
}

Update(GameTime gameTime)
{
    velocity += acceleration;
    position += velocity;
}

Draw(GameTime gameTime)
{
    Matrix world = Matrix.CreateWorld(position, Vector3.Forward, Vector3.Up);
    DrawModel(model, world, view, projection);
}

```

This should create a ball thrown upwards (in the +z direction), which gradually slows down and starts falling again. Note that the above code won't compile as is:

1. You must define a view and projection matrix somewhere, and make sure they are suitable for displaying the object (the camera won't see anything if it's looking away from the origin, because the ball's x and y coordinates are always 0, for instance).
2. I'm not sure what modifiers (`private`, `static` and so on) the `LoadContent`, `Draw` and `Update` have by default and what they return (IIRC `void`).

Also, keep in mind that:

* You may need to tweak my numbers for velocity and acceleration so that the ball doesn't move too slow or too fast (you may want to use gameTime for a more "correct" correspondence to real time). I think with 1000 and -1, it will take about 10 seconds to reach its apex.
* Your model is not necessarily "ball.fbx" under the "Models" directory.

However, if you just create a new XNA project in Visual Studio 2010, it should be obvious to you what code line to add where. There may be some SpriteBatch lines under Draw by default, I think you can safely remove them because they are for drawing 2D (which you aren't doing) but if you leave them, they will just make your models be drawn slightly weird, so don't worry too much about it.

Also, I have shown a very basic method here. With your list of coordinates, there are two things that can be done:

1. You can simply put each of your four triplets in a list of `Vector3`s, then have the Draw method get the next element (and come back to the first after the last one?) at every call, and create a world matrix based on that element. However, Draw gets called on the order of something like 100 times per second, so if you do this you will simply see the object flicker at each point at the same time. You can add a timer so that Draw moves to the next coordinate only once in a while, and then the object will seem to wait at a point, then "jump" to the next one.
2. You can create the list as above, but also interpolate the line connecting each two subsequent points with a large number of intermediate points (add a coordinate for halfway there, quarter of the way there, tenth of the way there and so on). You want to space these at a constant distance, and you want a lot of them. The more you have, the slower the object will appear to move. (The "jumping" will also be less obvious with many intermediate points close to each other)
3. The "sane" way- represent each position as a `Vector3`. Then, when moving from point `u` to point `v`, find velocity by doing `distance = (v-u)/RATE;` where `RATE` is a largish number (you can play with it for various effects but to start just make it a constant equal to 100-1000). Then, add velocity to position in Update as above, but don't forget to check whether you've reached v, and recalculate the velocity for your next point (as velocity carries direction information as well as speed).
> 1 votes

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


# Question
Title: Is there a limit to Gametime.TotalMilliseconds?
Gametime should always be increasing, and totalmilliseconds is going to be the largest value. So if the game is hypothetically run for 1 day, this value should 86 400 000.

This probably isn't a problem for most games, but I'm curious if there's some sort of fail safe mechanism if it does get too large, or if a limit even exists.

# Answer
I’m afraid the answers here don’t understand that the limit is the `Double`’s mantissa. The maximum **fully accurate** value for `GameTime.TotalMilliseconds` is actually about **10,000 days**.

`TimeSpan`’s internal representation is the `Tick`, which is defined as 1/10,000 milliseconds. `TotalMilliseconds` is a `Double`, which can only represent `2^53` different mantissa values. After 2^53 ticks, there is loss of information.

So the largest `TimeSpan` that can be represented as a `Double` with no loss of precision is:

```
2^53 ticks / 10000 ticksperms ≅ 900719925474 ms ≅ 10425 days

```
> 7 votes

# Answer
This is more of a silly bit of trivia, but if you don't care about perfect precision (who cares if you give or take a second when talking about centuries?) then as `TotalTime` is a double, the maximum value it can store is `1.7976931348623157E+308`.

I am not sure how overflows work in C#, but if you run the game for longer than this, I guess it would either go back to something like `-1.798*10^308`, or simply not change. It also depends on how it is implemented internally.

That said, that number of milliseconds is pretty big. If you compare it to the hypothetical age of the universe, it's... Uh... Well it's still pretty big.

Of course, as Sam said, the time is actually stored in ticks (tenths of a nanosecond?), so you would run into the "limit" after a "much shorter" time period. It's still something like a cube of a googol times the age of the universe.

I'm not sure how `GameTime` stores time, exactly, so this also means that you may never actually see `TotalMilliseconds` output get "close" to its maximum value. Although, if it's packaging time into days and years whenever the ticks value gets high enough, and not just when you call the getter, then the timer will increase until the maximum value of `double` *in years*, which is even higher.

If, for some reason, your game should have such plentiful content as to require spans of time in which a great many universes are born and perish to fully explore, there exist specialized data types for storing arbitrarily large numbers. Java has a `BigDecimal` whose size is basically limited by your RAM (and through virtual memory, even hard disk space). Apparently, C# doesn't have `BigDecimal`, but it has `BigInteger`.

Should you make such an epic-scaled game, doubtless to be played by the very gods themselves, you would probably start by duplicating the `BigDecimal` class, and then reimplementing the `GameTime` class (or even just periodically adding `GameTime`'s value to your `BigDecimal`) to use it.
> -1 votes

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


# Question
Title: How (if possible) would I change the BasicEffect Matrix mid draw
Say, for example, I have a list of enemies. Each enemy is a textured quad which is the stored in a singular shared VertexBuffer and IndexBuffer with the buffer usage set to BufferUsage.WriteOnly (static buffers essentially). Then only one call to DrawIndexedPrimitives would be needed to draw all enemies. The problem is enemies have to move around at some point. It is quite easy to change the BasicEffect Matrixes to get the desired result of enemy movement.

My question is how can I change the BasicEffect Matrixes after each Quad using only one static VertexBuffer and IndexBuffer?

Changing the Matrixes for movement is normal, right?

I thought about using a DynamicVertexBuffer instead, is this more effcient for my case?

What about 4.0 streaming? Would a call to GraphicsDevice.SetVertexBuffers(array); (where array is whatever you send it that frame) be a better idea?

I know this question may seem silly for quads considering SpriteBatch is pretty good at doing this already for sprites. But, I am going to add in my own dazzling effects and want to draw textured quads this way. Plus, I'm also OCD and want this to be organized and efficient.

Any help on the matter is appreciated.

# Answer
You should draw each unit in different draw calls. VertexBuffer is meant only for static geometry which doesn't move. You shouldn't use DynamicVertexBuffer either since you are not actually changing any vertices or indices. So, draw every unit ( = quad ) in seperate draw call. You could do some instancing to draw more efficiently, you can find plenty of information about that by googling.

EDIT: I have to note that if your units move rarely, it may be more efficient to build VertexBuffer every time they move. For example if you were making chess game where there may be minutes between turns. However, I wouldn't use VertexBuffer in that case either since I doubt I'd run into any performance problems because of that, and for me faster development is more important than minor performance boost.
> 2 votes

# Answer
You should use for each object a different world matrix. You simply set the world used for an object to the BasicEffect before it gets drawn. If you want to change the position of an object you set a new vector to the associated matrix's translation.

Do not change the VertexBuffer. Mention that any Vertex will pass a calculation step anyway where world, view and projection are involved. Changing the world will only upload one matrix to the GPU, every thing else will use the same amount of time. To create and fill a new VertexBuffer will need to upload all the new vertices.

As you want to use only one Vertex- and IndexBuffer you need to store the range of indices used by each object somewhere and pass them to the drawing method as startIndex and primitivesCount (used indices/3 for TriangleList), after you set the associated world matrix to the BasicEffect.
> 0 votes

---
Tags: xna, c#, xna-4.0, hlsl
---