# Question
Title: How should we be storing procedurally generated behavioural code?
Me and a group of friends are developing a game and we've run into a road block. Before we describe that road block, here's a simplified explanation of our game:

The game will be able to take in a song in `.wav` format, and from that song procedurally generate a "level" whose elements and features vary depending on the properties of the song.

Seems simple enough on the surface (aside from the *massively* understated complexity of the procedural generation algorithms), but there's a problem. We want to be able to store the procedurally generated content in some portable format, but we also want to be able to execute it very quickly.

Here's the deal. The procedurally generated objects all have procedurally generated behaviours. They each have an `update` "method" that encapsulates this behaviour. The behaviour may be something like "if position is some position, do something" or "do this 10 times in a for loop", or something else (most likely only very simple code).

So I was thinking of using the bytecode pattern, and writing a very basic language in which we could encode the behaviour of each object. There's a problem with this though; there's a good chance it won't be fast enough.

On screen at once there will be **thousands** of these objects with procedurally generated behaviours. If the behaviours were coded in the native language (C# by the way), it would most likely be fast enough, but since we would be parsing and executing our own language bytecode *in* C# there would be a lot of added overhead that we think is enough to make our game unplayable.

Of course, we haven't tried implementing our own language to see if it actually *would* be fast enough, but we're kind of on a tight time constraint and don't want to take the risk of wasting time implementing something that won't work.

What should we do?

# Answer
Get the simplest possible example that approaches your expected complexity, running. Code up say 5-6 considerably different behaviours, make entity count variable, and then *test* at different counts, optimise, and scale up from there. *You cannot do game development without prototyping,* it is the nature of this profession. You can reduce the complexity of your prototypes sometimes through forethought (which due to hidden complexities can only take you so far), but most typically during coding -- the front line is where you have your tactical epiphanies. ;)

One of the most exciting, definitive features of game dev against a background of traditional business programming, is the degree of flexibility we have in adapting engineering requirements to user experience; i.e. in cases of game logic it is not so often a black-and-white matter of "is this possible?" so much as "how do we reduce this enough to make it run acceptably in real time?".

**Thousands** is not unusual. If this were to become a problem, you could reduce the bounds within which these things operate, what I refer to as the "area of interest" around the player(s). You could also tie into a native code section e.g. by hooking up with a DLL written in C, *once you are certain* that your C# code has reached it's performance limits.

Consider factoring out your specialised behaviours as much as possible to make optimal use of the instruction cache... I'm sure this will be an ongoing process. Long functions that repeat code used in other behaviours means the instruction cache won't be optimally used. It can sometimes be to one's advantage to repeat code, but you probably needn't worry about this.

C# can actually get compiled to some pretty damned efficient code if you're careful with it, using things like tightly packed, cache-coherent struct-of-arrays etc., i.e. minimising the variety of data you are operating on at any one time, so data fits cache line widths. P.S. Unity or .Net / Mono?

FWIW, remember that your performance critical sections only make up a tiny proportion of your code; having said that, AI is almost certainly one of these in your case.

I am by no means convinced that you have no shot at making this work. Once you start optimising, you will often be astounded by the leaps and gains you make in increasing speed, and much of this early optimisation is data-driven, ensuring good cache performance. Optimisation on naive code is trivial; it's a rising curve, only getting much harder once you have already heavily optimised a given code section. That's the point at which an algorithmic paradigm shift is needed if still not fast enough.

At the end of the day though, you have to begin the project to begin to know if it's possible.
> 3 votes

---
Tags: c#, procedural-generation, storage
---


# Question
Title: What is the recommended way to store game entity data?
The following is specific to my problem, but I believe the principles can be applied to any game.

I am currently working on a 3D game which will have many different types of spaceships. The physics and behavior of the spaceships are controlled by a base 'Ship' class. This base class in turn derives from a 'Drawable Object' class which handles the transformations and drawing of the ship.

I want the spaceships to have a set of stats such as

* Max speed
* Cargo capacity
* Weapon power
* etc

that can be passed into the physics and behavior functions.

However, during gameplay new spaceships will be able to be bought/upgraded, but i want to be able to pre-define a (possibly large) list of setups that will be available to the player.

**What is the best way to store the available stat setups?**

Should I be using a large JSON/XML file or similar to store the stats which is loaded at runtime? Or might I just as well hard-code the stats into the constructors of a set of derived classes?

The actual physics attributes (location, velocity etc) and its stats of a particular spaceship are being saved to file when the game is actually played.

I have researched about entity-component-system architecture, but I haven't found much about how to define these entity stats.

Any advice on improving my entity architecture would be much appreciated - this is one of my first attempts at hobby game development.

# Answer
> 0 votes
Having the ship stats in an external file would likely be a lot easier to maintain.

* You can modify values without having to recompile your game binary
* When you are working in a team with non-programmers, these can be taught how to edit these files on their own and contribute to the game balancing. It might even enable them to add and remove ships without help of a programmer.
* When you pick the right format, editing the values will likely be a lot more convenient because of less language syntax around the actual values (this problem can be better or worse depending on what programming language you use. For example, when you use Javascript, a JSON config file and a file which initializes an object with fixed values is exactly the same thing)

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


title: How to build an AIManager class

text:
# Question
Title: How to build an AIManager class
I'm trying to figure out how to write a good AIManager class in Java in order to manage the AI of all the objects in my game.

From another post of mine, an user has suggested to do the following:

*Your calculations should go into the update method. it's fine to have an AIManager class, that has an update() method itself which gets called in the main update loop. this AIManager could hold a list of all the Objects that need to be updated. Since you're using java, you could use an interface to declare something to have an AI, and use this interface to iterate over your objects (which could then be completely different Classes) and have interactions managed by this AI manager.*

It is not so clear to me.

If my Player class implements SeekArriveMovement (for instance), then it should implement the methods of this interface. And AIManager have to implement an update method. But... i don't know. I mean.. how the AIManager should be built and how it should interact with the objects?

Something like this.. ?

```
public class AIManager {

private List<Object> objects;

public AIManager() {
    objects = new ArrayList<Object>();
}

public void addObject(Object o) {
    objects.add(o);
}

public void removeObject(Object o) {
    objects.remove(o);
}

public void update() {
    for(Object o : objects) {
        if(objects instanceof SeekArriveMovement) { // ?
            RedEnemy re = (RedEnemy)o;
            move(re);
        }
    }
}

private void move(RedEnemy re) {
    // ?
}

```

# Answer
I guess what the user on your other question suggested was something like the following.

Your interface provides the method move

```
public interface SeekArriveMovement {
    void move();
}

```

which is implemented by your `Player` class

```
public class Player implements SeekArriveMovement {
    @Override
    public void move() {
        // do something
    }
}

```

In your `AIManger` you iterate over all objects in need of an update, identify all classes using the `SeekArriveMovement` interface and call their `move` method.

```
public class AIManager {
    private List<Object> objects = new ArrayList<Object>();

    public void update() {
        for (Object object : objects) {
            if (object instanceof SeekArriveMovement)
                ((SeekArriveMovement) object).move();
        }
    }
}

```

The problem with your `update` method is that you call `instanceof SeekArriveMovement` on `objects` which is your list of objects. Further you're trying to cast the current object of the list (o) to `ReadEnemy` without knowing if it is an instance of this class which could lead to an exception.
> 1 votes

# Answer
I thought this was a good solution for a similar problem, from a question (and answer) by me here on SO.

Abilities here are essentially AI if they are tickable. I have a runnable that just runs through all Actors and their abilities and tries to tick() them.

interface for manipulating abilities:

```
public interface ActorAbility {

    // doesn't work, but need something to enable
    // instance retrieval for addAbility...
    public ActorAbility getInstance();

    public void act(Actor actor);

    public boolean isTickable();

    // maybe add
    // public boolean isAI();

}

```

sanitized implementation of interface:

```
public enum ActorMove implements ActorAbility {
    INSTANCE;

    private ActorMove() {
    }

    public ActorAbility getInstance() {
        return INSTANCE;
    }

    public void act(Actor actor) {
        log.debug("Move");
        // or, AI stuff goes here
    }

    public boolean isTickable() {
        return true;
    }

}

```

new class:

```
public enum Ability {
    MOVE(ActorMove.INSTANCE), FIGHT(ActorFight.INSTANCE);

    private ActorAbility ability;

    private Ability(ActorAbility abilityClass) {
        this.ability = abilityClass;
    }

    public ActorAbility getAbility() {
        return this.ability;
    }
}

```

StdActor:

```
public class StdActor implements Actor {
private HashSet<Ability> abilities = new HashSet<>();

public void addAbility(Ability ability) {
    this.abilities.add(ability);
}

```

subclass:

```
public class StdCharClass extends StdActor {

    public StdCharClass() {
        addAbility(Ability.MOVE);
    }

}

```

and finally, usage:

```
HashSet<Ability> abilities = bob.getAbilities();
for (Ability ability : abilities) {
    ActorAbility abilityClass = ability.getAbility();
    if (abilityClass.isTickable()) {
        abilityClass.act(bob);
    }
}

```

output on tick()

```
12:44:15.835 [main] DEBUG ActorMove - Move

```
> 1 votes

---
Tags: java, ai
---


# Question
Title: How can I quantify a drawn line's straightness?
I'm working on a game which requires players to draw a line from a point A(x1,y1) to the other point B(x2,y2) on the screen of an Android device.

I want to find how well that drawing fits to a straight line. For instance, a result of 90% would mean the drawing almost perfectly fits the line. If players draw a curved line from A to B, it should get a low score.

The end points are not known in advance. How can I do this?

# Answer
A perfectly straight line would also be the shortest possible line with a total length of `sqrt((x1-x2)² + (y1-y2)²)`. A more scribbly line will be a less ideal connection and thus be inevitably longer.

When you take all individual points of the path the user drew and sum up the distances between them, you can compare the total length with the ideal length. The smaller the total length divided by the ideal length, the better the line.

Here is a visualization. When the black dots are the end-points of the gesture and the blue points are the points you measured during the gesture, you would calculate and add up the lengths of the green lines and divide it by the length of the red line:

A score or sinuosity index of 1 would be perfect, anything higher would be less perfect, anything below 1 would be a bug. When you prefer to have the score in percent, divide 100% by that number.
> 53 votes

# Answer
This might not be the best way to implement this either, but I suggest a RMSD (root mean square deviation) could be better, than merely the distance method, in cases mentioned by Dancrumb (see first two lines below).

`RMSD = sqrt(mean(deviation^2))`

Note:

* The sum of the absolute deviations (integral-like) might be better, as it does not average out positive errors with negative ones. ( `=sum(abs(deviation))`)
* You probably would have to search the shortest distance to the linear line if there is a way that creates shorter distances than dropping the perpendicular.

(Please excuse the low quality of my drawing)

As you see, you have to

1. find an **orthogonal vector to your line** (dot-product equals 0).
If your line points towards `(1, 3)` you'd want `(3, -1)` (trough the origin each)
2. **Measure the distances** `h` from the ideal line to the user one, parallel to that vector.
3. **Calculate** the RMSD or sum of absolute differences.
> 32 votes

# Answer
Existing answers do not take into account that the end points are arbitrary (rather than given). Thus, when measuring the straightness of the curve, it does not make sense to use the end points (for example, to calculate expected length, angle, position). A simple example would be a straight line with both ends kinked. If we measure using the distance from the curve and the straight line between the end points this will be quite large, as the straight line we have drawn is offset from the straight line between the end points.

How do we tell how straight the curve is? Assuming that the curve is smooth enough, we want to know how much, on average, the tangent to the curve is changing. For a line, this would be zero (as the tangent is constant).

If we let the position at time t be \\$(x(t),y(t))\\$, then the tangent is \\$(D\_x(t),D\_y(t))\\$, where \\$D\_x(t)\\$ is the derivative of x at time t.

If the curve is not parameterized by arc-length, we normalize by dividing by \\$||(D\_x(t),D\_y(t))||\\$.

So we have a unit vector (or angle) of the tangent to the curve at time t. So, the angle is \\$a(t)=(D\_x(t),D\_y(t))/||(D\_x(t),D\_y(t))||\\$

We are then interested in \\$||D\_a(t)||^2\\$ integrated along the curve.

Given that we most likely have discrete data points rather than a curve, we must use finite differences to approximate the derivatives. So, \\$D\_a(t)\\$ becomes \\$\frac{a(t+h)-a(t)}{h}\\$. And, \\$a(t)\\$ becomes $$\frac{(x(t+h)-x(t))/h,(y(t+h)-y(t))/h}{||((x(t+h)-x(t))/h,(y(t+h)-y(t))/h)||}$$

Then we then get S by summing up \\$h||D\_a(t)||^2\\$ for all data points and possibly normalizing by the length of the curve. Most likely, we use \\$h=1\\$, but it really is just an arbitrary scale factor.

To reiterate, S will be zero for a line and larger the more it deviates from a line. To convert to the required format, use \\$\frac{1}{1+S}\\$. Given that the scale is somewhat arbitrary, it is possible to multiply S by some positive number (or transform it in some other way, e.g. use \\$bS^c\\$ instead of S) to adjust how straight certain curves are.
> 24 votes

# Answer
This is a grid based system, right? Find your own points for the line and calculate the slope of the line. Now, using that calculation, determine valid points that the line would pass through, given some margin of error off the exact value.

Through a short amount of trial-and-error testing, determine what good and bad amount of matching points would exist and set your game up using a scale for the same results from your testing.

i.e. A short line with almost horizontal slope may have 7 points that you could draw through. If you can consistently match 6 or more of the 7 that were determined to be part of the straight line, then that would be the highest score. Grading for length and accuracy should be part of the scoring.
> 3 votes

# Answer
A very easy and intuitive measure is the area between the best fitting straight line and the actual curve. Determining this is fairly straightforward:

1. Use a least-squares fit on all points (this prevents the end-kink problem mentioned by Joel Bosveld).
2. For all points on the curve, determine the distance to the line. This is also a standard problem. (linear algebra, base transform.)
3. Sum all distances.
> 3 votes

# Answer
The idea is to keep all the points the user touched, then evaluate and sum the distance between each of those points to the line formed when the user releases the screen.

Here is something to get you started in pseudo-code:

```
bool mIsRecording = false;
point[] mTouchedPoints = new point[];

function onTouch
  mIsRecording = true

functon update
  if mIsRecording
    mTouchedPoints.append(currentlyTouchedLocation)

function onRelease
  mIsRecording = false

  cumulativeDistance = 0

  line = makeLine( mTouchedPoints.first, mTouchedPoints.last )

  for each point in mTouchedPoints:
    cumulativeDistance = distanceOfPointToLine(point, line)

  mTouchedPoints = new point[]

```

What is `cumulativeDistance` could give you an idea on the fitting. A distance of 0 would mean the user was straight on the line all the time. Now you'd have to do some tests to see how it behaves in your context. And you might want to amplify the value returned by `distanceOfPointToLine` by squaring it to penalize more the large distances away from the line.

I'm not familiar with unity, but the code in `update` here may go in a `onDrag` function.

And you might want to add somewhere in there some code to prevent registering a point if it's the same as the last one registered. You don't want to register stuff when the user does not move.
> 2 votes

# Answer
One method you could use is to subdivide the line into segments and do a vector dot product between each vector that represents the segment and a vector representing a straight line between the first and last point. This has the benefit of letting you find extremely "spiky" segments easily.

Edit:

Also, I would consider using the length of the segment in addition to the dot product. A very short but orthogonal vector should count less than a long one that has less of a deviation.
> 2 votes

# Answer
The easiest and quickest might be simply to find out how thick the line would have to be to cover all the points of the user drawn line.

The thicker the line has to be, the worse the user did in drawing their line.
> 1 votes

# Answer
Somehow referring to MSalters Answer, here is some more specific information.

Use the least squares method to fit a line for your points. You are basically looking for a function y=f(x) which fits best. Once you have it you can use the actual y values to sum the square of differences:

s = sum over ( (y-f(x))^2 )

The smaller the sum, the straighter the line.

How to get the best approximation, is explained here: https://web.archive.org/web/20210506231850/http://math.mit.edu/~gs/linearalgebra/ila0403.pdf

Just read from "Fitting a straight line". Note that t is used instead of x and b instead of y. C and D is to be determined as approximation, then you have f(x) = C + Dx

Additional Note: Obviously, you also have to take the length of the line into account. Every line consisting of 2 Points will be perfect. I do not know the exact context, but I guess I would use the sum of squares divided by the number of points as rating. Also I would add the requirement of a minimal length, minimal number of points. (Maybe about 75% of the maximun length)
> 0 votes

---
Tags: algorithm, geometry, touch
---


title: How do I wrap an image around a sphere?

text:
# Question
Title: How do I wrap an image around a sphere?
Ideally I'd like a reference of the math involved, so I can start breaking down the problem.

The simplest thing I can deduce about this problem is that the part of the sphere that the user is currently seeing is a circle on the image that is located somewhere on the image, and the rest of the coordinates on the image are somehow mapped to 3D with a linear transformation.

Consider the following example:

If I rotate the sphere theta degrees on the Y axis (up/down) to the left, the sun will come close to the center of the sphere and the tree that is currently positioned in the center will be shifted to the left as the three on the left currently is. You can consider that the volume of the image is exactly enough to have the image completely wrap the sphere.

# Answer
Part of what you are looking for is an understanding of map or sphere projections.

http://en.wikipedia.org/wiki/Map\_projection

A rectangle is not a sphere. (I know it's obvious, but useful to state.) To map a rectangle onto a sphere, you have some choices about how to do it. Your picture looks like it's an "equirectangular" mapping, which maps vertical position to latitude and horizontal position to longitude, like a classic wall map.

And this format is pretty standard for sphere pictures and sky environments, and is what @Dudeson's shader is doing.

But! It's valuable to know that it's a choice, and there are other projections. For example, "fisheye" projections like the one below are created by some cameras and are standard for planetarium projection images.
> 1 votes

# Answer
Expressed as a GLSL fragment shader (untested):

```
const float M_1_PI = 1.0 / 3.1415926535897932384626433832795;
const float M_1_2PI = 1.0 / 6.283185307179586476925286766559;

uniform sampler2D texture1;

varying vec3 v_normal;

void main(void)
{
    vec3 n_normal = normalize(v_normal);

    vec2 texture_coordinate;
    texture_coordinate.x = 0.5 - atan(n_normal.z, n_normal.x) * M_1_2PI;
    texture_coordinate.y = 0.5 - asin(-n_normal.y) * M_1_PI;

    gl_FragColor = texture2D(texture1, texture_coordinate);
}

```
> 2 votes

---
Tags: mathematics, uv-mapping, sphere
---


# Question
Title: dynamic 2d texture creation in unity from script
I'm coming from HTML5 and I'm used to having the 2D Canvas API I can use to generate textures. Is there anything similar in Unity3D?

For example, let's say at runtime I want to render a circle, put 3 initials in the middle and then take the result and put that in a texture. In HTML5 I'd do this

```
var initials = "GAT";
var textureWidth = 256;
var textureHeight = 256;

// create a canvas
var c = document.createElement("canvas");
c.width = textureWidth;
c.height = textureHeight;
var ctx = c.getContext("2d");

// Set the origin to the center of the canvas
ctx.translate(textureWidth / 2, textureHeight / 2);

// Draw a yellow circle
ctx.fillStyle = "rgb(255,255,0)"; // yellow
ctx.beginPath();
var radius = (Math.min(textureWidth, textureHeight) - 2) / 2;
ctx.arc(0, 0, radius, 0, Math.PI * 2, true);
ctx.fill();

// Draw some black initials in the middle.
ctx.fillStyle = "rgb(0,0,0)";
ctx.font = "60pt Arial";
ctx.textAlign = "center";
ctx.fillText(initials, 0, 30);

// now I can make a texture from that
var tex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, c);
gl.generateMipmap(gl.TEXTURE_2D);

```

I know I can edit individual pixels in a Unity texture but is there any higher level API for drawing to texture in unity?

# Answer
> 2 votes
Theoretically you could do what you are asking for, however it may run differently and give you different results on different devices.

The Unity way of doing things would be to create a prefab game object that has a circle graphic and a text object attached to it and when you instantiate it you can change the size & color of the circle (even stretch it to an oval if you want) and change the size, text & color of the text object.

If you want to go down that path and need more details let me know what you need more details on.

If you have your heart set on drawing your own texture you will basically need to create an empty texture and then set the color of each pixel via code.

```
var texture = new Texture2D(2, 2, TextureFormat.ARGB32, false);

texture.SetPixel(0, 0, Color(1.0, 1.0, 1.0, 0.5));
texture.SetPixel(1, 0, Color.red);
texture.SetPixel(0, 1, Color.green);
texture.SetPixel(1, 1, Color.blue);

texture.Apply();

```

You would of course want to create an entire class to create texture object so you didn't have to do it by hand and there is probably something on the asset store that already does all that, so maybe start there.

---
Tags: unity
---


# Question
Title: Speed needed to make a car jump from a ramp
I need to make a car jump from a ramp to another, and I need this to be done using AI so I thought it would be enough to set a fixed speed for my car when near the ramp, in order to let it jump correctly.

It works fine if I input the speed manually but I'd like my game to calculate it since the ramps will be generated by user's input.

Unfortunately my physics knowledge lacks, so I need your help.

The problem is summarized in the picture below.

Basically, what I need to compute is the speed (in m/s) that the car has to have on the highest point of the first ramp, given that all the data in red are user's input.

I had some rough ideas on using the projectile range with `x=L, y=h-launchRampHeight` but the results weren't as I expected them so I gave up.

Do you have any hints on this?

Please note that both ramps have the same length (50m).

EDIT:

Based on @mklingen here's the `C#` code that I'm using (where `Distance = L`)

```
var speed = (Mathf.Sqrt(g)*Mathf.Sqrt(Distance)*Mathf.Sqrt((1/Mathf.Sin(Theta)))* Mathf.Sqrt((1/Mathf.Cos(Theta))))/Mathf.Sqrt(2);

```

What happens is quite weird though.

For example, with `theta = 19, L = 196, h = 46` my code returns `80.54646` which seems to work if I input it to the car. However running the expression in WolframAlpha leads to `55.8` which is wrong.

It may seem that the code is correct but with `theta = 35, L = 261, h = 39` my code returns `NaN` while WolframAlpha shows `52.17` which made the jump happen.

So, tu summarize, I have 2 different cases in which my result is different from WolframAlpha's one and none of them is the correct one both the times.

What's going on?

# Answer
> 0 votes
I solved it using kinematics but got a much more complex equation than what you have already.. I think it should work, and I've double-checked the math (and did a bunch of it using wolfram), but I'm wary of it just because of how long the equation came out to be.

where y = the height of the second ramp - the end height of the first ramp, and g is positive

See solution at wolframalpha.com

---
Tags: c#, unity, physics, projectile-physics
---


# Question
Title: FPS issue between computers results in slow down of animations and moving
I have been developing my game on two computers. I recently got a new computer and have noticed an issue that seems to be happening in my game.

When computer 1 runs the game at 60 FPS everything seems to run fine, all the timings are correct and everything runs smoothly.

When computer 2 runs the game at 60 FPS everything seems to slow down, everything happens properly (all the timings are correct) but it's as if the update is not being called at 60 FPS. If I "unlock" the frame rate and let it go to \>3000 fps then it runs fine, but not when it's at the expected 60 FPS. A frame counter in code seems to tell me the FPS is 59.

I'm not sure if this is relevant but I usually use something like this to perform updates between moving or animations, etc:

```
 public bool ShouldUpdate(GameTime gameTime)
 {
     if (this.Disable)
         return false;

     float dpf = this.DelayPerFrame; // example value: 60f
     float tpf = 1.0f / dpf;

     this.totalElapsedTime += (float)gameTime.ElapsedGameTime.TotalSeconds;

     if (this.totalElapsedTime >= tpf)
     {
         this.totalElapsedTime = 0f;

         return true;
     }

     return false;
 }

```

What kind of things can be causing this? I'm more than happy to add any additional information.

I guess my question really comes down to, how do I ensure that all updates and timings happen the same across computers?

# Answer
You shouldn't be trying to ensure that all your updates happen after X milliseconds - the existing game loop does that already. Instead, what you should be doing is applying delta time correction to your updates to ensure your updates, no matter how frequent or infrequent, regular or irregular, all happen at the same rate.
An example is as follows, and is rather simple to implement.

```
float delta = (float)gameTime.ElapsedGameTime.TotalSeconds;
position += velocity * delta;

```

What this does is effectively scale your update logic to move according how much time has elapsed since the last update. If you move at 1 meter/second, and you update 10 times a second, each update will move you forward 10cm. Update 20 times/second, move forward 5cm each time. This has the advantage of keeping everything moving at the same rate on different machines despite the number of updates occuring.
> 4 votes

---
Tags: xna, game-design, monogame
---


title: 2D game world engine

text:
# Question
Title: 2D game world engine
I'am starting to develop a 2D game with snake or worm.

My question now is: When my snake reaches the right edge the world should move. (Like in this game) My first thought was to implement a camera and to create a huge image for the world. (e.g 4096 x 512). So I only have to move the camera to solve the problem.

Is that a good solution?

# Answer
You could do that, but if the image is just the same pattern repeated over and over, you are better off using a smaller texture with "texture repeat" since that will use less memory. If your image varies and isn't just repeating, tiled graphics is also another good alternative to a single large texture. Tiled graphics use small image tiles and set them down in a pattern of your choosing to make it look interesting. But, a large texture isn't the end of the world, so your solution would work in a pinch too, yep.
> 1 votes

---
Tags: c#, unity
---


# Question
Title: Stepping through 3D noise to generate a cubemap for a sphere
This is somewhat related to a previous question I asked How to create a seamless cubemap noise texture?

I have managed to successfully step through a 3D noise function to create a cubemap texture which I'm then applying to an icosphere. This is done by stepping though it as suggested above.

However, I'm getting some mixed results on some of my edges:

In this picture, I'm not sure if it's clear but you can see the seam up the middle. However, this "seam" is actually perfectly smooth from a noise perspective. The problem is that both of these cube faces seem to be distorted, like they are being dragged up the sphere.

This picture shows one of the corners. Again, the noise is perfectly fine, but I think it's obvious that the way I'm stepping through my noise along a sphere surface is wrong. It's like it's going in opposite directions?

From RenderDoc I was able to retrieve the actual cubemap generated:

Which I think shows the this problem is only apparent on a few face edges, or at least, not all of them.

The code I'm using goes through all six faces individually (so that I don't have to generate the noise from inside the sphere, just the surface). The code looks like this:

```
...
glm::vec3 origin = glm::vec3(100,100,100); // really whatever, just some arbitrary point
int radius = 100; // the "size" of my textures

glm::vec3 dimensions = glm::vec3(radius,radius,radius);

ImageObject img1;
ImageObject img2;
ImageObject img3;
ImageObject img4;
ImageObject img5;
ImageObject img6;

for(int y = radius-1; y >= 0; --y)
{
    for(int z = 0; z < radius; ++z)
    {
        glm::vec3 pointDirection = glm::normalize(glm::vec3(0,y,z)-origin);
        glm::vec3 pointOnSphere = pointDirection * dimensions;
        glm::vec3 pointOnSphereAdjustedForCenter = pointOnSphere + origin;

        float noise = noise_function(pointOnSphereAdjustedForCenter.x,    pointOnSphereAdjustedForCenter.y,pointOnSphereAdjustedForCenter.z);

        img1.SetPixel(y,z,0,noise);
    }
}

for(int y = 0; y < radius; ++y)
{
    for(int z = 0; z < radius; ++z)
    {
        glm::vec3 pointDirection = glm::normalize(glm::vec3(radius-1,z,y)-origin);
        glm::vec3 pointOnSphere = pointDirection * dimensions;
        glm::vec3 pointOnSphereAdjustedForCenter = pointOnSphere + origin;

        float noise = noise_function(pointOnSphereAdjustedForCenter.x,    pointOnSphereAdjustedForCenter.y,pointOnSphereAdjustedForCenter.z);

        img2.SetPixel(z,radius-1-y,0,noise);
    }
}

for(int x = radius-1; x >= 0; --x)
{
    for(int z = 0; z < radius; ++z)
    {
        glm::vec3 pointDirection = glm::normalize(glm::vec3(x,0,z)-origin);
        glm::vec3 pointOnSphere = pointDirection * dimensions;
        glm::vec3 pointOnSphereAdjustedForCenter = pointOnSphere + origin;

        float noise = noise_function(pointOnSphereAdjustedForCenter.x,    pointOnSphereAdjustedForCenter.y,pointOnSphereAdjustedForCenter.z);

        img3.SetPixel(z,x,0,noise);
    }
}

for(int z = 0; z < radius; ++z)
{
    for(int x = 0; x < radius; ++x)
    {
        glm::vec3 pointDirection = glm::normalize(glm::vec3(x,0,z)-origin);
        glm::vec3 pointOnSphere = pointDirection * dimensions;
        glm::vec3 pointOnSphereAdjustedForCenter = pointOnSphere + origin;

        float noise = noise_function(pointOnSphereAdjustedForCenter.x,    pointOnSphereAdjustedForCenter.y,pointOnSphereAdjustedForCenter.z);

        img4.SetPixel(radius-1-z,x,0,noise);
    }
}

for(int y = radius-1; y >= 0; --y)
{
    for(int x = 0; x < radius; ++x)
    {
        glm::vec3 pointDirection = glm::normalize(glm::vec3(x,0,z)-origin);
        glm::vec3 pointOnSphere = pointDirection * dimensions;
        glm::vec3 pointOnSphereAdjustedForCenter = pointOnSphere + origin;

        float noise = noise_function(pointOnSphereAdjustedForCenter.x,    pointOnSphereAdjustedForCenter.y,pointOnSphereAdjustedForCenter.z);

        img5.SetPixel(y,radius-1-x,0,noise);
    }
}

for(int y = radius-1; y >= 0; --y)
{
    for(int x = 0; x < radius; ++x)
    {
        glm::vec3 pointDirection = glm::normalize(glm::vec3(x,y,radius-1)-origin);
        glm::vec3 pointOnSphere = pointDirection * dimensions;
        glm::vec3 pointOnSphereAdjustedForCenter = pointOnSphere + origin;

        float noise = noise_function(pointOnSphereAdjustedForCenter.x,    pointOnSphereAdjustedForCenter.y,pointOnSphereAdjustedForCenter.z);

        img6.SetPixel(y,x,0,noise);
    }
}

```

I'm sure that the problem is the way that I'm stepping through each cube face. I'm stepping in different directions. I had to do this because it was the only way to get my cubemap textures to line-up; but now that they're lined up, they've got something going wrong with them.

# Answer
Okay, I solved the problem.

As the guys commenting above pointed out, the code was weird. It wasn't really clear what was happening. This was a result of my brute forcing axis until the individual faces aligned.

However, it's what resulted in the above. So I've taken the time to draw on paper how each face should be stepped through and I found the answer.

It might not be immediately clear in the picture of the cubemap above but the whole noise is stretched. If you look at this reference:

You can see on my cubemap that the +Y, -X and +Z faces are stretched to the top left, and the other faces are stretched to the top right.

One of the things I was doing wrong was only sampling half of the noise, and then stretching it to cover the texture. This happened because where I was getting the direction from origin, was only ever in one direction along that axis.

E.g. Let's say my origin is at `20,20,20` and the radius is `10`.

```
for(int y = radius-1; y >= 0; --y)
{
    for(int z = 0; z < radius; ++z)
    {
        glm::vec3 pointDirection = glm::normalize(glm::vec3(0,y,z)-origin);

```

From the start of the loops this will be `{0,9,0} - {20,20,20}` which gives me `{-20,-11,-20}`, at the end it will be `{0,0,9} - {20,20,20}` which is then `{-20,-20,-11}`. This is the negative x axis BTW, the the direction is in both cases, negative on the x axis, so this is good.

But then on the *positive* X axis

```
for(int y = 0; y < radius; ++y)
{
    for(int z = 0; z < radius; ++z)
    {
        glm::vec3 pointDirection = glm::normalize(glm::vec3(radius-1,z,y)-origin);

```

I'm going to get at the start, `{9,0,0} - {20,20,20}` to give me result of `{-11,-20,-20}` and at the end of the loop: `{9,9,9} - {20,20,20}` and the result is `{-11.-11,-11}`!

Whoops! On both the positive and negative x axis (and this is the same for the other axis), I'm always sample from the negative direction on my where, but in one case I'm taking all the noise, in the other only half and stretching.

So that's why it matched up as well. It was from the same point and travelling back in the same direction. AND that's what gave my the stripe where it looked like it was being dragged up, it was in fact and mirror image, with one side of the mirror being stretched and distorted more than then other (so it wasn't immediately apparent).

A few things need to change. I needed to sample around the origin from the beginning and correct the positions for the texture later. This meant that I no longer has to screw around with which axis goes where either.

So the amended code should look like this:

```
...
glm::vec3 origin = glm::vec3(100,100,100); // really whatever, just some arbitrary point
int radius = 100; // the "size" of my textures

glm::vec3 dimensions = glm::vec3(radius/2,radius/2,radius/2);

ImageObject img1;
ImageObject img2;
ImageObject img3;
ImageObject img4;
ImageObject img5;
ImageObject img6;

for(int y = origin.y-dimensions.y; y < origin.y+dimensions.y; ++y)
{
    for(int z = origin.z-dimensions.z; z < origin.z+dimensions.z; ++z)
    {
        glm::vec3 pointDirection = glm::normalize(glm::vec3(origin.x-dimensions.x,y,z)-origin);
        glm::vec3 pointOnSphere = pointDirection * dimensions;
        glm::vec3 pointOnSphereAdjustedForCenter = pointOnSphere + origin;

        float noise = noise_function(pointOnSphereAdjustedForCenter.x,    pointOnSphereAdjustedForCenter.y,pointOnSphereAdjustedForCenter.z);

        img1.SetPixel(y-origin.y+dimensions.y,z-origin.x+dimensions.z,0,noise);
    }
}

for(int y = origin.y-dimensions.y; y < origin.y+dimensions.y; ++y)
{
    for(int z = origin.z-dimensions.z; z < origin.z+dimensions.z; ++z)
    {
        glm::vec3 pointDirection = glm::normalize(glm::vec3(origin.x+dimensions.x,z,y)-origin);
        glm::vec3 pointOnSphere = pointDirection * dimensions;
        glm::vec3 pointOnSphereAdjustedForCenter = pointOnSphere + origin;

        float noise = noise_function(pointOnSphereAdjustedForCenter.x,    pointOnSphereAdjustedForCenter.y,pointOnSphereAdjustedForCenter.z);

        img2.SetPixel(z-origin.x+dimensions.z,radius-1-(y-origin.y+dimensions.y),0,noise);
    }
}

for(int x = origin.x-dimensions.x; x < origin.x+dimensions.x; ++x)
{
    for(int z = origin.z-dimensions.z; z < origin.z+dimensions.z; ++z)
    {
        glm::vec3 pointDirection = glm::normalize(glm::vec3(x,origin.y+dimensions.y,z)-origin);
        glm::vec3 pointOnSphere = pointDirection * dimensions;
        glm::vec3 pointOnSphereAdjustedForCenter = pointOnSphere + origin;

        float noise = noise_function(pointOnSphereAdjustedForCenter.x,    pointOnSphereAdjustedForCenter.y,pointOnSphereAdjustedForCenter.z);

        img3.SetPixel(radius-1-(z-origin.x+dimensions.z),x-origin.x+dimensions.x,0,noise);
    }
}

for(int z = origin.z-dimensions.z; z < origin.z+dimensions.z; ++z)
{
    for(int x = origin.x-dimensions.x; x < origin.x+dimensions.x; ++x)
    {
        glm::vec3 pointDirection = glm::normalize(glm::vec3(x,origin.y-dimensions.y,z)-origin);
        glm::vec3 pointOnSphere = pointDirection * dimensions;
        glm::vec3 pointOnSphereAdjustedForCenter = pointOnSphere + origin;

        float noise = noise_function(pointOnSphereAdjustedForCenter.x,    pointOnSphereAdjustedForCenter.y,pointOnSphereAdjustedForCenter.z);

        img4.SetPixel(z-origin.x+dimensions.z,x-origin.x+dimensions.x,0,noise);
    }
}

for(int y = origin.y-dimensions.y; y < origin.y+dimensions.y; ++y)
{
    for(int x = origin.x-dimensions.x; x < origin.x+dimensions.x; ++x)
    {
        glm::vec3 pointDirection = glm::normalize(glm::vec3(x,y,origin.z-dimensions.z)-origin);
        glm::vec3 pointOnSphere = pointDirection * dimensions;
        glm::vec3 pointOnSphereAdjustedForCenter = pointOnSphere + origin;

        float noise = noise_function(pointOnSphereAdjustedForCenter.x,    pointOnSphereAdjustedForCenter.y,pointOnSphereAdjustedForCenter.z);

        img5.SetPixel(y-origin.y+dimensions.y,radius-1-(x-origin.x+dimensions.x),0,noise);
    }
}

for(int y = origin.y-dimensions.y; y < origin.y+dimensions.y; ++y)
{
    for(int x = origin.x-dimensions.x; x < origin.x+dimensions.x; ++x)
    {
        glm::vec3 pointDirection = glm::normalize(glm::vec3(x,y,origin.z+dimensions.z)-origin);
        glm::vec3 pointOnSphere = pointDirection * dimensions;
        glm::vec3 pointOnSphereAdjustedForCenter = pointOnSphere + origin;

        float noise = noise_function(pointOnSphereAdjustedForCenter.x,    pointOnSphereAdjustedForCenter.y,pointOnSphereAdjustedForCenter.z);

        img6.SetPixel(y-origin.y+dimensions.y,x-origin.x+dimensions.x,0,noise);
    }
}

```

Finally:
> 5 votes

---
Tags: opengl, c++, perlin-noise, cubemap, simplex-noise
---


# Question
Title: How to load in meshes efficiently into DirectX11
I wanted to know if there was a standard and efficient method to load meshes from a file into DirectX11. Currently, I'm loading .obj's by parsing them in and storing their information into a vertex buffer. This appears to be extremely slow especially when I have meshes with many vertices like the Stanford Dragon or other standard objects like the Mitsuba or Buddha.

# Answer
The general approach for games is that models are created and edited in some 'source' format (like WaveFront OBJ, Autodesk FBX, etc.). The models are then "exported" to some format which is optimized for runtime usage, usually something specific to the game engine being used.

DirectX Tool Kit supports loading Models from VBO, CMO, and SDKMESH as example runtime formats. CMO files can be created by VS 2012+ directly from FBX, DAE, or OBJ files. SDKMESH files can be created from FBX files using the Samples Content Exporter. All three can be also be created from OBJ files using the **meshconvert** command-line tool in DirectXMesh.

See this wiki for more content file formats.
> 2 votes

---
Tags: c++, directx11, graphics-programming
---


title: Good approach in designing game classes

text:
# Question
Title: Good approach in designing game classes
I took a semester-long course in java but I'm still a beginner in Object-Oriented programming paradigm. Suppose that I want to create a simple game where the player can go to different locations. Each location has its own unique treasure (that has other attributes) and has its own set of different animals. The question: How can I design classes that are not too naive based on the game? (can be too broad) Is my approach below correct or can it be improved? (narrowed)

I was thinking that I should create a Location, treasure, and Animal classes; Each classes declared in its own file.

```
public class Location {
    // attributes such as treasure and animals
    private ArrayList<Animal> animals;
    private Treasure treasure;
    public Location(String name) {
        // initialization of attributes
        if(name.equals("Jungle")) {
            treasure = new Treasure("Rare Vine");
            animals.add(new Animal("Monkey", 90, 50);
            animals.add(new Animal("Snake", 100, 60);
        }
        else if(name.equals("Valley")){
            // and so on
        }
        // and so forth
    }
}
public class Treasure {
    // attributes such as name and value
    public Treasure(String name, int value) {
        // initialization of attributes
        this.name = name;
        this.value = value;
    }
}
public class Animal {
    // attributes such as name
    public Animal(String name, int encounterRate, int captureRate) {
        // initialization of attributes
        this.name = name;
        this.encounterRate = encounterRate;
        this.captureRate = captureRate;
    }
}

```

But I doubt that the use of conditional statements in Location class to initialize its attributes makes the method have so many lines and may confuse the developer after some time. what if there are so many attributes per location and there are many locations?

Another approach that I can think of is to create subclasses of Location and put the corresponding values for the location's attributes. For me, I can understand the structure of the game and efficient if the number of location subclasses is small.

I'm new in creating java games so I don't have a solid view in designing game classes. this problem may be broad so I narrowed it down to my code above.

# Answer
> How can I design classes that are not too naive based on the game?

The trick is to:

1. Make a rough design (as you've done).
2. Implement it (as you're doing).
3. Test it.
4. Adjust 1 and 2 as required, carry out 3, then rinse and repeat until it feels right.

If you feel it can be improved, improve it until you do not feel the need to improve it any more.

Don't get too caught up in the design phase though, it's very important to implement and test. This is a very subjective topic, as it's your game, your vision, your design at the end of the day, but iterating until it feels complete is the way to go.

Ideas and designs are easy - actually making them happen is another. If need be, your code and structure acts as the game's design. It's a living, changing document. Start with an idea and evolve it as you test and progress.

What you have sounds like a good start, so test it out, adjust as required. I would not worry about what you're worrying about, as even the act of posting your question here has you stopped in your tracks -- you've imposed a problem on yourself before it's actually been deemed a problem. Don't second-guess for now, just say, "this works well enough for now, I'll keep going". If it becomes an issue when it is actually an issue, change it then; it's okay to refactor when the need arises. For now, go forth with what you've got, don't get caught out with the entire design before the game's actually been made.

There are so many different ways to accomplish different things with programming, but failure to actually make them happen can happen if you dwell too much. If things start to get confusing, write documentation to help clear up any confusion. Some systems are very complex, it happens. Start small, iterate, advance, and repeat until you call your game done. Good luck!
> 0 votes

---
Tags: java, oop
---


title: Rotate about a skybox

text:
# Question
Title: Rotate about a skybox
I'm a beginner with OpenGl so please discount my ignorance. I've managed to create a skybox (with a texture mapped cube) and would like to rotate the view (eye) around the center of the box, so I can admire the view :). By changing the X/Y coordinates of eye/camera in `GLM.LookAt()` I'm able to see most of the faces of the skybox but I'm not able to see the top and bottom faces though I'm sure that they are rendered. In any case what's the best way to rotate around the skybox? What I want to do is exactly shown in this video

Thanks!

EDIT: Sorry for the lack of relevant information.

1. I'm using OpenGL version 3.3.
2. Not using immediate mode. Everything is via shaders and VBO/VAO
3. I have already setup the projection, view and model matrices which I pass to the vertex shader, and obviously have the texture loading also working as I can render the skybox. At the moment i've set the projection and model matrices to Identity for simplicity.
4. I'm deriving the view matrix from GLM.LookAt(), So initially i thought that to rotate around the view box, I'd just have to change the viewMatrix
5. I'm working on C# using SharpGL
6. To draw the skybox, I've set up a VAO to draw a cube with vertices in the range (-1,-1,-1) and (1,1,1). Then I load 6 textures for each cube face to 6 Texture Units. During the rendering I draw the cube and update the texture for each face using a sampler variable. All of this seems to be working OK. I verified this my scaling down the size of the cube and checking if all 6 faces were being rendered properly by rotating the ModelMatrix

I suspect one problem is that I'm not positioning the camera in the center of the cube. At the moment it seems to be viewing the cube from outside. I'm still trying to grasp the usage of GLM.LookAt().

This is how I'm rendering the skybox at the moment. And I can see the front face of the cube, but how do I go about placing the camera in the center of the box and rotating it?

```
 viewMatrix = mat4.identity();
 projectionMatrix = mat4.identity();
 modelMatrix = mat4.identity();
 viewMatrix = glm.lookAt(new vec3(0f, 0f, 1f), new vec3(0f, 0f, 0f), new vec3(0.0f, 1.0f, 0.0f));

        shaderProgram.Bind(GL);
        shaderProgram.SetUniformMatrix4(GL, "projectionMatrix", projectionMatrix.to_array());
        shaderProgram.SetUniformMatrix4(GL, "viewMatrix", viewMatrix.to_array());
        shaderProgram.SetUniformMatrix4(GL, "modelMatrix", modelMatrix.to_array());

skyBox.renderSkybox(GL);

```

EDIT #2 I managed to figure out my error. I was trying to look at the Top and Bottom faces by doing `viewMatrix = glm.lookAt(new vec3(0f,-1f, 0f), new vec3(0f, 0f, 0f), new vec3(0.0f,1f, 0f));` and `viewMatrix = glm.lookAt(new vec3(0f, 1f, 0f), new vec3(0f, 0f, 0f), new vec3(0.0f,1f, 0f));` which was giving me a blank screen. The reason being that (0,1,0) is collinear with my up-vector and LookAt() couldn't generate the viewMatrix in this case. Changing the UpVector makes it OK!

# Answer
> 0 votes
There are different ways to implement / render a skybox but one way is to render the skybox first, turning off depth writes and using only the rotation from the camera, no translation. Then, you render the rest of your scene as normal on top of that. This gives the appearance that the skybox is infinitely far away and that you can never reach it, but you can see it all around you as you look different directions.

---
Tags: skybox
---


title: Networking Pong Clone

text:
# Question
Title: Networking Pong Clone
I have the fundamentals of TCP sockets, UDP communication etc, but can't find much on how to apply these to a real time game environment.

I have a Pong clone, with 4 players, and need to synchronise the paddle positions between the three clients and the server (the server is the fourth player). Currently I use UDP to send real time updates (paddle movements), and TCP for setting up the game lobby etc.

Is it a BAD THING to be spamming out huge amounts of UDP traffic? Should I look into something like DCCP for its congestion features? Or is this not really a problem with a small scale project like this?

When should synchronise messages be sent between client/server? Currently the server is spamming out UDP packets with the current game state as fast as it can manage, and clients are spamming out their paddle position back to the server as fast as they can. Is this the best way to do it? Is there some sort of delay I should add so messages are sent once every X milliseconds, or should I only be sending out messages as events happen? (eg paddle velocity changed due to user input)

Would it be better to make clients communicate their paddle positions with each other peer to peer?

I am asking these questions within the context of Pong but am also interested in how these problems would be overcome in other games, or generalised solutions.

# Answer
> 6 votes
Have a configurable update interval (so you can tweak and try 5 packets per second or 20), and each frame see if it's time to send an update. You might be ok with a simple game sending packets for each event, but in a more complex game this isn't practical. Also keep in mind that there is a packet overhead so if you are sending a bunch of small packets you are going to waste bandwidth.

Each update interval have each client send its paddle position to either the server, or to each client (peer-peer). Have the server also send the ball position and a velocity vector. Each client can run the same screen drawing code as it does in single player so the movement of the ball will be smooth. In multiplayer though you have only the server send the position/velocity updates for the ball at a regular interval (and if you like each time it hits something).

Have the ball position updates reference a gametime across all clients so you can discard out of order packets and even make the interpolation of the balls position more accurate (you know the position and velocity at a specific time in the past so you can interpolate the new position).

With this model with a laggy game you might see the ball move backwards at times or jump around a bit. But with a decent connection it should be pretty smooth.

# Answer
> 5 votes
Regarding traffic concerns - you want to avoid sending more than 20-30 packets per second per peer. In the general case, if you send smaller, fewer packets, you will experience (slightly) less latency and a lessened chance of dropped packets.

You definitely don't want to send updates at a speed faster than framerate, as players won't be able to tell the difference -- indeed, if you only send packets 10 times a second and interpolate/extrapolate the results on the receiving end, most players won't notice a difference.

# Answer
> 4 votes
This is a pretty broad question, but I'll try to summarize the important aspects.

The first decision to make in the network code for your game is whether you want a client/server setup of a peer to peer arrangement. Most games, with RTS probably being the only notable exception, are probably using a client/server architecture. The main advantage being that this arrangement is more fault tolerant and provides more control over what data each client receives. Peer to peer allows to send far less data, but requires each peer to fully simulate the world precisely as every other peer does. If one peer lags or desynchronizes, everyone must either wait for them to recover or they are simply lost.

UDP is generally the correct choice as well, certainly for any client/server model. TCP might be practical for a peer to peer game, but even then UDP might be a better choice. Basically, UDP handles less for you, which means more effort but also more control over how you deal with faults.

For Pong the choice I would make is client/server, being that it is an action oriented game. One thing to note here, even though you say that one player "is the server", you are best off structuring your code such that they are essentially running a local server and connecting to it as a client.

You definitely don't want to be "spamming" updates in any direction either. One update from the server per frame is all that is needed, and your server should be running at a fixed frame rate. What that is is up to you, but there is no need to go overboard. A 50ms frame (20 FPS) is plenty to get nice smooth game play. To keep things smooth on the client, you want to make use of interpolation. The client should be constantly transitioning between server frame snapshots, this could easily be the topic of a separate question though.

Client updates should be limited as well, though one per frame will likely be far too much if your client is running at a decent frame rate.

# Answer
> 1 votes
Do you care about cheating?

If not, going peer-to-peer will halve your lag, as it's A\<-\>C instead of A\<-\>B\<-\>C. If so, for fairness in synchronization you may want to make response somewhat laggy for the local player, or what most games do - let the player do whatever locally and then snap back if the server's result diverges from the locally simulated.

A pong clone is actually a bit tricky, because unlike most games you can't (as a developer) cheat by having one side see a hit and the other not.

As for something generalized, one technique I've heard of but haven't found necessary (may be for action games though) is to keep actions with their true timestamps (receive time - ping/2), and have the server roll back (snap) if an earlier-time event comes in, and then reapply later actions. That way, everybody is consistent locally unless there is some conflict due to different players' interactions. The only danger is the ability to 'roll back time' if they fake a laggy connection.

# Answer
> 1 votes
Google dead reckoning. Sending out updates for 4 players is not going to be significant. The amount of data sent is going to be on the order of bytes. So, that means frequent updates should be ok. With dead reckoning, you move the player on the client and the server. The server is the authority. When the clients position becomes too far out of synch from the server, it has to drift back into alignment. http://trac.bookofhook.com/bookofhook/trac.cgi/wiki/Quake3Networking Using UDP is the way to go. Bupdates will be sent to frequently that lost data will soon be replaced by incoming data anyway. The packet retransmit of TCP is not worth it for player position. Look at this article for more info on how to keep the client and server on synch.

# Answer
> 0 votes
I have programmed a 2-player-local-network-pong game a few weeks ago, here's how I did it:

-One side opens a server, the other one connects automatically -they are both spamming their paddles x position towards each other @ 60fps or less \[UDP\] -if one side hits the ball they decide about the balls new velocity and position and send that to the other one \[TCP\] -if the ball flies past a paddle, the player who missed it contacts the other one with an increase score message and the ball is reset \[TCP\] -the ball is getting simulated independently all the time, which suits the simple ball physics of pong

This creates roughly 0.3 to 0.5 KByte/s of traffic at 60fps and the players have no lag in their perception, but only if the ping is below a certain threshold, because the balls new position needs to be transmitted.

Also cheating is easy with this system and there's a high possibility to go out of sync with a very lossy connection, but who cares about cheating in pong?!

---
Tags: architecture, networking
---


# Question
Title: How do I convert a Source engine NPC model to a player model?
The Source engine's NPC and player models differ: An NPC model applied to the player has no animations. It cannot walk and holds its arms out to the side by about a foot. The weapon is held in the right hand and you can see the player switch weapons, but the weapons also have no animation.

How do I convert between these model types?

# Answer
> 1 votes
Source works a bit different than i guess you understand it. I can't claim that everything i write now is correct but it should point you in the general direction!

"Converting" a model:

* You can't just "convert" an model intended to be used on an specific NPC to a player model because the animations that you want to apply are called by actions, and the names of the actions are most likely different than the names of the actions that the player-controller/entity calls upon moving, shooting, etc.

What you need to do instead:

* You will need to recompile the model with different action names or reskin the npc-model to a player skeleton (hello blender / 3dsmax) that you can get by decompiling the player model. Trust me, both of this can be a whole new experience of pain in the ass, but it can and has been done before
* You will not need to recompile weapon-view models or anything that can also be used by the player anyway

I hope this helps you, you may also want to visit a source-engine specific forum to post this question into

Good Luck!

---
Tags: animation, models, npc, source-engine
---


# Question
Title: Quaternion Slerp and Lerp implementation (with overshoot)
I am working with Unity (C#) and was looking for an implementation of Slerp and possibly Lerp that allow overshoot (progress not strictly limited to 0..1 range). I want to do some tweening animation using an elastic ease-out function. My ease-out function returns values slightly outside the 0..1 range in order to get an oscillating-around-the-target effect. The problem is that Unity's Quaternion Lerp and Slerp functions appear to clamp the progress input in the 0..1 range.

Implementation code in any language would be helpful. I don't know enough about Quaternion math to write this myself.

# Answer
> 2 votes
Here’s a little example. Suppose you slerp `q0` and `q1` with a value of `t = 0.2` and a value of `t = 0.4`. This gives you a quaternion `s(0.2)` and a quaternion `s(0.4)`. Quaternion multiplication also gives us the following:

```
s(0.2) = q0 * inverse(q0) * s(0.2)
              '——————— K ————————'

```

So we have a value `K` which, when right-multiplied with `q0`, gives us `s(0.2)`. Now intuitively we can guess that multiplying twice will give us `s(0.4)`:

```
s(0.4) = q0 * inverse(q0) * s(0.2) * inverse(q0) * s(0.2)
              '——————— K ————————'   '——————— K ————————'

```

Simplifying:

```
s(0.4) = s(0.2) * inverse(q0) * s(0.2)

```

We can use this technique to slerp with values greater than `1` by just dividing by two. Which brings us to the following pseudocode:

```
quat slerp_generic(quat q0, quat q1, float t)
{
    // If t is too large, divide it by two recursively
    if (t > 1.0)
    {
        quat tmp = slerp_generic(q0, q1, t / 2);
        return tmp * inverse(q0) * tmp;
    }

    // It’s easier to handle negative t this way
    if (t < 0.0)
        return slerp_generic(q1, q0, 1.0 - t);

    return slerp(q0, q1, t);
}

```

---

**Edit**: the above code works great for `slerp`; for `lerp` however you’re going to get discontinuities in the derivative which you may not want. This code uses a similar technique and will work better for `lerp`:

```
quat lerp_generic(quat q0, quat q1, float t)
{
    // If t is too large, subtract 1.0 from it recursively
    if (t > 1.0)
    {
        quat tmp = lerp_generic(q0, q1, t - 1.0);
        return tmp * inverse(q0) * q1;
    }

    // It’s easier to handle negative t this way
    if (t < 0.0)
        return lerp_generic(q1, q0, 1.0 - t);

    return lerp(q0, q1, t);
}

```

---
Tags: unity, mathematics, quaternion
---


# Question
Title: Bug in XNA Developer function CalculateEigenVector() from the file "xnacollision.cpp"?
I am trying to decipher the content of the Microsoft XNA Developer source file "xnacollision.cpp" and I've found a function that calculates one of the three eigenvectors of a homogeneous system of three linear equations. The name of that function is **CalculateEigenVector()** and its content is as follows:

```
//-----------------------------------------------------------------------------
static inline XMVECTOR CalculateEigenVector( FLOAT m11, FLOAT m12, FLOAT m13,
                                         FLOAT m22, FLOAT m23, FLOAT m33, FLOAT e )
{
FLOAT f1, f2, f3;

FLOAT fTmp[3];
fTmp[0] = ( FLOAT )( m12 * m23 - m13 * ( m22 - e ) );
fTmp[1] = ( FLOAT )( m13 * m12 - m23 * ( m11 - e ) );
fTmp[2] = ( FLOAT )( ( m11 - e ) * ( m22 - e ) - m12 * m12 );

XMVECTOR vTmp = XMLoadFloat3( (XMFLOAT3*)fTmp );

if( XMVector3Equal( vTmp, XMVectorZero() ) ) // planar or linear
{
    // we only have one equation - find a valid one
    if( ( m11 - e != 0.0 ) || ( m12 != 0.0 ) || ( m13 != 0.0 ) )
    {
        f1 = m11 - e; f2 = m12; f3 = m13;
    }
    else if( ( m12 != 0.0 ) || ( m22 - e != 0.0 ) || ( m23 != 0.0 ) )
    {
        f1 = m12; f2 = m22 - e; f3 = m23;
    }
    else if( ( m13 != 0.0 ) || ( m23 != 0.0 ) || ( m33 - e != 0.0 ) )
    {
        f1 = m13; f2 = m23; f3 = m33 - e;
    }
    else
    {
        // error, we'll just make something up - we have NO context
        f1 = 1.0; f2 = 0.0; f3 = 0.0;
    }

    if( f1 == 0.0 )
        vTmp = XMVectorSetX( vTmp, 0.0f );
    else
        vTmp = XMVectorSetX( vTmp, 1.0f );

    if( f2 == 0.0 )
        vTmp = XMVectorSetY( vTmp, 0.0f );
    else
        vTmp = XMVectorSetY( vTmp, 1.0f );

    if( f3 == 0.0 )
    {
        vTmp = XMVectorSetZ( vTmp, 0.0f );
        // recalculate y to make equation work
        if( m12 != 0.0 )
            vTmp = XMVectorSetY( vTmp, ( FLOAT )( -f1 / f2 ) );
    }
    else
    {
        vTmp = XMVectorSetZ( vTmp, ( FLOAT )( ( f2 - f1 ) / f3 ) );
    }
}

if( XMVectorGetX( XMVector3LengthSq( vTmp ) ) > 1e-5f )
{
    return XMVector3Normalize( vTmp );
}
else
{
    // Multiply by a value large enough to make the vector non-zero.
    vTmp *= 1e5f;
    return XMVector3Normalize( vTmp );
}
}

```

In my opinion there are two mistakes:

1) The code snippet:

```
// recalculate y to make equation work
if( m12 != 0.0 )
   vTmp = XMVectorSetY( vTmp, ( FLOAT )( -f1 / f2 ) );

```

should be changed with:

```
if( f1 != 0.0f )
   vTmp = XMVectorSetX( vTmp, ( FLOAT )( -f2 / f1 ) );

if( f2 != 0.0f )
   vTmp = XMVectorSetY( vTmp, ( FLOAT )( -f1 / f2 ) );

```

2) In the next else block instead:

```
vTmp = XMVectorSetZ( vTmp, ( FLOAT )( ( f2 - f1 ) / f3 ) );

```

we must have:

```
vTmp = XMVectorSetZ( vTmp, ( FLOAT )( ( -f2 - f1 ) / f3 ) );

```

Please tell me if I am wrong or right!

# Answer
> 2 votes
Your point ① is **almost** correct. This is indeed a bug, but your fix is buggy, too. When `f1 != 0` and `f2 == 0` you’re going to set `X = 0` and your eigenvector will be zero. Here is the proper fix, much simpler:

```
// recalculate y to make equation work
if( f2 != 0.0 )
   vTmp = XMVectorSetY( vTmp, ( FLOAT )( -f1 / f2 ) );

```

Your point ② is correct. This is a bug and your fix gives the proper value for `Z`.

---
Tags: xna
---


# Question
Title: XNA Starting a parallel Thread during a draw loop is slower than doing the same task in the main thread in update loop
I'm using XNA and all of my drawing is done in the main thread. I am CPU-bound and I thought I could gain performance by moving some non-update logic (like animation update) from the update loop into the draw loop and performing it in a parallel thread. This is the pseudocode:

Before:

```
void Update()
{
    foreach (var model in AllGameModels)
        model.UpdateAnimation();
}

```

After:

```
void UpdateAnimation()
{
    foreach (var model in AllGameModels)
        model.UpdateAnimation();
}
Thread UpdateAnimationThread;

void Draw()
{
    if (UpdateAnimationThread != null)
        UpdateAnimationThread.Join();
    UpdateAnimationThread = new Thread(UpdateAnimation);

    [main Draw code follows]
}

```

Unfortunately this always results in a significant DROP in performance. What can I be doing wrong? There is NO multithreading code in the Draw loop as it is simply impossible to do and I am not missing anything.

# Answer
> 4 votes
Creating threads is expensive. If you’re going to perform animation processing each frame, it’s better to keep the thread around. Something like this:

```
void UpdateAnimationWorker()
{
    for (;;)
    {
        WaitForTrigger(); // waits for Draw() to signal us

        if (ShouldExit())
            break;

        foreach (var model in AllGameModels)
            model.UpdateAnimation();
    }
}

void Draw()
{
    AnimationTrigger(); // signal the animation thread

    [main Draw code follows]
}

```

There are lots of different ways to synchronise threads, and plenty of resources about threading in XNA. I suggest looking for “worker threads”. Also this MSDN thread seems to have good advice.

Also make sure that `Draw()` doesn’t rely on the results of `UpdateAnimation()`; in a typical game it does, and you don’t look like you have a mechanism to ensure that the results are ready before you draw them.

---
Tags: xna, optimization, multithreading
---


# Question
Title: How to add a UI Text for keeping Score in Unity 5
My Problem is simple I want to show scores on my game. The examples on internet are good but in Unity 5 there are no `GUI` elements but instead these are now `UI` elements. I was following this example: https://unity3d.com/learn/tutorials/projects/space-shooter/counting-points but it didn't work.
I followed the code and added a new `UI` text to the scene as in the picture. After adding the script to a `.cs` file and declaring `public GUIText scoreText;` and making this text as `prefab` when I drag it to the inspector panel it didn't get attached.
and it gave this error:

```
The variable scoreText of Fruits has not been assigned.
You probably need to assign the scoreText variable of the Fruits script in the inspector.

```

Fruit is a projectile and every time this projectile hits the container it should add the score. So how to do this in Unity 5. I've seen in one example online that on previous versions of unity there was this option of adding `GUI Text` in GameObject.

# Answer
I got the same problem, try this instead of using `public GUIText scoreText;`

Put `using UnityEngine.UI;` at the top of your `.cs` file and after that change the variable type from `GUIText` to just `Text` like this:

`public Text scoreText;`

Complete code for better example:

```
using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class GameController : MonoBehaviour
{
    public Text scoreText;

    // Use this for initialization
    void Start () {

    }
}

```

That should works fine.
> 5 votes

# Answer
Dragging the prefab file over gives it a reference to the prefab, not the actual instantiated version you've got in your scene.

If you drag the text box over from the scene itself, you should have no problem. You will see something like "GUIText" appear in Score Text instead of "None".
> 2 votes

---
Tags: c#, unity, 2d, gui, text
---


# Question
Title: How can I set up an intuitive perspective projection/view matrix combination in OpenGL, using GLM?
Could anyone help me set up an intuitive perspective camera matrix using OpenGL and the GLM library?

By "intuitive" I mean that I want the camera to be looking at the middle of the screen down the -Z axis, but I want it to be positioned in front of the camera to the exact degree that would cause a vector placement at `(0,0,0)` and a vector placement of `(screen_width, screen_height, 0)` to show up in the bottom-left and top-right corners respectively.

Feel free to ask me to clarify, if need be. This is what I have currently:

```
 glm::mat4 Projection = glm::perspective(45.0f, (GLfloat) window_width / (GLfloat) window_height, 0.1f, #X#);

 glm::mat4 View = glm::lookAt(
     glm::vec3(window_width/2, window_height/2, #X#), // camera position
     glm::vec3(window_width/2, window_height/2, 0), // look at origin
     glm::vec3(0, 1, 0)  // Head is up
 );

  glm::mat4 Model = glm::mat4(1.0f);

  glm::mat4 MVP = Projection * View * Model;

```

The `#X#`s are the arguments that I'm not sure how to calculate.

I don't know how to calculate the correct Z position for the camera, and I also don't know how far out to put my far clipping plane. (Should it be a fixed(large) value, or should it be based on my width/height?)

Also, is 45 degrees what I should be using? I've seen some people use values like 60 or 70.

I'm sure whatever the calculation function is would work based off of the angle/window\_width/window\_height and I'm also sure its easy if you know trig.

---

## EDIT

***In response to user1118321***

I tried to implement the solution provided, but it didn't quite give me what I'm looking for.

Here is the code I have now

```
float fov=45.0f;
glm::mat4 Projection = glm::perspective(fov, (GLfloat) window_width / (GLfloat) window_height, 0.1f, 10000.0f);

float angle1=fov/2.0;
float angle2=180 - (90 + angle1);
float Z = 0.5 * window_height * sin(glm::radians(angle2))/sin(glm::radians(angle1));
glm::mat4 View = glm::lookAt(
    glm::vec3(window_width/2, window_height/2, Z), // camera position
    glm::vec3(window_width/2, window_height/2, 0), // look at origin
    glm::vec3(0, 1, 0)  // Head is up
);

 glm::mat4 Model = glm::mat4(1.0f);

 glm::mat4 MVP = Projection * View * Model;

```

When I try to render a square, who's bottom left corner is at `(0,0,0)` and who's top right corner is at `(window_width, window_height,0)`, it doesn't span the entire screen.

This is what I get instead:

# Answer
user1118321's answer will provide you the correct answer, though it is more general than necessary. Since we're dealing with a right triangle, the easiest solution is to use the definition of the tangent function:

```
tan(α) = A / B

```

Substituting half the height of the screen, the z coordinate of the camera, and half the vertical field of view gets us:

```
tan(22.5°) = 0.5 * height / z

```

Solving for `z` gives:

```
z = height / (2 * tan(22.5°))

```

Then it's just a matter of picking your near and far planes such that `z_near < z` and `z_far > z`.

As for the reason you had trouble using user1118321's solution (which is equivalent to mine), this is because GLM recently switched to using radians everywhere. The `glm::perspective` function was based on GLU's `gluPerspective`, and therefore older versions accepted the field of view in degrees by default. Since GLM 0.9.6.0, all functions behave by default as if `GLM_FORCE_RADIANS` were specified.

I was able to reproduce your screenshot using my engine:

```
// ...
float fov_y = 45.f;
float z = 0.5 / tan(glm::radians(fov_y / 2.f));

mat4 view = glm::lookAt(
    vec3(0.5, 0.5, z), // camera position
    vec3(0.5, 0.5, 0), // look at origin
    vec3(0, 1, 0));
dd.setView(view);
dd.setProjection(glm::perspective(fov_y, 1.f, 0.5f, 100.f));

dd.point(0, 0);
dd.point(1, 1);
dd.linearGrid(4, 4, vec2(), vec2(1));
dd.rect(be::rect { vec2(), vec2(1) });
// ...

```

By specifying the `fov_y` to `glm::perspective` in radians instead of directly in degrees, we solve the problem:

```
// ...
dd.setProjection(glm::perspective(glm::radians(fov_y), 1.f, 0.5f, 100.f));
// ...

```
> 3 votes

# Answer
Check out the Law of Cosines. It allows you to calculate any side or angle in a triangle if you have the opposite 2 angles or sides. Or alternately, use the law of sines (described at the bottom of the above link).

In your case, you know that vertical field of view is 45 degrees and that the base side you want is the height of the screen. You can think of the setup of the camera pointing towards the scene as either a single isosceles triangle, or 2 right triangles. Let's look at the 2 right triangles case.

If the eye is at the apex of the focal angle, then we can divide things up like so: at the eye (or camera) are 2 angles, each 22.5°. Directly in front of them are 2 triangle bases, each 1/2 the height of the screen. So you know 2 angle (which means you know 3 angles), and 1 side. The angles are 90° (for the right angle), 22.5° (for 1/2 the field of view), and the 3rd angle must be 180 - (90 + 22.5) = 67.5°. So applying the law of sines:

```
sine(67.5°)   sine(22.5°)
---------- = -----------
    z         0.5*height

```

or:

```
z = 0.5 * height * sine(67.5°)/sine(22.5°)

```

And if you change your field of view, you simply need to change 22.5° to half your field of view, and 67.5° to \[180 - (90 + 0.5\*field\_of\_view)\].
> 2 votes

---
Tags: opengl, c++, camera, glm, projection-matrix
---


# Question
Title: Why are games locked at a certain frame per second?
A lot of PC games are locked at 60 frames per second. I know that this is because a high frame rate can cause glitches/bug in a game and mess up the physics but is there another reason? Should anyone who makes games lock their games at 30-120fps? Thanks in advance!

# Answer
The reasons the games are commonly "locked" at 60fps is that displays can't render faster than that. Further more, to make sure the rendered frames get to the screen with minimal delay and to prevent tearing (only a portion of the screen getting updated which looks flickery and bad), a frame will be rendered and will wait for the monitor to finish it's redraw cycle before going to the display. This is called "vsync" and normally happens 60 times a second unsurprisingly! You can actually turn it off if you want to, but it usually just makes the game look worse. Check out this Wikipedia page for more info: http://en.m.wikipedia.org/wiki/Screen\_tearing#V-sync
> 0 votes

# Answer
Because you don't need more frames per second.

Most computer monitors I know have their refresh rate around 60 Hz. Going beyond that, you would not notice the difference.

More FPS for physics means a smoother simulation, but there is a point beyond which you don't gain much.

Also, having more frames to pack in each second means you have less time for your game logic each frame. Locking the frame rate means the programmers know how much time they have for each task during a frame.
> 1 votes

---
Tags: performance
---


title: How can a pygame image be colored?

text:
# Question
Title: How can a pygame image be colored?
How can I color a Pygame image surface? I either want to change every pixel that is color A into color B, or else change every pixel into color B. Either works, so long as transparent regions remain the same.

# Answer
What you're looking for are surfarrays. A simple tutorial on how to get started with them can be found here.

Essentially what a surfarray does is directly modify the pixel values of pygame surfaces, and can operate on each of the R, G, and B channels for every pixel "simultaneously," which I put in quotes because I just mean you can change all the pixels with just one line of code. Ordinarily, this would be a very slow operation, but surfarrays use numpy/numeric as their core, so the operation is quite fast. I should still note that in practice, I've found it not to be fast enough for some applications, such as operating on large images, but if you're only operating on small particle sprites, you should be fine.

I did a bit of toying around to make sure that this works as you need it. Below is a code example of what you're looking to do. Some credit goes to the poster who answered this question.

```
def color_surface(surface, red, green, blue):
    arr = pygame.surfarray.pixels3d(surface)
    arr[:,:,0] = red
    arr[:,:,1] = green
    arr[:,:,2] = blue

```

In that function, I use `pygame.surfarray.pixels3d` because it references the pixels into an array, rather than copy them, making it a faster operation. The tutorial I posted also uses an additional instruction, something like:

```
iarray = numpy.array(arr)

```

which I also left out because I've found this to be a startlingly slow call in practice. It might be necessary if you try to do more complicated things with the surface.

So, the last few steps are actually taking your original surface and coloring it the way you need:

```
origSurface = pygame.image.load('images/blue_circle.png')
origSurface.convert_alpha()

coloredSurface = origSurface.copy()
color_surface(coloredSurface, 120, 78, 240)

```

A couple of notes about this code: the call to `convert_alpha` on the surface seems to be unnecessary if the image already has per-pixel alphas defined. The StackOverflow question that I referenced details the two ways to ensure a surface has alphas which are unaffected by surfarray operations. Also, copying a surface may not necessarily preserve the alphas, but like the last point, I've found that it does when the alphas are already defined in the original image. Just a few things to watch out for.

This ended up rather long... One last note... If you're feeling adventurous, you can look into the gfxdraw libraries for pygame. The `pygame.gfxdraw.textured_polygon` function caught my attention. I know very little about how it works or it's performance though.

Hope this helps :)
> 5 votes

# Answer
ktodisco's solution is good but requires numpy to be installed. I wanted my game to require no extra dependencies beyond Python and PyGame, so I searched for another solution and was inspired by this answer to a related question.

This routine only requires a couple calls to fill() with blend flags:

```
def colorize(image, newColor):
    """
    Create a "colorized" copy of a surface (replaces RGB values with the given color, preserving the per-pixel alphas of
    original).
    :param image: Surface to create a colorized copy of
    :param newColor: RGB color to use (original alpha values are preserved)
    :return: New colorized Surface instance
    """
    image = image.copy()

    # zero out RGB values
    image.fill((0, 0, 0, 255), None, pygame.BLEND_RGBA_MULT)
    # add in new RGB values
    image.fill(newColor[0:3] + (0,), None, pygame.BLEND_RGBA_ADD)

    return image

```
> 2 votes

---
Tags: python, pygame
---


title: XNA C# Texture Atlases

text:
# Question
Title: XNA C# Texture Atlases
Fairly new to XNA and not an expert on C# either. So I was following a tutorial, specifically this one http://rbwhitaker.wikidot.com/texture-atlases-1, and there is a bit of code I am unfamiliar with.

```
public void Draw(SpriteBatch spriteBatch, Vector2 location)
{
    int width = Texture.Width / Columns;
    int height = Texture.Height / Rows;
    int row = (int)((float)currentFrame / (float)Columns);
    int column = currentFrame % Columns;

```

Mostly all of this I am familiar with. However, the line that says

```
int row = (int)((float) currentFrame / (float) Columns);

```

This line is not familiar to me and I would appreciate if someone could explain what this does. Clearly it is designed to find out what row the program is on in the texture atlas but what how does it do that with that code? What is it calculating?

# Answer
> 2 votes
As the variable name suggests, its finding the row where the image for "currentFrame".

```
int row = (int)((float)currentFrame / (float)Columns);

```

If you have 4x4 images, so 4 in row and 4 in columns. Then you are animating your image and going through frames. Well, frame 1 is easy to find, since it's the first, so row = 0 and column = 0. But if you are in frame 11, it gets harder. If you need to support different sizes, ie. some animations have 6 frames and some have 9 frames and you are using structure like in the tutorial, then you have to calculate the row. You could of course place images side by side to overcome this.

It's casted to int, because the actual row is pure integer, not floating point ( so not row 1,2424342, but 1), right now i don't understand why there is float casting going on.

Essentially that line is just dividing the current frame with columns and doing some casting at the same time.

Example:

```
int row = 11 / 4; // row = 2
int column = 11 % 4 // column = 3

```

So, now we have the position of the image from the atlas. All we have to do now, is to multiply row and column with tile w & h to find the pixel perfect location of the current frame from the atlas.

---
Tags: xna, c#, software-engineering
---


title: Finding flexible patterns in a 2D grid

text:
# Question
Title: Finding flexible patterns in a 2D grid
I'm stumped trying to create a matching algorithm for my game.

I have a 2D grid like this for example:

0, 0, 0, 0, 0, 0

0, 1, 2, 2, 1, 0

0, 1, 1, 0, 0, 0

0, 0, 2, 0, 1, 0

0, 0, 0, 2, 1, 0

0, 0, 0, 0, 0, 0

Along with a list of patterns:

1, 2, 1

1, 1, 1

Where I am trying to find instances of the patterns in the grid, and the higher listed pattern has the higher priority if multiple patterns are found. That would normally not be a problem if I were searching for them appearing purely horizontally or vertically. But I want to implement the search for them appearing in more than just straight lines like this (an "L shaped" example for the first pattern):

1, 2

0, 1

Some implementations I've tried included picking a grid element and trying to crawl from it to neighboring elements, but this has been problematic since each element has 4 neighbors and when you go to a neighboring element it has 4 more possible neighbors, and sometimes the crawling path curls in on itself resulting in duplicates. I feel like there is an easier and more efficient way to implement this that I am missing.

Is there any already well known algorithm that would fit this criteria? I have not been able to find something that fits these criteria on google. Any help would be appreciated.

# Answer
A naive algorithm to find one pattern in a grid would be this:

```
for (int grid_x = 0; grid_x < grid_width; grid_x++) {
    for (int grid_y = 0; grid_y < grid_height; grid_y++) {
         bool fail = false;
         for (pattern_x = 0; pattern_x < pattern_width && fail == false; pattern_x++) {
             for (pattern_y = 0; pattern_y < pattern_height && fail == false; pattern_y++) {
                  if (grid[grid_x + pattern_x][grid_y + pattern_y] != pattern[pattern_x][pattern_y]) {
                      fail = true;
                  }
             }
         }
         if (fail == false) {
              // found pattern
         }
    }
}

```

There is certainly some optimization potential in this algorithm which someone will surely point out in the comments, but it should be fast enough to get you started.

When you execute this algorithm for multiple patterns in a row and do not want to get a positive when cells are already part of a pattern which was checked before, perform the algorithm with a copy of the grid and when you find a pattern, overwrite those cells which are part of the pattern with a value which does not occur in any pattern.
> 2 votes

---
Tags: c#, grid, search, patterns
---


title: XNA - debugging

text:
# Question
Title: XNA - debugging
I know how to debug step by step in XNA however when I do that the screen is gray and the console does not give out any output. This is a problem because it greatly limits my ability to find problems. Is there anyway around this?

# Answer
> 1 votes
Ideally, what you want to do is set a breakpoint in visual studio, run your game as normal, and then start stepping through when you reach the breakpoint. You can then hit "continue" when you want the game to run again. There is no way to simultaneously step through step by step and *also* have the game running as normal.

Another option is to print out debugging information to a log file, and read the file later (for instance, when you want to collect broad statistics about what's going on in the game) -- or drawing debugging information onscreen.

# Answer
> 0 votes
Running game "normally" is not possible, while stepping in debugger. However, game should continue normally, when you press continue, if it does not, then you have a bug.

You can output text to visual studio output window using

```
System.Diagnostics.Debug.WriteLine("It's me, Bugxor!");

```

If your output window is not open, you can open it from top menu "VIEW-\>Output" or keyboard shortcut "CTRL+W,O"

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


# Question
Title: Is spatial partitioning for collision detection an appropriate way for objects to "know" whats around them even if they are not colliding?
I've been puzzling over how to do spatial awareness for units and buildings. I've asked a few questions and the final conclusion was spatial partitioning in the same manner used for collision detection. So an object knows if something is close to it and can react appropriately (such as attacking an enemy)

I'm making sure this is what I expect it is, so that my monetary and time investment in reading materials is not a waste for the purpose of completing this game.

# Answer
> 2 votes
It sounds like you're making an RTS, so let's say you need to have a building that automatically attacks the nearest enemy within 100 metres.

---

A naive (and inefficient) approach would be to calculate the distance to every enemy unit, find the minimum, and ensure that it's within 100 m. Then you have your target. However, this means that for every N buildings and M enemies, you have to do N\*M distance tests.

One optimization you can make is to use a distance squared check to eliminate the relatively expensive square root operation. So instead of checking the distance against 100 m, you check distance^2 against 10,000 m^2. This will save a bit of time but you're still working with an O(N\*M) complexity.

Here is where spatial partitioning comes in. Now, you can do a broad test to first find which partitions may potentially intersect with the building's range, and narrow down the list of candidates for enemies to attack significantly. Applying both of these optimizations should give you a significant average-case cost reduction.

---

This is the exact same thing that you would do in a generic collision detection algorithm - narrowing down the list of candidates through a gauntlet of cheap (and usually parallel) early-out tests. Indeed, you could implement the building's broad phase query as a collision test against the circle/sphere that bounds its range, which might be useful if you're using a 3rd-party collision/physics library.

---
Tags: space-partitioning
---


# Question
Title: In Eclipse using libgdx, what does "project description file is missing" mean?
In a sudden case of nostalgia, I switched my eclipse workplace from my working libgdx projects to an older one. After looking through my old stuff I had some problems switching it back, since I didn't import it right. After I got that working, I cant run my libgdx desktop projects anymore. It says it couldn't load the Spritesheet anymore: After googling a little, I was told to make sure the Android asset folder is linked to the desktop project, which it is.

I then noticed that one of the project folders is closed (I've got Project-android,Project-core,Project-desktop and just Project) The folder project was closed and when trying to open it, it gave me the following error:

> The project description file (.project) for 'Projekt Stella' is missing. This file contains important information about the project. The project will not function properly until this file is restored.

The thing is I made sure that this file is still in the folder which it is... so now I have no idea how to get this working. Any ideas?

Edit: The project works fine in Android studio. Its just not working in Eclipse.

# Answer
The best solution is to re-create project with libGDX setup tool and copy all source code and assets into it from old project. .project file is file that contains information about project Eclipse should know. Do you use Gradle? If so, do you import project into Eclipse as Gradle Project (right) or as Eclipse Project (wrong)? And it's pretty bad idea to use Android Studio and Eclipse simultaneously. Both generate own special files that no one except IDE needs.
> 1 votes

---
Tags: java, libgdx, eclipse
---


title: Client-server architecture with box2d

text:
# Question
Title: Client-server architecture with box2d
I am running a client-server architecture with an authoritative server running box2d and the client running box2d as well.

If gravity is set to 0, is there any point to linear interpolation and creating the 100ms buffer to smooth client positioning if the forces and impulses of world objects are sent out with each snapshot (say 5 times a second)?

The client would be smoothly simulating with the server and remove the need for interpolation, right?

# Answer
The client and the server will go out of sync eventually, so you'll have a smoother game if you interpolate instead of simulating with the server and then correcting, but this will induce extra lag.

You cannot answer this definitely, it's up to you to decide which suits your application better. Also your questions seems a bit lacking in terms of describing what is actually happening in your game/application.
> 1 votes

---
Tags: box2d, networking, client-server
---


# Question
Title: Opengl textures change color of everything
Whenever I render textures, all shapes get the color of the texture. I'm not sure why, but I think it's something to do with the way I render textures. Here's what I use to draw textures:

```
public void drawTex(Texture t, int x, int y, int width, int height)
    {
        t.bind();
        glBegin(GL_QUADS);
        glTexCoord2f(0,0);
        glVertex2f(x,y);
        glTexCoord2f(1,0);
        glVertex2f(x+t.getTextureWidth(),y);
        glTexCoord2f(1,1);
        glVertex2f(x+t.getTextureWidth(),y+t.getTextureHeight());
        glTexCoord2f(0,1);
        glVertex2f(x,y+t.getTextureHeight());
        glEnd();
    }

```

Now I draw shapes like this:

```
public void drawQuad(int x, int y, int width, int height, float r, float g, float b)
    {

        glBegin(GL_QUADS);
    //  glColor3f (r, g, b);
        glVertex2f(x, y);
        glVertex2f(x + width, y);
        glVertex2f(x + width, y + height);
        glVertex2f(x, y + height);
        glEnd();
    }

```

# Answer
> 0 votes
You need to unbind your texture object after using it for drawing certain shape.

```
// In Texture class add
void unbind()
{
 glBindTexture(0);
}

public void drawTex(Texture t, int x, int y, int width, int height)
{
        t.bind();
        glBegin(GL_QUADS);
        glTexCoord2f(0,0);
        glVertex2f(x,y);
        glTexCoord2f(1,0);
        glVertex2f(x+t.getTextureWidth(),y);
        glTexCoord2f(1,1);
        glVertex2f(x+t.getTextureWidth(),y+t.getTextureHeight());
        glTexCoord2f(0,1);
        glVertex2f(x,y+t.getTextureHeight());
        glEnd();
        t.unbind();
}

```

Though, this raise the question of how leaky OpenGL states could be used with OOP languages. Is it appropriate to call OpenGL functions that can affect the global state in class objects.. One way to handle this is to restrict OpenGL calls in certain(one?) places, for example `OpenGLRenderer` class.

---
Tags: opengl, java, lwjgl
---


# Question
Title: How do I draw a full screen quad in DirectX 11?
How do I draw a full screen quad that shows red on the screen?

# Answer
> 3 votes
First, set the primitive topology to TRIANGLESTRIP (ID3D11DeviceContext::IASetPrimitiveTopology), set the following shaders then call devicecontext-\>Draw(4,0). You don't even need vertex buffers for this because of the automatic system value of vertex id in the shader.

```
float4 VertexShader(uint vI : SV_VERTEXID):SV_POSITION
{
    float2 texcoord = float2(vI&1,vI>>1); //you can use these for texture coordinates later
    return float4((texcoord.x-0.5f)*2,-(texcoord.y-0.5f)*2,0,1);
}

float4 PixelShader(float4 pos : SV_POSITION):SV_TARGET
{
    return float4(1,0,0,1); //the red color
}

```

---
Tags: directx11
---


# Question
Title: Unity sprite with higher sorting layer not firing its OnMouseDown function
I have 2 objects, both have a Box collider 2D.

The first object is on the `Level1` Sorting Layer and has a `Tile script` attached to it.

The second object is on the `Level0` Sorting Layer and doesn't have any scripts.

The `Tile script` code is as follows:

```
void OnMouseDown()
{
    Debug.Log(Input.mousePosition.ToString());
}

```

Whenever I click the top tile, nothing prints in the console unless I click on the red area like I show in the image below (red area = \[first box collider\] minus \[the two box colliders intersection area\]).

Why this happens ? Why doesn't the `OnMouseDown()` function fire up simply when you click on its collider, since the top tile is on a higher sorting layer than the bottom tile. How does this work ? Doesn't sorting layer affect the 2D box collider ? (If I change the Z-axis of the top tile to -1, while keeping the bottom tile to 0, it works as expected.)

# Answer
If you have stacked BoxCollider2Ds like that, Unity will only capture the mouse click on the topmost one.

You could:

* Adjust the z-layer of your colliders (I think you do this by setting the renderer's "Order in Layer").
* Enable/Disable your colliders in code based on which one is on top.
* Do a RaycastAll, and process the click yourself.
> 3 votes

---
Tags: c#, unity, collision-detection
---


# Question
Title: How to stop 3D model from reflecting light like plastic
I was browsing SketchFab and found a 3D model I decided to try in Unity.

This is how the model looks in SketchFab's viewer:

When I put it in Unity, I used a Directional Light object:

As you can see, it looks like plastic. I have been playing with the light's intensity, but the model seems to always reflect light as if it were some sort of plastic (unlike SketchFab's viewer).

How can I make it look like the above image?

The model is https://sketchfab.com/models/1ee9b44352c840bda4202895948c30bb

# Answer
Specular highlights are controlled by the *Shader* of the *Material* assigned to the *MeshRenderer* component of an object.

The standard shader in Unity 5 has a slider for "Metallic" and "Smoothness". When you turn up the smoothness, your object will have a less glossy look. You could also try experimenting with the other shaders Unity has to offer.
> 1 votes

# Answer
This is entirely an issue of shader configuration.

Without completely reiterating the workflow in the Unity manual, you'll probably want to apply the new Standard Shader and then, using the material charts, and adjust the material's parameters accordingly.
> 0 votes

---
Tags: unity, 3d
---