# Question
Title: How are deterministic games possible in the face of floating-point non-determinism?
To make a game like an RTS networked, I've seen a number of answers here suggest to make the game completely deterministic; then you only have to transfer the users' actions to each other, and lag what's displayed a little bit in order to "lock in" everyone's input before the next frame is rendered. Then things like unit's positions, health, etc. don't need to be constantly updated over the network, because every player's simulation will be exactly the same. I've also heard the same thing suggested for making replays.

However, since floating-point calculations are non-deterministic between machines, or even between different compilations of the same program on the same machine, is this really possible to do? How do we prevent that fact from causing small differences between players (or replays) that ripple throughout the game?

I've heard some people suggest avoiding floating-point numbers altogether and using `int` to represent the quotient of a fraction, but that doesn't sound practical to me - what if I need to, for example, take the cosine of an angle? Do I seriously need to rewrite an entire math library?

Note that I am mainly interested in C#, which as far as I can tell, has exactly the same problems as C++ in this regard.

# Answer
> 17 votes
## Are floating-points deterministic?

I did a lot of reading on this issue a few years back when I wanted to write an RTS using the same lockstep architecture you do.

My conclusions about hardware floating-points were:

* The same native assembly code is most likely deterministic provided you're careful with floating point flags and compiler settings.
* There was one open source RTS project that claimed they got deterministic C/C++ compiles across different compilers using a wrapper library. I didn't verify that claim. (If I recall correctly it was about the `STREFLOP` library)
* The .net JIT is allowed quite a bit of leeway. In particular it is allowed to use higher accuracy than requires. Also it uses different instruction sets on x86 and AMD64 (I think on x86 it uses the x87, AMD64 it uses some SSE instructions whose behavior differs for denorms).
* Complex instructions (including trigonometric function, exponentials, logarithms) are especially problematic.

I concluded that it's impossible to use the built in floating point types in .net deterministically.

## Possible Workarounds

Thus I needed workarounds. I considered:

1. Implement `FixedPoint32` in C#. While this is not too hard(I have a half finished implementation) the very small range of values makes it annoying to use. You have to be careful at all times so you neither overflow, nor lose too much precision. In the end I found this not easier than using integers directly.
2. Implement `FixedPoint64` in C#. I found this rather hard to do. For some operations intermediate integers of 128bit would be useful. But .net doesn't offer such a type.
3. Use native code for the math operations which is deterministic on one platform. Incurs the overhead of a delegate call on every math operation. Loses ability to run cross platform.
4. Use `Decimal`. But it's slow, takes a lot of memory and easily throws exceptions (division by 0, overflows). It's very nice for financial use, but no good fit for games.
5. Implement a custom 32 bit floating-point. Sounded rather difficult at first. The lack of a BitScanReverse intrinsic causes a few annoyances when implementing this.

## My SoftFloat

Inspired by your post on StackOverflow, I've just started implementing a 32 bit floating-point type in software and the results are promising.

* The memory representation is binary compatible with IEEE floats, so I can reinterpret cast when outputting them to graphics code.
* It supports SubNorms, infinities and NaNs.
* The exact results are not identical to the IEEE results, but that usually doesn't matter for games. In this kind of code it only matters that the result is the same for all users, not that it's accurate to the last digit.
* Performance is decent. A trivial test showed that it can do about 75MFLOPS compared 220-260MFLOPS with `float` for addition/multiplication(Single thread on a 2.66GHz i3). If anybody has good floating point benchmarks for .net please send them to me, since my current test is very rudimentary.
* Rounding can be improved. Currently it truncates, which roughly corresponds to rounding towards zero.
* It's still very incomplete. Currently division, casts and complex math operations are missing.

If anybody want to contribute tests or improve the code, just contact me, or issue a pull request on github. https://github.com/CodesInChaos/SoftFloat

## Other sources of indeterminism

There are also other sources of indeterminism in .net.

* iterating over a `Dictionary<TKey,TValue>` or `HashSet<T>` returns the elements in an undefined order.
* `object.GetHashCode()` differs from run to run.
* The implementation of the built in `Random` class is unspecified, use your own.
* Multithreading with naive locking leads to reordering and differing results. Be very careful to use threads correctly.
* When `WeakReference`s lose their target is indeterministic because the GC may run at any time.

# Answer
> 26 votes
The answer to this question is from the link you posted. Specifically you should read the quote from Gas Powered Games:

> I work at Gas Powered Games and i can tell you first hand that floating point math is deterministic. You just need the same instruction set and compiler and of course the user’s processor adheres to the IEEE754 standard, which includes all of our PC and 360 customers. The engine that runs DemiGod, Supreme Commander 1 and 2 rely upon the IEEE754 standard. Not to mention probably all other RTS peer to peer games in the market.

And then below that one is this:

> If you store replays as controller inputs, they cannot be played back on machines with different CPU architectures, compilers, or optimization settings. In MotoGP, this meant we could not share saved replays between Xbox and PC.

**A deterministic game will only be deterministic when using the identically compiled files and run on systems that adhere to the IEEE standards. Cross platform synchronized network simulations or replays will not possible.**

# Answer
> 10 votes
I've worked on a number of large titles.

Short answer: It's possible if you're insanely rigorous, but probably not worth it. Unless you're on a fixed architecture (read: console) it's finicky, brittle and comes with a host of secondary problems such as late join.

If you read some of the articles mentioned, you'll note that while you can set the CPU mode there are bizarre cases such as when a print driver switches the CPU mode because it was in the same address space. I had a case where an application was frame-locked to an external device, but a faulty component was causing the CPU to throttle due to heat and report differently in the morning and afternoon, making it in effect a different machine after lunch.

***These platform differences are in the silicon, not the software, so to answer your question C# is affected too.*** Instructions such as fused multiply-add (FMA) vs ADD+MUL change the result because it rounds internally only once instead of twice. C gives you more control to force the CPU to do what you want basically by excluding operations like FMA to make things "standard"--but at the cost of speed. The intrinsics seem to be the most prone to differ. On one project I had to dig out a 150 year old book of acos tables to get values for comparison to determine which CPU was "right". Many CPUs use polynomial approximations for trig functions but not always with the same coefficients.

My recommendation:

Regardless of whether you go integer lock-step or sync, handle the core game mechanics separately from presentation. Make the game play accurate, but don't worry about accuracy in the presentation layer. Also remember you don't need to send all the networked world data at the same frame-rate. You can prioritize your messages. If your simulation is 99.999% matched you won't need to transmit as often to to stay paired. (Cheat prevention aside.)

There's a nice article about Source engine that explains one way to go about sync: Source Multiplayer Networking.

Remember, if you're interested in late join, you're going to have to bite the bullet and sync anyway.

# Answer
> 4 votes
Edit: A link to a fixed point class (Buyer beware! - I haven't used it...)

You could always fall back on fixed point arithmetic. Someone (making an rts, no less) has already done the leg work on stackoverflow.

You will pay a performance penalty, but this may or may not be a problem, as .net will not be especially performant here as it won't use simd instructions. Benchmark!

N.B. Apparently someone at intel appears to have a solution to allow you to use the intel performance primitives library from c#. This may help vectorising fixed point code to compensate for the slower performance.

# Answer
> 4 votes
Use fixed point arithmetics. Or choose an authoritative server and have it sync game state once in a while - that's what MMORTS do. (At least, Elements of War works like this. It's written in C# too.) This way, errors do not have a chance to accumulate.

# Answer
> 1 votes
> Note that I am mainly interested in C#, which as far as I can tell, has exactly the same problems as C++ in this regard.

Yes, C# has the same problems as C++. But it also has a lot more.

For example, take this statement from Shawn Hawgraves:

> If you store replays as controller inputs, they cannot be played back on machines with different CPU architectures, compilers, or optimization settings.

It's "easy enough" to ensure that this happens in C++. In **C#**, however, that's going to be a lot harder to deal with. This is thanks to JIT.

What do you suppose would happen if the interpreter ran your code interpreted once, but then JIT'd it the second time? Or maybe it interprets it twice on someone else's machine, but JIT's it after that?

JIT is not deterministic, because you have very little control over it. This is one of the things you give up to use the CLR.

And God help you if one person is using .NET 4.0 to run your game, while someone else is using the Mono CLR (using the .NET libraries of course). Even .NET 4.0 vs. .NET 5.0 could be different. You simply need more control over the low-level details of a platform to *guarantee* this kind of thing.

You ought to be able to get away with fixed-point math. But that's about it.

# Answer
> 1 votes
I realized after writing this answer that it doesn't actually answer the question, which was specifically about floating-point nondeterminism. But maybe this is helpful to him anyway if he's going to make a networked game in this manner.

Along with the input sharing that you're broadcasting to all players, it can be very useful to create and broadcast a checksum of important game state, such as player positions, health, etc. When processing input, assert that the game state checksums for all remote players are in sync. You are guaranteed to have out of sync (OOS) bugs to fix and this will make it easier - you will have an earlier notice that something's gone wrong (which will help you figure out reproduction steps), and you should be able to add more game state logging in suspect code to allow you to bracket whatever is causing the OOS.

# Answer
> 0 votes
I think the idea from the blog linked to still needs periodic synchronisation to be viable - I've seen enough bugs in networked RTS games which don't take that approach.

Networks are lossy, slow, have latency and might even pollute your data. "Floating point determinism", (which sounds buzzwordy enough to make me skeptical) is the least of your worries in reality... esp if you use a fixed time step. with variable time steps you will need to interpolate between fixed time steps to avoid determinism problems too. I think this is usually what is meant by non-deterministic "floating point" behaviour - just that variable time steps cause integrations to diverge - not anything to do with math libraries or low level functions.

Synchronisation is key though.

# Answer
> -2 votes
You make them deterministic. For a great example, see Dungeon Siege GDC Presentation as to how they made the locations in the world networkable.

Also remember that determinism applies to 'random' events as well!

---
Tags: c++, c#, networking, replays, floating-point
---


# Question
Title: How do I clip an image in OpenGL ES on Android?
My game involves "wiping off" an image by touch:

After moving a finger over it, it looks like this:

At the moment, I'm implementing it with `Canvas`, like this:

```
9Paint pTouch;
9int X = 100;
9int Y = 100;
9Bitmap overlay;
9Canvas c2;
9Rect dest;

    pTouch = new Paint(Paint.ANTI_ALIAS_FLAG);
    pTouch.setXfermode(new PorterDuffXfermode(Mode.SRC_OUT));
    pTouch.setColor(Color.TRANSPARENT);
    pTouch.setMaskFilter(new BlurMaskFilter(15, Blur.NORMAL));

    overlay = BitmapFactory.decodeResource(getResources(),R.drawable.wraith_spell).copy(Config.ARGB_8888, true);

    c2 = new Canvas(overlay);

    dest = new Rect(0, 0, getWidth(), getHeight());
    Paint paint = new Paint();9
    paint.setFilterBitmap(true);

    ...

    @Override
    protected void onDraw(Canvas canvas) {
        ...

        c2.drawCircle(X, Y, 80, pTouch);
        canvas.drawBitmap(overlay, 0, 0, null);

        ...
    }

    @Override
9public boolean onTouchEvent(MotionEvent event) {

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE: {
                X = (int) event.getX();
                Y = (int) event.getY();9
                invalidate();
                c2.drawCircle(X, Y, 80, pTouch);9
                break;
            }
        }
return true;
...

```

What I'm essentially doing is drawing transparency onto the canvas, over the red ball image.

`Canvas` and `Bitmap` feel old... Surely there is a way to do something similar with OpenGL ES. What is it called? How do I use it?

**\[EDIT\]**

I found that if I draw an image and above new image with alpha 0, it goes to be transparent, maybe that direction?

Something like:

```
gl.glColor4f(0.0f, 0.0f, 0.0f, 0.01f);

```

# Answer
> 1 votes
OK, that's waaaaay too much to ask in such a brief QA format, but here's a super-condensed answer:

* Create a GLSurfaceView

see platform documentation: http://developer.android.com/training/graphics/opengl/environment.html#glsurfaceview

* Create an orthogonal camera that runs from 0,0 to 1,1 (see docs again)
* Load your foreground image (the one you want to erase) into a texture (see docs again)
* Load your background image into a texture
* Create a single-channel off-screen texture with glBindTexture backed by a ByteBuffer. Set the format to alpha.
* In the touch event of the GLSurfaceView, transform the touch coordinates from screen space to the dimensions of your alpha texture. Change the color in the byte array in the byte buffer, then refresh the contents of the alpha texture with the byte buffer data. While you can do this by off-screen render-to-texture, if all you are doing is drawing circles I'd just slam the bytes into the array as scan-lines at least until you have more experience with GL. e.g. System.arraycopy
* Turn OFF z-buffering and ON alpha blending in your render states.
* Render 2 full-screen quads to your surface view: your background, then your foreground with your foreground texture bound in the diffuse channel (texture unit 1) and the off-screen alpha texture bound in the alpha channel (texture unit 2). (see docs for GLSL shader, change from rgb to rgba on fragment shader)

---

Alternative: You can use the stencil buffer instead of the alpha channel. It is designed for masking, but either will get the job done.

If you want anti-aliased edges, stick with alpha. Since you're new to OpenGL, you are more likely to find simple examples with alpha. Stencil examples are likely to get into shadow mapping and slightly more advanced topics.

Unfortunately, OpenGL does have a learning curve and what you're asking for is a lot more than a simple answer. There's no component that "just does" what you are asking although you may find a wrapper to do so.

I hope that helps!

# Answer
> 0 votes
There are many ways to go about doing this I suppose in openGL.

* First, you could make a sprite sheet of every step of the covering of the ball and by using

glTranslatef();

on the

```
GL10.GL_TEXTURE

```
* Second, and probably better you could make a second black ball texture that moves over it with the persons figure in your Render loop.

glBlendFunc(GL10.GL\_ONE, GL10.GL\_ONE\_MINUS\_SRC\_ALPHA);
* You could use geometry to do it.
* You can also do it in canvas like this with the same idea as number 2:

http://www.javacodegeeks.com/2011/07/android-game-development-moving-images.html

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


# Question
Title: Resolving penentration after collision using Separating Axis Thereom
I implemented collision detection in my game using SAT. The detection works, but I'm trying to use the algorithm to figure out the penetration vector of the two OBBs and push them apart (before doing the 'actual' collision handling).

I think I got the penetration vector successfully. However I'm not sure which of the two entities in the collision to apply it on (i.e. add to the position of which entity).

If I apply it on both entities, obviously nothing happens. How can I know to the position which entity I need to add the penetration vector so the entities 'touch' at the exact point of collision?

# Answer
> 2 votes
## Common, easy but ultimately wrong answer

Iterate along the vector in very small increments. Eventually they'll de-penetrate at a "reasonable" position, assuming you continue any additional constraints at each iteration. It's brute force, and for something simple, it's good enough. You will almost certainly need to add artificial max/min force limiters to your collision handler if you take this approach. If you don't like limiters, a high dampener, drag or friction value will hide any numerical issues. If you're making a phone game or doing a weekend jam, this will do the trick. *See: Better Answer.*

## Better answer

Wind back time using the last known position and your SAT penetration vector to find the correct time delta between frames of the collision. Don't artificially de-penetrate, re-calculate the physics from the time step at which the collision occurred.

When you de-penetrate then process collisions, you're effectively violating conservation of energy. You've taken an inelastic collision and turned it into an simple elastic collision without doing anything with the forces involved. You've either not absorbed them in the inelastic "crunch" that should have happened or if you're using a fixed coefficient of restitution you may over-compensate. Many physics engines don't handle that well. Depending on what kind of iterator you're using in your physics engine, you can run into numerical problems as well. Verlet iterators are pretty tolerant to that kind of thing because they're inherently positional, but others are not. If the extra error from force-moving objects accumulates your physics can become unstable over time.

---
Tags: 2d, collision-detection, mathematics, separating-axis-theorem
---


title: Continuous world and camera problem

text:
# Question
Title: Continuous world and camera problem
I have this problem where I split my big world into chunks and I don't know how to draw it into my game camera's view. Each world chunk has its own coordinate system, so when object reaches border of one chunk and steps into another - coordinate system resets to zero. For example from world\_x = 1440 into world\_x = 0.

To draw only those objects that are in the camera's view, I use code:

```
int screenX, screenY; //screen position of the object being drawn

screenX = object.x-camera.x;
screenY = object.y-camera.y;

```

The problem appears when camera sees two different chunks. Lets say camera's coordinates are:

```
screenX = 567
screenY = 0

```

My drawable object is at

```
world_x = 1266
world_y = 0

```

In this case object's screen coordinates are (x)699, because screenX = object.x-camera.x. But what if camera stays in the same place and object finally reaches different chunk. Object's coordinates are reset to zero. That means that its screen coordinates becomes (x)-567.

That screen coordinates conversion would work if I would be doing non partitioned game world, but now it don't. Any ideas?

# Answer
> 3 votes
Invert your thinking. Don't convert objects to camera space, convert the camera to object space.

* Start by clearing the output buffer including the stencil buffer.
* Sort the chunks in painterly order from back to front. Subdivide per usual transparency-drawing rules if needed.
* For each chunk:

+ Clear the z-buffer and set the stencil buffer to mask anything already stenciled.
    + Create a camera transformation matrix that positions the camera relative to the chunk. Keep your projection the same, but ideally move the front and back planes of the z-buffer to be max and minimum values of the nearest and farthest edge of the chunk along the camera look vector. This gives you the most z-buffer resolution.
    + Draw all the visible objects in that chunk and *only* in that chunk.
    + Draw the chunk to the stencil buffer.
* Continue until all the chunks have been rendered.

Do your transforms ***once per chunk,*** not once per object. This is the most efficient way and it preserves your numeric precision. Done correctly, it will also prevent polygon flimmering.

If you try to render a very large world with absolute coordinates in floating point, a number of bad things will happen... besides being difficult to get your head around. As you run out of numeric precision you will start to get object "drift". The further you get from the origin the distance between two objects that are X units apart will appear larger even though they are the same. This is because the last digits are being truncated. *-You're trading precision for range, it's not really a larger number!-*

You also risk exceeding the precision of the z-buffer. What will happen is that the polygons will "fight" for z-order and will appear to sparkle. By tight-fitting the z-buffer as much as possible, the objects will sort better and the whole scene will look nicer when rendered.

# Answer
> 0 votes
I would say to make each chunk continuous. Don't reset the world co-ords. As the old chunk scrolls off (into fog etc) write it to file or store to memory. New chunks scrolling in would do so only under fog (way at screen edge). Let your x,y, z go to 2000000000 both ways that's more than large enough for anyone.

---
Tags: camera
---


title: Prevent GUI Clickthrough

text:
# Question
Title: Prevent GUI Clickthrough
I'm using `NGUI` to setup my UI in Unity.

Attached to the `MainCamera` I do have a script to rotate the camera view by clicking and dragging.

It does handle mouse events using `Input.GetMouseButton()`.

The problem is that if I click and drag when the mouse is over a NGUI element (Button, Panel, Slider, whatever), NGUI handles all the mouse events correctly, but they also go through the `MainCamera`, and the camera rotate.

I want to prevent that.

If I use for example the Unity `GUI.Button()`, the mouse events are not transfered to the `MainCamera` and the camera does not rotate.

I have to replicate that, but using NGUI.

I have searched on their support forum, but i couldn't find a solution.

# Answer
You can implement your own version of the below. Create a static bool in whatever GUI class you have available to all your scripts. Now, whenever you start a click operation with NGUI, you can set that bool to true. Then simply check to see if the bool is true before doing operations in other scripts. Ideally, if you have access to the NGUI source, this is a change you'd want to implement there, so it's all in one spot.

Remember to set it to false at the beginning of each frame.

---

Below works for Unity GUI:

Anywhere you want to respond to input that's shared with the GUI, you can use the test the hot control.

Hot control identifies the controlID of the GUI utility that's currently active. When it's set to zero, that means that no GUI control is active. So for example, in your camera control script you could do a test like this:

```
Update() {
    if (GUIUtility.hotControl == 0) {
        //Update camera
    }
}

```
> 2 votes

# Answer
1. Make sure all NGUI components' layers are the same, like "UI".
2. Attach your UI's NGUI panel with box collider.
3. Add a script "InputManager.cs" and rewrite function GetMouseButton() like:

```
public static bool GetMouseButton(int button)
{
    if (UICamera.hoveredObject == null) {
        return Input.GetMouseButton(button);
    } else {
        // If click/drop on 2D UICamera, do not send the event to MainCamera.
        // 5 represents layer "UI"
        if (UICamera.hoveredObject.layer == 5) {
            return false;
        }
    }

    return false;
}

```
4. As the code above, use UICamera.hoveredObject.layer to check whether mouse is on NGUI UI layer, if on UI, GetMouseButton() will return false and MainCamera will not be affected.
5. Make sure you add box collider to UI in step 2, otherwise UICamera.hoveredObject will be null.
6. The layer number may be any number you like, not always 5.
> 1 votes

---
Tags: unity, gui, ngui
---


# Question
Title: Initial force to achieve orbital velocity
I'm attempting to get asteroid to orbit a black hole that is asserting gravity. Some parts currently work, like the black hole asserting gravity, attracting asteroids in and destroying them. And sometimes the asteroids, or smaller chunks end up in orbit around the black hole. But my desire is to have them orbiting at random distances at the start of the game.

**Gravity**

First please note, I am certain the math behind a lot of this is off, I'm hacking a concept at the moment and once enough pieces are in place I intent to come back through and apply proper scale and units to everything. Next, it's written in JS but concepts *should* be fairly universal.

```
  function attractBodyToBlackHole(body) {
    var sx = body.position[0];
    var sy = body.position[1];
    var bx = blackHoleBody.position[0];
    var by = blackHoleBody.position[1];

    var angleToBody = Math.atan2(sx - bx, sy - by);
    var distanceToBody = Math.sqrt(Math.pow(sx - bx, 2) + Math.pow(sy - by, 2));

    var magGrav = 0.8 - (distanceToBody / 14);
    if(magGrav < 0) {
      magGrav = 0;
    }

    body.force[1] -= magGrav*Math.cos(angleToBody);
    body.force[0] -= magGrav*Math.sin(angleToBody);
  }

```

This function is applied to each object on p2's step, attracting it closer to the black hole.

**Asteroids**

```
function addAsteroid() {
  var bx = blackHoleBody.position[0];
  var by = blackHoleBody.position[1];

  var a = Math.random() * (Math.PI * 2);
  var dist = 3 + (Math.random() * 3);
  var x = dist * Math.cos(a);
  var y = dist * Math.sin(a);

  var vx = ?;
  var vy = ?;

  var asteroidBody = new p2.Body({
    mass:10,
    position:[x,y],
    velocity: [ vx, vy ]
  });
}

```

So my question is, how can I calculate velocity x/y (or force x/y ideally) to get these objects, based on their position, distance and the force of attraction from the black hole?

# Answer
I know this is gamedev not game playing, but the Kerbal Space Program wiki has all the math and then some. More importantly, it explains it quite nicely in "plain English" if you drill down.

Here's the basic mathematics of how to get something into orbit: http://wiki.kerbalspaceprogram.com/wiki/Tutorial:\_Basic\_Orbiting\_(Math)

I apologize for not copying the whole thing but it's quite long.

**Strong starting points:**

The relation between orbital speed and acceleration:

The distance between the craft and the body:

Note that there are quite a few different types of orbits and ways to get into orbit.

Newton's cannonball explains basic orbiting well:

http://en.wikipedia.org/wiki/Newton%27s\_cannonball
> 2 votes

---
Tags: javascript, html-canvas
---


# Question
Title: How to achieve best performance in DirectX 9.0 while rendering on multiple monitors?
I have read this article, and I am making use of some pixel shaders to achieve some effects. At most four shader effects can be applied at same time. What are the best practices to achieve best performance with DirectX 9.0.

I read somewhere that DirectX 11 provides support for parallel rendering, but I am not able to get any working sample for DirectX 11.0.

How can I boost the performance of my application? Are there any best practices for rendering different things on multiple monitors at the same time?

# Answer
I've run up to 7 off a single PC.

First and foremost on multi-monitor on DX9:

* Use exclusive mode and run each head as an independent device or you risk the two display adapters trying to lock vsync with each other. Basically, neither will flip the back buffer until BOTH displays have finished rendering. This slows things down considerably. If you run them as an independent device, you can avoid this problem without any fuss.
* Exception: if both heads are on the same card and you have *very* large textures. If your texture size will blow the cache, merge both heads onto a single device. This will allow you to share the texture memory between the two heads instead of halving it. But avoid this if you can.
* Prefer small textures to textures, textures to materials and geometry to alpha.
* Consolidate your shaders if you can as long as that doesn't lead to branching or more state changes. Basically, do anything you can to avoid state changes.
* I don't know if it's peculiar to DX9 or the engine I was using, but switching mesh transforms always cost me more than sending the geometry even when I had a ton of vertices. In this weird case, pre-computing the vertices into world space actually saved time even though I had multiple instances... like I said, that could have been peculiar to the engine, however.
> 1 votes

---
Tags: performance, directx9
---


# Question
Title: Programmatically determine UVs by rotating a plane along X axis
I'm having a math brainfart while trying to solve what might be a simple problem. I've got a plane in 3d space (it's actually the face of a 10-sided die):

```
Coordinates [x,y,z]:
Point_top  = [0,0,1]
Point_left = [Sin (2pie9/10), Cos(2pie9/10), 0.1] = [-.5878,.809,.1]
Point_right= [Sin (2pie/10) , Cos(2pie/10), 0.1]  = [ .5878,.809,.1]
Point_bot  = [-1,0,-0.1]

```

If you project that out, it's a plane with the top leaning back away from you, and the bottom closer to you.

I'm trying to automatically build a UV map of that face to put a texture on, so *think* I should rotate it around the x-asix so that it's only in 2D, then scale that to best fill up a 256x256 texture. I'm doing this in Three.JS for a canvas app.

Is this the right approach? In this example: http://wecreategames.com/games/DiceBoard ( die creation code is in: http://wecreategames.com/games/DiceBoard/die10.js ), I'm estimating the UVs by:

```
//Build UVs
scope.faceUvs = [[]];
scope.faceVertexUvs = [[]];
for (var f = 0; f < numHalfFaces; f++) {
    var faceuv = [
        new THREE.UV(.2, .6),
        new THREE.UV(.5, .75),
        new THREE.UV(.8, .6),
        new THREE.UV(.5, .2)
    ];
    scope.faceUvs[0].push(new THREE.UV(0, 1));
    scope.faceVertexUvs[0].push(faceuv);
}

```

But when I view on an iPhone or Android, it shows weird screen artifacts... I'm thinking because the UVs aren't exact.

I think I'd apply some function like this (where andDist is an angle):

```
rx = x;
ry = (y * Math.cos(angDist)) - (z *Math.sin(angDist));
rz = (y * Math.sin(angDist)) + (z *Math.cos(angDist));

```

But, I'm not sure how to get the angle that the face is inclined at. Any suggestions? Or, are those white screen artifacts due to something else I've overlooked?

# Answer
Here's the approach I would use. No rotations at all, just projections:

* For the face you want to solve, take the cross product of two outer edge vectors. This is your normal vector.
* With your normal vector and the distance from the origin, you now have the face plane in Hessian normal form.

ax + by + cz + d = 0
* Calculate the barycentric coordinates of your vertices by projecting them onto them plane. This is their U,V position in tangent space. If you've ever done a point-in-triangle test, it's the same math.

This link is a point in triangle test with source code for everything mentioned thus far: http://www.blackpawn.com/texts/pointinpoly/

Pretty much any ray-tracing site will have some variation of this.

* Find the min max of your barycentric coordinates.
* Using the min max, center your coordinates and scale to fit.

These are your texture coordinates for the face.

*Side note: When you select your edge vectors, mind your clockwise/counter-clockwise winding order. If your winding order is wrong, the texture will be inverted or mirrored.*
> 0 votes

---
Tags: rotation, uv-mapping
---


title: Anisotropic and trilinear filtering?

text:
# Question
Title: Anisotropic and trilinear filtering?
I'm confused about the usage of trilinear filtering and anisotropic filtering in SharpDX.

As far as i understood, trilinear filtering does linear filtering to the textures and in a case of LOD-change it also interpolates between the too LODs to smooth the transition.

Anisotropic filtering make the texture bigger. Now it is possible to use trilinear filtering to do the same thing, due to anisotropic filtering with bigger textures. This causes a lesser blurred image, when you use anisotropy, because the interpolation is better.

Now, it should be possible to use trilinear filtering and anisotropic filtering at the same time. But in the SamplerState i can only choose Filter.Anisotropy *or* Filter.MinMagMipLinear (should be trilinear, right?). You can see all possible filters here: D3D11 Filter Enumeration.

So my question: Can you use both techniques together, if yes, how can i archieve that in SharpDX with SamplerState?

# Answer
Anisotropic filtering does not alter the size of the texture. Anisotropic filtering allows the texture to be probed at a different rate on each axis, versus isotropic filtering (linear, bilinear, trilinear...) which must be probed at the same rate on each axis.

**Anisotropic filtering is primarily to solve the problem of texture blurring at highly oblique angles such as looking down a roadway or standing next to a wall.** Objects that are rendered long and skinny look better because the filter can choose the right mip level on each axis instead of being stuck with the resolution of the smaller axis and blurring the other one.

Anisotropic and isotropic textures are stored differently in the hardware because they do different things. **Anisotropic filtering isn't inherently better, it's only *"better for objects at funny angles"*.** You can't mix them.

You don't want to use it all the time because you'll be paying a performance penalty. Batch the objects its appropriate for and use it only for those, or if you don't have enough objects to justify it, copy them into pieces so the chunks aren't oblique when rendered.
> 3 votes

---
Tags: sharpdx
---


# Question
Title: Camera Touch Zoom and Pan with world - 2D
I am doing my first unity2d game and im in need of a little optimization for my camera.

I have a camera which could pan and zoom with the speed i have defined. The problem with that is the speed i defined for panning will be too fast when zoomed in and soo slow when zoomed out. Maybe it could be achieved by having varying speed with zoom level. I dont want that.

Instead, i would like to have the camera used in Clash of Clans (i have seen it only in that).

The camera pans/zooms async with the world. That is, at any zoom level, if we placed our finger on an object X and started moving, the object X will be right below our fingers all the way. That means the world moves relatively.

Its the same with the zooming. If we placed two fingers on object X & on object Y and started 'zooming' in or out, Those two objects will be there right below the fingers all the way.

## That is what i would like.

For panning, i tried this and failed : (Unity C#)

`Touch t = Input.getTouch(0); //when touchcount = 1 only`

`Vector2 prev_touch_position = t.position - t.deltaPosition;

Vector3 resultant_unitvector = (prev_touch_position - t.position) / (prev_touch_position - t.position).magnitude;

float resultant_magnitude = Info.half_height / camera.orthographicSize * (prev_touch_position - t.position).magnitude;
//Info.half_height is calculated during change in orthographic size and is a static variable.

camera.transform.position += resultant_unitvector * resultant_magnitude;`

The above code doesnt work as expected on debugging.

It would be a great help for the community if someone could solve this cuz that is some pretty good camera :) (Include damping after touch release if you could ? :) ) Im just a student by the way :)

Thanks in advance :)

# Answer
So I have found the solution at last :P the problem was the position of the Touches were in pixels and i took them as for screen coordinates. So to fix it,

```
float resultant_magnitude = Info.half_height / camera.orthographicSize * (prev_touch_position - t.position).magnitude;

```

replace the above by this :

```
float resultant_magnitude = Info.half_height / (Screen.height / 2) * (prev_touch_position - t.position).magnitude;

```

This helped :)
> 0 votes

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


# Question
Title: Collectible Card Game Card Text To Code Association
I am making a collectible card game using a command pattern for using card abilities and creating a class for each card text ability. The game is setup to work with an authoritative server structure. I have each cards stat values in a MySQL database. My question is what would be the best way to associate a cards text with the class that executes it?

For example, I have a Card class that pulls card stats from the database for the specific card. I would like to have an entry in the database for each card that determines what ability class the card has. Since, I'm limited to the basic data types in the database I'm trying to find the best way to associate a string or int to a class that executes the cards ability in my code.

My first solution is having each database entry for a card hold a string that holds the code for the class, and compiling that string on the fly. A second solution is having a giant switch statement class that associates each card name with the class of its ability. I feel like there should be a simpler way to get this accomplished though. Anyone have any insights? Thanks

# Answer
> 1 votes
Two methods that come to mind:

Rather than a big switch statement, which would be slow, you can use a Dictionary of some kind (probably Trie-based) to associate the string names to the classes for your card behaviors.

Another way that would be more automatic, but possibly slower, would be to use `Type.GetType(String classname)`

If you give this the full classname in the namespace of your application, you'll get the class specified by the string. That would let you just put the classnames in your database and associate them to card classes without defining the names-\>classes association beforehand.

---
Tags: c#, mysql
---


# Question
Title: cocos2dx: RunningScene != Scene You just Replace
I have this code for cocos2d-x 3.x:

```
void MainMenu::StartGame(cocos2d::Ref* pSender)
{
    auto director = Director::getInstance();
    auto newScene = Scene::create();
    director->replaceScene(newScene); //run
    Scene *maybeNewScene = director->getRunningScene();
    CCASSERT ( maybeNewScene == newScene , "...") ;          //Assert Fail

    auto hudLayer= HUD::create();
    hudLayer->setPosition(Vec2::ZERO);
    scene->addChild(hudLayer, Z_NORMAL);
}

```

But When I get runnign scene by `director->getRunningScene()`, It gives me the scene which was running before calling `director->replaceScene()`. (the scene which is going to be destructed soon)

When I checked `replaceScene()` function, This function places `newScene` in some varibale called `_nextScene` but not assigned it to `_runningScene` .

**Question:** How can I access `newScene`, just some lines further? ( for example in `HUD::init()`)

# Answer
Quoted from @mannewalis

> The reason your scene is not the running scene is because it it only gets set the **next frame**, or **even later** if there is a transition running.
>
> You could add you HUD create code in the new scene **onEnter** method, I believe runningScene will be set by then, but possibly not if there is a transition running, in which case you should add your HUD create code to the **onEnterTransitionDidFinish** method. You can even use a lambda method to do it by calling **setonEnterTransitionDidFinishCallback**.
> 0 votes

---
Tags: cocos2d-iphone, cocos2d, cocos2d-x
---


# Question
Title: Isometric view : what is the right angle to use?
Wikipedia states in an isometric view, all angles must be equal to 120.

I am building my assets by making screenshots of some 3D models, so I can get any point of view on them. I tried to capture them with a POV which gave me angles of 120 everywhere, but once I put those 2D assets in an isometric game engine, it was a bit weird looking.

Then I noticed something weird : in Age Of Empires, angles are not of 120 but 127 ! example : http://img1.wikia.nocookie.net/\__cb20120311170558/ageofempires/images/7/74/Age\_of\_empires\_building\_towncenter.jpg I tried building assets so that their base has an angle of 127 and it's better looking.

What is the reason behind that ? What is the right angle to use ? What do you use ?

# Answer
> 5 votes
When people refer to an isometric perspective in the context of pixel art or video games, they are usually talking about a dimetric projection where the z-axis is vertical and the x and y axis go diagonal with a vertical:horizontal ratio of 1:2. The reason is that this is much easier to pixel than a "true" isometric projection:

Alternatively there are also a few games which use a trimetric projection where one axis is 1:2 and the other is 2:1

However, when your workflow is based on rasterizing 3d models and not on 2d pixel art, then you can just as well go for a true isometric perspective when you think that this is more aesthetically pleasing.

# Answer
> 4 votes
As I found out later here isometric in video games in game development it is better to have tiles with a 1/2 height/width ratio, which displays better and is nice for calculations. As I measured, having those ratios also means having a 127 degrees angle.

Later, I found this answer on gamedev : What is the view perspective angle of most 2.5D isometric games it seems that diablo 2 also had this 127 degrees angles, which is also interesting because its ratios make a pythagorean triangle. If I understood this correctly, this would make a lot of calculations, especially on diagonals, easier.

---
Tags: isometric, angles
---


# Question
Title: Alpha blending, transparence and z-ordering
I'm making some tests with alpha blending in a projet and I don't understand something.

**In my tests I've done something like that and everything look good**:

* Draw blue box first (**depth test**: true, **blend alpha**: none, **color**: 1, 1, 1, 1)
* Draw left Mario (**depth test**: false, **blend alpha**: true, **color**: 1, 1, 1, 0.8)
* Draw red box (**depth test**: true, **blend alpha**: none, **color**: 1, 1, 1, 1)
* Draw right Mario (**depth test**: false, **blend alpha**: true, **color**: 1, 1, 1, 0.8)

**Every tutorial say that we should:**

* Draw opaque object first
* Order transparent object back to front then draw them.

Here is the result:

So, I'm not sure to understand how it work/what is wrong (I've read this document).

Thanks!

# Answer
> 1 votes
A quote from the document you pasted:

> 15.070 If I draw a translucent primitive and draw another primitive behind it, I expect the second primitive to show through the first, but it's not there?
>
> Is depth buffering enabled?
>
> If you're drawing a polygon that's behind another polygon, and depth test is enabled, then the new polygon will typically lose the depth test, and no blending will occur. On the other hand, if you've disabled depth test, the new polygon will be blended with the existing polygon, regardless of whether it's behind or in front of it.

You shouldn't disable depth testing before drawing the transparent marios. When depth testing is enabled, it will test if the pixels are already behind the opaque (or transparent if any has been drawn) boxes you have drawn earlier, and the output should be what you want.

---
Tags: opengl, 3d, sprites, transparency, alpha-blending
---


title: How to increase player Lifes count

text:
# Question
Title: How to increase player Lifes count
I am new in Unity Game Development. I am designing infinite game using C# scripting. There are many cubes in my game scene. if single cube is hit by player, He gets 100 points. if same color, two cubes are hit then gets 250 points. if same color three cubes are hit, gets 500 points....

This kind functionality is used in my game. It increases my score. I want to increase player life after every 2000 points or above. for Example. first life increase 2000 or above, second 4000 or above, third 6000 or above...so on. I don't want to use if condition for every 2000 points because game is infinite.

I don't know how to solve this logic. any help would be appreciated.

Thanks

# Answer
> 1 votes
You can do something like this:

```
// This is somewhere outside the update function
var lastPoints = 0;

// This is inside the update function
if(currentPoints - lastPoints > 2000) {
    increaseHealth();
    lastpoints = points;
}

```

This way you can infinitely increase the player hitpoints, until the points counter overflows.

---
Tags: c#, game-design, game-loop, unityscript
---


# Question
Title: How do I choose where to position a mini-map in the HUD?
In a game with a minimap, what factors should be considered when choosing where to put the minimap on the screen HUD? What choices are typically made when wanting to emphasize a particular factor?

# Answer
> 5 votes
There's no clearly "most common" position beside one the four corners. If you an information band/ribbon/... you typically want to embed it in your information ribbon, and leave the viewport as clean as possible. Since it's usually one of the biggest and more visual element to display in a HUD, you often want to push it to the corner to avoid it to be too distracting/overlapping. The band, when there is one, has often been place on the bottom, so it's no surprise, the minimap is often on the bottom left or bottom right in many games, especially RTS. Here is *Dota 2* and *league of legends*:

But other games have the band above, so the minimap is above. *On binding of isaac*, it's on the top left

Other have the band on the left or right, so the minimap is on the left or right. I can't remember a recent game with a left band, so here is *populous : the beginning*, with the minimap top left.

If you do not have a band in your HUD, put it where it hides the least interesting part of the viewport.

However if your minimap is very, very important and you cannot go around without, you can center it on the top or bottom edge of the screen, like *star citizen* or *elite dangerous* (which besides embed their minimap in the game world).

Without knowing what kind of game you want to make, that's all help we can give.

---
Tags: maps, hud
---


# Question
Title: Box2dWeb: must fixtures be destroyed explicitly when destroying the body?
I use b2WorldObj.DestroyBody(bodyObj) to destroy the body when it is not needed anymore. The body has one fixture attached to it.

Do I need to destroy the fixture before destroying the body? or should I assume that by destroying the body all its fixtures will be automatically destroyed?

Right now, I do not destroy the fixtures explicitly and the game runs fine. But my concern is more about memory leaks. I want to make sure that all the bodies and fixtures that are not used anymore are completely removed from the memory. How can I best achieve this?

Thanks!

# Answer
You could just have read the manual, you know.

Citation from the manual, chapter 7, section 7.2, page 35 :

> You can destroy a fixture on the parent body. You may do this to model a breakable object. Otherwise you can just leave the fixture alone and let the body destruction take care of destroying the attached fixtures
> 0 votes

---
Tags: box2d, memory, body
---


title: How do I crop a camera's viewport?

text:
# Question
Title: How do I crop a camera's viewport?
I'm making an Android game using LibGDX. I would like to render a cropped version of the camera's viewport.

Here's an original camera view (in 3ds max):

I can get the same view in LibGDX without any problems, with this code:

```
perspCam = new PerspectiveCamera(40, screenHeight, screenWidth * h / w);
perspCam.position.set(1, 6, 18f);
perspCam.lookAt(1, 3, -1f);
perspCam.update();

```

Now the tricky part: I actually want to see this view in-game:

It's basically just a crop of the camera viewport, keeping the original perspective and other camera properties.

Could someone explain the general concept? (No need for working code.)

# Answer
> 4 votes
This is an old question, so I'm guessing that tom37 may have moved on by now, but I think I have an answer for anyone else with the same problem.

For reference, here is a view of a surface grid using a perspective camera.

Now let's say that we want to render a portion of this current view, but to the entire screen. Let's render the top-left quarter of the image, outlined in white.

If we move the camera, then the perspective will change. We can use scissors to mask the rest of the image, but we want that portion to take up the entire screen. Let's try changing the viewport.

```
public class PerspectiveTest implements Screen {

    Viewport viewport;
    Camera camera;
    Sprite background = new Sprite(new Texture("grid.png");
    Stage ui;
    SpriteBatch batch = new SpriteBatch(250);

    public PerspectiveTest () {
        camera = new PerspectiveCamera(60f, 16, 9f);
        viewport = new FitViewport(8f, 4.5f, camera);
        ui = new Stage(viewport, batch);
        camera.rotate(60f, 1f, 0f, 0f);
        camera.translate(12f, -5f, 4f);
        camera.update();
        background.setSize(32f,32f);
    }

    @Override
    public void render (float delta) {
        Gdx.gl.glClearColor(0,0,0,1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        int x = 0;
        int y = -Gdx.graphics.getHeight();
        int w = 2*Gdx.graphics.getWidth();
        int h = 2*Gdx.graphics.getWidth();
        Gdx.gl.glViewport(x, y, w, h);
        batch.setProjectionMatrix(camera.combined);
        batch.begin();
        background.draw(batch);
        batch.end();
    }

    // There are a bunch of empty overrides here that I have left out.
}

```

The important line is Gdx.gl.glViewport(x, y, w, h); The viewport usually starts at x = 0 and y = 0 and extends to the full width and height of the screen. If we want to see only a part of that original viewport, we need to change both the size and the starting position. Here, I have moved the viewport down by one screen height and stretched the viewport to be twice as large in both directions. Let's see what happens:

The camera hasn't moved, so the perspective is the same, but we're only looking at what was the top-left corner of the original view! This topic had been giving me trouble for a few hours. I read this solution to a similar problem, and I realized it could be applied here.

To focus on any different portion of the viewport, simply choose x, y, w, and h accordingly. If you're going to do any more rendering in the normal fashion, make sure to reset the viewport with the original x, y, w, and h values.

I believe that the other three quarters of the viewport are not visible but are still rendering. It would probably be wise to use scissors in conjunction with this method in order to save resources.

# Answer
> 2 votes
You want scissor regions. Documentation for this feature in libgdx is here.

Sample code provided on that page is:

```
Rectangle scissors = new Rectangle();
Rectangle clipBounds = new Rectangle(x,y,w,h);
ScissorStack.calculateScissors(camera, spriteBatch.getTransformMatrix(), clipBounds, scissors);
ScissorStack.pushScissors(scissors);
spriteBatch.draw(...);
spriteBatch.flush();
ScissorStack.popScissors();

```

---
Tags: opengl, java, libgdx, camera, perspective
---


title: Fully dynamic KD-Tree vs. Quadtree?

text:
# Question
Title: Fully dynamic KD-Tree vs. Quadtree?
Working on my game, I'm at the point where I need to track all of the units in the world so that I can do nearest-neighbor checks for combat. This is an RTS-like game, with potentially thousands of small automated units moving around.

I've been looking into KD-Trees and Quadtrees (especially Point Quadtrees). I'm still trying to learn the details of how they work, but so far Point Quadtrees are making the most sense to me. However, I'm getting the impression that KD-Trees are quicker to search, which is important with the number of points I'll have in the tree.

On the other hand, in my case, I'm going to be tracking a massive number of units that are **always** moving. From frame to frame, their positions will always be different. Quadtrees are apparently faster to rebalance than KD-Trees, but I don't know if that is applicable when you are rebalancing **every** point in the tree.

I'm wondering if it would be better in this case to just scrap the tree each frame and rebuild it from scratch, rather than try to rebalance every single point in the tree? If a Quadtree is quicker to rebalance, does that also mean it is quicker to build from scratch? If so, that might be more important for performance than the KD-Tree's search speed, depending on how much of a burden it is to create the tree, but I don't know...

# Answer
> 17 votes
KD-trees are definitively not dynamic enough to be considered, honestly. Moving a few units can easily require you to rebuild the whole KD-Tree. Plus, a KD-tree is very efficient for queries, but not so much for neighbor searching.

A quadtree is more flexible over time, as the modification are kept more locally. The disadvantage is that if you have many units at one place that move often, it may subdivide too much and require a lot of updates due the movement of units. You can set a threshold under which, no subdivisions can occur. But beware, that implies a lot of units could potentially be in the same leaf square.

If however you're only interested in finding all units within a constant radius *r*, you don't need quadtree and kd-tree right away. You can simply create a 2D array of cells of side of length *r* and stack your units in each cell according to their position. That way, you always have at worst 9 cells to search. Only if your map is *huge*, such a grid would be too large to implement.

There's two more entirely different structures we didn't spoke of : hierarchical AABBs and local-sensitive hash table. If the origin of each hierarchical AABB is described relative to the parent AABB, it has advantage that if a large group of unit keep its formation, then you don't need to update the smaller AABBs since they keep the same relative positions. Of course, rotating the formation could cause many updates, in that case the usage of other bounding volumes like spheres or *oriented* bounding boxes (OBB) may be more efficient.

Local-sensitive hash tables only gives approximate solutions efficiently, so I wouldn't bother with them.

What would I do ? I'd probably start with a simple grid, and when I need it, I'd upgrade it to a quadtree and if I need it, I'll combine it with a bounding volume hierarchy under some threshold: quadtrees work well at a large scale, relative bounding volumes work well at a small scale. Doing it gradually, I don't have to spend hour from the start to get the best data structure *immediatly*.

# Answer
> 7 votes
Lærne's suggestions are great, but I would also suggest a dynamic bounding volume tree of AABBs. Conceptually the dynamic bounding volume tree keeps a balanced tree of nodes which can be queried at any time for near elements by passing in an AABB and retrieving an overlapping pair. The tree is not rebuilt every frame. Instead each node's AABB is slightly inflated when put into the tree, and the tree is only rebuilt whenever the node's actual AABB is no longer contained by the inflated AABB. I use it in my physics engine and it works great.

The Box2D source code has a great implementation of it.

https://github.com/erincatto/box2d/blob/master/include/box2d/b2\_dynamic\_tree.h

Here's a good review of their implementation:

Dynamic AABB Tree by Randy Gaul (archived from original)

---
Tags: rts, quadtree, kd-tree
---


# Question
Title: Creating looping canvas animation (slot machine with reels)
I have a small assignment to create something like slot machine with spinning pictures. I have to use HTML5 Canvas. I would like to hear some opinions how this can be made simply and performantly.

There are symbols that would be spinning vertically while only 2 would be fully visible, next 2 are partially hidden and remaining 2 are not visible at all.

I have chosen CreateJS suite, but I have no experience with that, so I am just trying to figure it out. I made this for the start...

```
var reels = [160, 405, 648, 892, 1137]; // X offset of reels
var reelLines = [0, 317, 634]; // Y offset of symbols in the reel

var stage = new createjs.Stage('game');

for (x = 0; x < reels.length; x++) {
  for (y = 0, y < reelLines.length; y++) {
    bmp = new createjs.Bitmap('symbol').set({
      x: reels[x],
      y: reelLines[y]
    });
    stage.addChild(bmp);
  }
}

```

This displays 3 symbols in each reel and it looks good. Now I need to add some animation to it. I am thinking about it like having stack of symbol bitmaps at the top position where it's not visible yet. I tried to use Tween class like this.

```
createjs.Tween.get(bmp, {loop: true}).to({
  y: 808
}, 500);

```

It's basically correct, symbol rolls in and out and then it pops at top again. However this works for single symbol only. If I position three symbols as stated above and run same tween on them, each of them will go in different speed, because `to` call second argument is *duration*, not the *speed*.

I would really appreciate some ideas on this approach and if it's even correct one.

# Answer
The problem is that you are using a fixed duration for each reel even though each reel has a different y offset. Instead, you should calculate the difference between the current y offset of each reel and the y position 808. Using this difference, you can determine how long each reel should tween if each reel went a fixed speed.

```
var diff = 808 - bmp.y;
var duration = diff / speed; // some fixed speed

createjs.Tween.get(bmp, {loop: true}).to({
  y: 808
}), duration);

```
> 0 votes

---
Tags: javascript, animation, html-canvas
---


# Question
Title: Tower Defense Search Enemies Efficiently
I had a problem with the build of a TD.

I got a slow - non efficient search for towers find targets to shoot.

PD: enemies\[\] got all the active & non-active enemies (death and alive) -\>Im using COCOS2dX and don't know yet how to remove items while the array is still on use. it is

```
CCArray enemies[Enemies];

```

and if anyone know how to remove without crashing in cocos2d-x or leaving the "NULL pointer", please tell me..

```
void Tower::update()
{

if (this->pChosenEnemy == NULL)
{
    int i = 0, size = enemies.size();
    for ( ; i < size; i++)
    {
        if (circleCollition(enemies[i]->getPosition(),    enemies[i]->getContentSize().width)  && enemies[i]->notDead())
        {
            //cout << << endl;
            this->chosenEnemyForAttack(enemies[i]);
            break;
        }
    }
}
else if(this->pChosenEnemy != NULL)
{
    if( pChosenEnemy->notDead())
    {
        if (!circleCollition(this->pChosenEnemy->getPosition(), this->pChosenEnemy->getContentSize().width)   )
        {
            this->lostSightOfEnemy();
        }
    }
}
}

```

I would like to know how you guys solve this unefficient problem. Thanks.

# Answer
1. Keep the array free of dead creatures. Here is the API for manipulating arrays. See `removeObjectAtIndex`
2. You can iterate once over all living creatures and check if their distance from each tower is smaller than the range of the tower.
3. If so decide on the factor you wish to pick the target by. Normally towers pick the target that is closest to the objective. You can remember which one of the creatures you iterated over was picked for each tower.

pseudo code:

```
array creatures;
array towers;
array tower_targets;
for (i = 0; i < creatures.length; i++){
  for(j = 0; j < towers.length; j++){
    if(distance(creature[i], tower[j] < tower.range){
      if(is_closer_to_objective(creature[i], tower_targets[j]){
        tower_targets[j] = creature[i];
      }
    }
  }
}

```

This is just pseudo code, convert it to working code.
> 1 votes

# Answer
*and if anyone know how to remove without crashing in cocos2d-x or leaving the "NULL pointer", please tell me..* Understand that:

```
int i = enemies->count();
for(int j = 0; j < i; j++){
  ...
  myArray->removeObjectAtIndex(j);
  ...
}

```

In this time myArray will be the count() = i - 1, but i will stay in i. On the last iteration a null pointer will happen. So, use that way to avoid null pointer:

```
int i = enemies->count();
for(int j = i - 1; j >= 0; j--){
  ...
  myArray->removeObjectAtIndex(j);
  ...
}

```
> 0 votes

---
Tags: algorithm, optimization, cocos2d-x, tower-defense, search
---


title: Build-time GLSL syntax validation

text:
# Question
Title: Build-time GLSL syntax validation
Is there a way to validate GLSL syntax build-time instead of run-time? My application takes a long time to start and I want to know at the earliest possible stage that my shaders are ok. I'm using Visual Studio/Xcode. The solution probably involves running a tool as a part of build process, but I'm looking for such a tool.

# Answer
NVIDIA's Cg Toolkit should be able to compile (or translate) shaders offline and spit errors. Another option is to create a tiny executable yourself that takes in a shader file and tries to compile it with your GPU driver's compiler (or perhaps such a compiler is already provided for you by the vendor). Though I think at least in the latter cases many compilers are too forgiving to catch all errors.

Related question: Multiplatform GLSL shader validator?
> 4 votes

# Answer
This is a pretty late reply, but some new options have shown up recently to address this.

Khronos released a reference compiler called *glslangValidator* that can perform syntax validation (and more) on GLSL shader files. If there are any issues with your shader, it will print them out with line number information.

You can set up a custom pre build step or the like in Visual Studio or XCode to run this tool on your shader files.

I also wrote a Property Sheet for Visual Studio that makes use of glslangValidator to do build time validation of shader files. You can find it here.
> 4 votes

---
Tags: opengl, glsl, xcode
---


# Question
Title: Camera stops moving forwards near World-Center
So basically this is a problem I've been having since forever. I implemented a Camera System, it works fine but somewhere around the center (0, 0, 0) of the world it doesn't work. Actually it works, but it always moves back at the position I was before. Like, if I'm at (1, 0, 0), walking forward will make me stay at (1, 0, 0), while moving backwards will not. The weird thing is that as said before it only happens there and if I'm moving forwards, backwards, left and right work perfectly!

That's how I do my Walking:

```
XMVECTOR D = XMVectorReplicate(d);
XMVECTOR L = XMLoadFloat3(&m_LookDirection);
XMVECTOR P = XMLoadFloat3(&m_Pos);
XMStoreFloat3(&m_Pos, XMVectorMultiplyAdd(D, L, P));

```

My Strafing (Left to Right) is basically the same thing. I update my ViewMatrix like that:

```
XMVECTOR R = XMLoadFloat3(&m_Right);
XMVECTOR U = XMLoadFloat3(&m_Up);
XMVECTOR L = XMLoadFloat3(&m_Look);
XMVECTOR P = XMLoadFloat3(&m_Pos);
XMVECTOR WU = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);

//Compute wuv vectors for camera space
XMVECTOR w = XMVector3Normalize(XMVectorSubtract(L, P));
XMVECTOR u = XMVector3Normalize(XMVector3Cross(WU, w));
XMVECTOR v = XMVector3Cross(w, u);

XMStoreFloat3(&m_LookDirection, w);
XMStoreFloat3(&m_Right, u);
XMStoreFloat3(&m_Up, v);

```

Then I fill in the ViewMatrix but that's unimportant.

Hope someone knows that basic mistake I'm doing!

Thanks

# Answer
> 0 votes
You could define your "look at" point to be the same as current position. In this case, this line:

```
XMVECTOR w = XMVector3Normalize(XMVectorSubtract(L, P));

```

will give you zero vector as forward direction, then you'll use it and of course there will be no movement

Simple example: you're at (0, 0, 0) and your look at point is (0, 0, 0)

Another possibility is that you're not moving your look at point, and when you cross it after some movement your forward direction negates thus moving you back

---
Tags: directx, camera
---


title: Gravity: Slow down on ground approach

text:
# Question
Title: Gravity: Slow down on ground approach
I'm looking for some math, nothing language dependant.

"Standard" gravity for a character in a 2D game would go something like this:

```
if player.y > ground.y {
   player.velocity.y = player.velocity.y - gravity
}

```

In the little game I'm implementing I would actually like the gravity to weaken, and the velocity to slow, as the player approaches the ground.

IE: When the character is 100m above ground he should fall faster than when he is 1m above ground. He should land like a feather in a way.

# Answer
> 2 votes
As you are creating a "fictional force" physics should be our starting point but the exact form can be up to you. My suggestion would be to use a modified drag rather than trying to modify gravity.

## Why you shouldn't use a modified gravity

This is because gravity applies a simple acceleration. This means if an object is rushing towards the ground at 100mph and gets close to the ground so gravity drops to zero it just doesn't get any faster, it doesn't land "light as a feather" as you hope. To slow it down you would have to apply a negative gravity. However; this still wouldn't work nicely because objects that were falling slowly would "bounce" without ever hitting the ground.

## Why you should use a modified drag

What you want to do is apply a force proportional to the velocity of the object. And make that force stronger nearer the ground.

So! What exact form should this force have? My suggestion would be as follows

```
if (height<heightAtWhichDragStarts){
     dragForce=dragCoEfficientAtGroundLevel*(heightAtWhichDragStarts-height)*objectMass*velocity
}else{
    dragForce=0
}

```

Usually drag force would not have mass in it, but I'm assuming you want heavy objects to have just as much "land light as a feather" as light objects so you'll need to apply more force to them. The more lightly you want objects to land the greater dragCoEfficientAtGroundLevel should be. You may want to also only apply this force to objects heading downwards so jumping objects aren't slowed down.

## How to apply this force

If you're using a physics engine apply it as that engine wants it (but be careful to make sure you don't mix up forces and impulses) but if you're "rolling your own" then apply it as follows.

Within your physics step you always want to include the time of that physics step, you'll need that because of how force effects velocity by the formala `F=ma` and `a=changeInVelocity/changeInTime`

So:

```
F=ma
dragForce=mass*changeInVelocity/changeInTime
changeInVelocity=dragForce*changeInTime/mass

```

Although including the `changeInTime` in the formula is important to get the physics right its also important for your simulation. If you don't include changeInTime you can get really nasty effects such as if your game slows down (for example because annother program is running) from 60 frames per second to 30 frames per second your physics can actually change which is obviously very bad

---
Tags: mathematics, software-engineering
---


title: Scripting vs Programming

text:
# Question
Title: Scripting vs Programming
How does using Scripting and calling functions of scripting API differ from programming using C++ in UDK or Unity?in scripting we use the scripting API to interact with the engine and use functions provided by this API to get things done by the engine?

# Answer
Scripting is a subset of programming. Programming in udk means you are also creating functions, mathematical expressions, logic and conditions etc yourself. When you say you are using a scripting language then basically it means you are calling functions, creating objects, setting the resources and much more batch work and sometimes AI too. Python, perl and java script are mostly used when you are doing the scripting work and are much easier to use.
> 1 votes

# Answer
Scripting and programming are used interchangeably in certain contexts, but they are certainly distinct. The clearest difference is that scripting is a type of programming in which you are controlling the behavior of complex objects. With scripting, you do not generally specify the structure of the application, but rather you manipulate the objects within an existing structure of another program (e.g. the UDK or Unity runtime engine). Of course, scripts can often set up their own internal structure, but they ultimately rely on another program for the low-level structure.

Some programming languages are referred to as "scripting languages". They are typified by being parsed and run by a program (the interpreter). You can see that this is another case of the script controlling objects (interpreter intermediate data objects, including things like bytecode) within a structure that already exists.

Another way to think about it is to see scripts as part of a data-driven program, whereas native programming (e.g. C++) is used to generate the actual machine code for that program. These lines can be blurred, of course!
> 1 votes

# Answer
**Scripting** usually referred to programs, which are processed by **interpreter** (virtual machine).

**Programming** usually referred to programs, which are **compiled** to machine code.

I think there is no reason to discriminate scripting and programming, since both scripting and programming environments are usually Turing-complete, so they are equally powerful.
> 0 votes

# Answer
Scripting is very different for various reasons from programming using C++ and very similar in the same time.

Similarities:

* You'll often write function, classes and expressions
* You instruct the Engine what to do during the game / menu state.

Differences:

* You need to compile C++ and you don't need to compile a script.
* C++ often offers lower level access to functionality and leaves more room for mistakes.
* Scripting languages often offer a useful and easier to learn API but not necessarily the case.

Why is C++ hard?
> 0 votes

---
Tags: unity, udk
---


# Question
Title: How can I implement a camera like the one in RotMG?
RotMG, an MMO top-down shooter, takes on a unique 2d-3d style, and has an intriguing camera;

The game is obviously 3d, not simply isometric, and if you play the game and turn on camera rotation you will notice the effect the game produces, like so.

RotMG is made using flash, and I am currently experimenting with libgdx (which uses lwjgl/opengl). How should I go about implementing a RotMG-like camera?

# Answer
> 2 votes
Can't speak to the exact implementation details (and if I could it would be off-topic), but here's some obvious ingredients to put together:

* The camera is using an *orthographic* projection. You can tell this because a vertical wall is exactly vertical on-screen no matter where it is — if the camera were perspective then they would be "leaning outward" from the center.

Once you have the camera set up, you just apply the rotation in 'modelview' space — it's exactly the same as if you had a first-person moving camera. The complete sequence of transformations you'd use are:

1. orthographic projection
    2. rotate around X axis to look down at world
    3. translate forward and down to establish camera's distance from player character
    4. rotate around Y axis (the player-controlled rotation)
    5. translate horizontally to follow player's position in world

Note: Since orthographic projection doesn't give any visual cue about how far the camera is from the scene, it can be easier to make mistakes than with perspective projection, and if you get things really wrong you can have the scene disappear due to near/far limits. This isn't a reason not to use orthographic projection — it's just something to know can go wrong.
* The walls, floors, water pool, etc. are ordinary 3D geometry with low-resolution textures. To have the pixelated effect, make sure to specify NEAREST rather than LINEAR texture magnification filtering.
* The characters and the water spray are 2D sprites. To learn about how to draw them and keep them upright even as the camera turns, read about *billboarding*. (The thin black outline and shadows are a completely separate problem to implement.)

---
Tags: opengl, java, 3d, libgdx, camera
---


title: NGUI Texture Background Font of Sprite

text:
# Question
Title: NGUI Texture Background Font of Sprite
I am new to Game Development and using NGUI plugin free version. There are few sprite images in my game. I made them prefab and instantiated at runtime. then I created NGUI Texture and Made it background. When I play my game. sprite prefabs instantiate behind the NGUI Texture Background. I want to place them front of NGUI Texture.I also changed camera Setting, now mainCamera depth is -1, and NGUI Camera depth is 1. changed both of them. But, could n't find solution. I have tried in several ways.

Any suggestions will be highly appreciated. Thanks

# Answer
> 1 votes
There are a few values that are crucial to multi-camera rendering in Unity: the culling mask, the clear flags, and the depth value. All three are mentioned in the camera component manual.

> mainCamera depth is -1, and NGUI Camera depth is 1.

Unity draws cameras in ascending order. If you want the NGUI background behind the scene, you should flip those depth values.

You should probably also make sure that the two cameras have appropriate culling masks. In this case, that might mean the UI camera should render *only* the UI layer, with the main camera rendering *only* other layers.

I'm not sure if NGUI renders to the depth buffer, but most multi-cam configurations call for clearing depth between cameras.

---
Tags: unity, textures, gui, unityscript, ngui
---


# Question
Title: Marching cubes leaving holes in the mesh
Hi I'm trying to reproduce GPU Gems 3 chapter 1 (Generating Complex Procedural Terrains Using the GPU) and so far I managed the basics... Now I'm betting some strange output.

I started with the suggested -ws.y to generate a plane. Then when I moved to the noise I noticed some holes in the mesh. But unlike this previous question.

The noise mesh:

So I decided to try something more simple, 3 tubes: x^2+y^2-2

x^2+z^2-2

y^2+z^2-2

I would assume there is some problem with the z axis. But I can seem to figure out what. My function to get the triangles vertex positions also seems ok...

```
Vector3 vertexAlongEdge(int edge, Voxel v){
    Vector3 result=new Vector3(0,0,0);

    Vector3 p1=v.vertexes[edges [edge, 0]];
    Vector3 p2=v.vertexes[edges [edge, 1]];
    float v1 = density (p1);
    float v2 = density (p2);
    if (Mathf.Abs (isoLevel - v1) < 0.00001)
        return p1;
    if (Mathf.Abs (isoLevel - v2) < 0.00001)
        return p2;
    if (Mathf.Abs (v1 - v2) < 0.00001)
        return p1;

    float m = Mathf.Abs((isoLevel - v1) / (v1 - v2));
    result.x = p1.x + m * (p2.x - p1.x);
    result.y = p1.y + m * (p2.y - p1.y);
    result.z = p1.z + m * (p2.z - p1.z);

    return result;
}

```

The only thing I can think of right now is an error in my table with the edges for each case. Please help.

# Answer
I found the problem. I had a wrong value on the vertex for an edge. My edge table said that for the edge 10 the vertex were 2 and 4 when they should be 2 and 6.

Thank you for your time.
> 1 votes

---
Tags: c#, unity, voxels, marching-cubes
---


# Question
Title: My texture blends into one single color (DirectX11)
First thread on gamedev stackexchange. I am currently creating a cube with a single texture on each side. I got my cube up and running. But when I apply my texture, I get this:

It blends the texture into a single color and apply it. I have various of examples that look near identical but do not have the same problem. Anyone know what can be the cause of this issue?

3D programming in general contains quite a bit of code. I wont copy paste all of it. If you want to see anything specific, you can request it. But here are some of the functions. Thanks in advance.

```
HRESULT Cubes::Render(ID3D11DeviceContext* _deviceContext, Camera _camera)
{
    HRESULT hr = S_OK;

    unsigned int stride = sizeof(Vertex);
    unsigned int offset = 0;

    _deviceContext->IASetVertexBuffers(0, 1, &this->mVertexBuffer, &stride, &offset);
    _deviceContext->IASetIndexBuffer(this->mIndexBuffer, DXGI_FORMAT_R32_UINT, 0);
    _deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

    D3D11_MAPPED_SUBRESOURCE ms;
    hr = _deviceContext->Map(this->mMatrixBuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &ms );
    if(FAILED(hr))
    {
        OutputDebugString("Failed to map matrixbuffer in Cubes.\n");
        return hr;
    }

    WVPBuffer* dataPtr;
    dataPtr = (WVPBuffer*)ms.pData;
    dataPtr->worldMatrix        = DirectX::XMMatrixTranspose( this->mWorld);
    dataPtr->viewMatrix         = DirectX::XMMatrixTranspose( _camera.GetView());
    dataPtr->projectionMatrix   = DirectX::XMMatrixTranspose( _camera.GetProj());

    _deviceContext->Unmap(this->mMatrixBuffer, NULL );

    // Set the position of the constant buffer in the vertex shader.
    int bufferNumber = 0;
    _deviceContext->VSSetConstantBuffers( 0, 1, &this->mMatrixBuffer );

    // Set the vertex input layout.
    _deviceContext->IASetInputLayout(this->mInputLayout);

    // Set the vertex and pixel shaders that will be used to render this triangle.
    _deviceContext->VSSetShader(this->mVertexShader, NULL, 0);
    _deviceContext->PSSetShader(this->mPixelShader, NULL, 0);
    _deviceContext->RSSetState(this->mRasterState);

    // Set shader texture resource in the pixel shader.
    _deviceContext->PSSetShaderResources(0, 1, &this->mTexture);
    _deviceContext->PSSetSamplers(0, 1, &this->mSamplerState);

    // Render the triangle.
    _deviceContext->DrawIndexed(this->mNoIndex, 0, 0);

    return hr;
}

HRESULT Cubes::LoadTexture(ID3D11Device* _device)
{
    HRESULT hr = S_OK;

    hr = D3DX11CreateShaderResourceViewFromFile(_device, "../Pictures/cube.png", nullptr, nullptr, &this->mTexture, nullptr);
    if(FAILED(hr))
    {
        OutputDebugString("Failed to create Cubes texture.\n");
        return hr;
    }

    return hr;
}

```

Pixelshader:

```
Texture2D shaderTexture;
SamplerState Sampler;

struct PSIn
{
    float4 Position : SV_POSITION;
    float2 Tex : TEX;
};

float4 PS_Cubes(PSIn _input) : SV_TARGET
{
    float4 textureColor;

    // Sample the pixel color from the texture using the sampler at this texture coordinate location.
    textureColor = shaderTexture.Sample(Sampler, _input.Tex);

    return textureColor;
}

```

# Answer
Your input layout defines `POSITION` as `R32G32B32_FLOAT` but `Vertex`'s first member is an `XMFloat4`. This results in garbage in the `TEX` input. To fix the problem, switch to a `XMFloat3` for the `Vertex` position member. Also, the offset for your `NORMAL` is set to zero - this should be `D3D11_APPEND_ALIGNED_ELEMENT` as well.
> 2 votes

---
Tags: c++, textures, directx11
---


# Question
Title: When would a mesh collider be better than primitive colliders
I have been reading through the Unity Manual and have come across some interesting information about mesh colliders and primitive colliders. It got me wondering if using many primitive colliders would be better than using a mesh collider for say a character object?

I was also wondering if there was any information on exactly how inefficient a mesh collider is to say having 20 box or cylinder colliders on a character mesh. I am guessing that the number of polygons on the mesh would be a factor but it would be interesting to see some raw comparisons between how this efficiency scales per polygon (or per 100 polys or some unit of measurement)

# Answer
In my experience writing collision detection, mesh-based collision (triangles versus other triangles) are the most expensive form of collision in physics engines (PhysX, Havok). Unity uses PhysX internally, so this is no different. Because each computer and platform perform differently, exact numbers cannot be provided, but generally speaking the relative costs of collision detection of types are in the following order, from most expensive to least: triangle mesh, convex hull, box, capsule, sphere, plane, point.

Triangle meshes have the least-helpful characteristics for writing efficient collision detection. As a mesh, they don't guarantee convexivity, are not solid, and cannot be described implicitly through an equation. As a result, any detection is performed with each triangle individually.

To expand on triangle mesh collisions, and without direct knowledge of the source code, I would think Unity does collision detection against triangle mesh in the following way: a spatial data structure wraps the triangles. Likely a KD-tree, bounding volume hierarchy (BVH) or some other form of hierarchical structure. This accelerates queries between primitives and the mesh, yielding a list of candidate triangles for what is called narrow-phase collision algorithm. Then primitive-v-triangle tests are performed. For spheres, the basic sphere-v-triangle test calculates the distance of point from triangle testing if the distance is less than the radius of the sphere. More complicated primitives against the triangle use the GJK algorithm, or SAT algorithm against the triangle.

To address the high cost of triangle meshes, most games that require high fidelity collision detection with characters resort to using a combination of primitives to approximate the character - spheres, capsules or convex hulls bound to the joints of the skeleton hierarchy. The actual number of shapes used to represent the character are determined by requirements and the hardware the platform running on.

So to answer your question, I don't think there is always an objective answer to your question about 'exactly how inefficient a mesh collider is...'. But a handful of simple primitives is always faster then a deforming mesh geometry.
> 11 votes

# Answer
Use the profiler to do detailed checks on these things.

But you're best off using primitive colliders unless you really need to be able to shoot a bullet between someone's arm and his side, and possibly miss. For most purposes, a simple pill shape is good enough for character collision.
> 1 votes

# Answer
The only time when a mesh collider may be appropriate would be for terrain surfaces that are often not flat and it's important to give a more realistic feel to walking on the ground surface as possible.
> 1 votes

# Answer
For a character object, mostly a capsule collider is enough. But ofcourse it depends on your game. Primitive colliders are more efficient compared to mesh colliders.

You can use Profiler in Unity Pro versions and there's an internal profiler in Android and iOS for Indie versions. Although the pro Profiler obviously gives you detailed analysis, the internal profiler is useful for getting some basic efficiency checks.

Check here: http://docs.unity3d.com/Manual/iphone-InternalProfiler.html
> 0 votes

---
Tags: unity, collision-detection, efficiency
---


# Question
Title: Can i buy a license to create a Pokemon game?
Is there a way to purchase a license to create a Pokémon game? Would I be able to pay owners or the Pokémon name and creators of concept and whoever has permission to make games a fee to make my own game?

# Answer
> 2 votes
In theory, yes, practically it's very, very unlikely (or simply too expensive). You'd most likely have to pay the initial license owner, since other licensees might not be allowed to sub-license anything. We're typically not lawyers here and you should ask such questions a real lawyer if you're serious about something.

Personal opinion: Screw the idea. :) Create your own IP/game world/setting. That way you're in full control, people might call it a knock-off, yet you'd have far more freedom. If your game idea doesn't work without the Pokemon label on it, it's most likely not good enough anyway to interest anyone in playing it.

---
Tags: game-design
---


title: Triangles go missing as Z changes

text:
# Question
Title: Triangles go missing as Z changes
I'm rendering a height map using shader-based OpenGL (3.3 to be precise). The height map data is from a grayscale bitmap (2D array of bytes). The dimension of the bitmap is 256 x 256.

With this data, being the Y value, I calculate X and Z as corners of uniformly distributed cells in a grid. I generate the vertices and upload it to a VBO. I generate indices and populate an IBO; indices are of type `GLshort`.

I've implemented a free roaming camera to roam around the terrain and verify its correctness. As I move around everything renders fine, except in some angles, particularly when viewing the terrain from above/afar, I see that some triangles in peaks of mountains go missing. In this position, if I vary the camera's position along its Z axis, I see the missing triangle are also varying. When I go closer to the peak, the error goes away and everything is nice and whole.

# Culling

I've read other similar questions here, which mainly suggest that it could be because those triangles are deduced as back facing and thus may disappear when facet culling is enabled. To rule that case out, I tried `glDisable(GL_CULL_FACE)` in vain.

# Z fighting

I thought of this issue too, but it doesn't make sense. Z fighting happens when two fragments have the same depth buffer value, but the triangles appearing in place of the missing ones (in a slightly different dull colour; see image below) are *behind* the missing ones and not at the same Z and thus shouldn't have this problem. In either case, I tried enabling and disabling depth test to be sure, but to no avail.

# Floating-point

Worried about floating point issues, I make sure that the vertices of the terrain are distributed around the origin i.e. if each cell is a square of length `c`, then both `X` and `Z` values of vertices are distributed equally around 0 e.g. X doesn't vary between 0 to 256 but from -128 to 128, assuming a per cell dimension to be 1 unit.

# Draw

Other than those I tried changing the way I give draw calls to GL: `glDrawElements` with `GL_TRIANGLES`, `glDrawElementBaseVertex` and `glMultiDrawElementsBaseVertex` with `GL_TRIANGLE_STRIP` didn't change the the situation too.

I tried searching on the internet for an explanation but I'm at a loss there too, particularly when one doesn't know the keyword to search for. This should be happening fairly commonly in serious games since they all have terrains of some kind. Is there a proper name for this, and a solution?

# Answer
so, to rework from comments: this is Z-fighting. The math is very well explained here: http://chaosinmotion.com/blog/?p=555, and the ways to solve it here: https://www.opengl.org/wiki/Depth\_Buffer\_Precision, but the gist is that Z-buffer is discrete, non-linear, and depends on the ratio of farplane/nearplane.

* discrete: the distance between near and far plane is sliced into layers. if two overlapping fragments (would-be pixels) fall in the same Z-layer, it's up to chance as to which one will be actually drawn. the number of layers depends on how many bits per pixel is allocated to the depth buffer. In extreme case, if the depth buffer is 2 bits per pixel, there are only 4 slices.
* non-linear: far-away slices are 'thicker' than the nearby slices. so the further away you look, the more chance there is of Z-fighting
* depending on the ratio: you say you have near at 0.001f and far at 5000.0f - ratio of 5 million. the suggested ratio is no more than 30k. one easy way to fix it is to move the near to 0.1f: not a huge loss of scenery, but a great increase of depth resolution.
> 6 votes

---
Tags: opengl, terrain, depth-buffer, heightmap
---


# Question
Title: Sound plays several times upon collision
Upon collision, my sound effect plays several times. How can I fix this?

```
public Sprite charAlive, charDead;
public AudioClip popAudio;

void  OnCollisionEnter2D (Collision2D col ){

    if (col.gameObject.name == "dirtWalls") {
        gameObject.GetComponent<SpriteRenderer>().sprite = charDead;
        AudioSource.PlayClipAtPoint(popAudio, transform.position);
        StartCoroutine (Dead ());
    }
    if (col.gameObject.name == "gooWalls") {
        gameObject.GetComponent<SpriteRenderer>().sprite = charDead;
        StartCoroutine (Dead ());
    }
    if (col.gameObject.name == "grassWalls") {
        gameObject.GetComponent<SpriteRenderer>().sprite = charDead;
        StartCoroutine (Dead ());
    }
}

IEnumerator Dead() {
//      AudioSource.PlayClipAtPoint(popAudio, transform.position); // PLAYS SEVERAL TIMES
//      AudioSource.mute(popAudio);
    yield return new WaitForSeconds(3/2);
            Application.LoadLevel ("untitled");
    // LOAD LEVEL RESETS EVERYTHING, MAKE LOAD CHAR INSTEAD?
}

```

# Answer
It was as easy as adding this to my IEnumerator Dead:

```
 if(hasPlayed == false){
        audio.PlayOneShot(popAudio);
        hasPlayed = true;
    }

```
> 1 votes

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


# Question
Title: Unity - SetLookAtPosition() - Body Jittering?
I'm working on a third person controller and I'm trying to make character look at the same point as the camera. The problem is that the character jitters all the time the SetLookAtPosition() starts working. Here is a pic:

Everything works great if don't call the LookAt function. Even commenting all the other code on FixedUpdate() and Update() functions the problem remains. The code goes like this:

```
void FixedUpdate()
{
    // Commented Code

    // Movimiento de Cabeza
    HeadOrientation();
}

private void HeadOrientation()
{
    animator.SetLookAtPosition(animator.GetBoneTransform(HumanBodyBones.Head).position + gameCamera.transform.forward);
    animator.SetLookAtWeight(1f, .4f, 1f, 1f, .8f);
}

```

Hope someone knows what's happening. Thanks and sory for my bad english!

---

After trying differents things, it seems that the SetLookAtPosition() function needs to be call in the **Update()** function, not in the **FixedUpdate()**.

I would appreciate if someone could explain why it needs to be like this.

# Answer
Apply any transformations inside the `Update()` method, rather than `FixedUpdate()`. Fixed update runs independently of your framerate, and this will inevitably cause stutter. Think that there may be a number of frames displayed without any call to `FixedUpdate()` in-between (the update is performed "late").

Aside from dealing with rigidbodies, you should have no use for `FixedUpdate()` in most typical projects.
> 6 votes

# Answer
The other answers are on the correct path, but note that **LateUpdate** is specifically useful for cases like this.

Using **Update** can cause "race conditions" of sorts, where the object you're tracking is updated before your object looks at it, causing a jitter at higher speeds.

The difference between the two is:

***LateUpdate*** *methods are called after all **Update** methods have been called.*

Generally speaking any kind of "Look" maneuver that's not physics related, including head movements and cameras will use **LateUpdate** (and in fact, I recall the default camera scripts use it as well).
> 2 votes

# Answer
I had this same problem. I found out you have to call this from `OnAnimatorIK`, not an update function.
> 0 votes

---
Tags: unity, third-person-view
---


# Question
Title: How can I have a Mecanim animation with displacement and physics?
I have 3D wolf models from my animator with displacement (i.e the wolf transforms with animation, not in-place). I have added rigid bodies to the models. I am facing following issues while executing them in my project:

1. When I turn on `IsKinematic` on my rigid body (i.e disable physics) the animations work perfectly, with displacement. But I need to have physics enabled on my wolf because it doesn't detect collision when physics is disabled and gravity doesn't have any impact.
2. When turn off `IsKinematic` (i.e enable physics), the animations don't work; the wolf start wobbling and flying in the air.

How can I resolve this?

# Answer
It depends on what type of collisions you want to resolve and who controls the wolf.

### Wolf is NPC

If you want to resolve collisions with static environment you should think about using NavMeshAgent and bake static geometry to navigation mesh (so, that kind of collisions will never happened). If you want to collide wolf with other units with simple colliders (for example capsule) you can implement custom collision behaviour by using methods: OnTriggerEnter, OnTriggerExit and OnTriggerStay. In this case set isKinematic on true in wolf's RigidBody component, and isTrigger on true in wolf's Collider component.

### Wolf controlled by player

In that case, you can use RayCast to check can you move wolf in preferred direction or not before move it. You even don't need RigidBody component be attached to your wolf.
> 1 votes

---
Tags: unity, physics, mecanim
---


# Question
Title: How to draw the contour of a hexagon area, like in Civ 5
I am trying to achieve the hexagon contour look you find in Civilization V:

I want to outline the area a unit can move to on a hexagon grid, so far I can get a list of all the tiles a unit can move to and from that select the tiles that are on the boundary, which looks like this:

Assume the list of boundary tiles are in random order. I can also get a list of all the corners on each hex. As you can see above the island in the middle would create a hole in the contour shape, Civ 5 also seems to handle these holes nicely:

# Answer
> 6 votes
The logic is simple: your contour is the set of all the edges that separate border tiles from non-border tiles. You can code the following:

```
for each boundary tile
    for each edge
        if edge is shared with a hex tile that is NOT in the boundary tile list
            mark as contour edge
render all contour edges

```

Note that if you want the contour to encompass the whole green area, rather than just the boundary tiles, then the condition becomes "if edge is shared with a hex tile that is NOT in the green tile list", and the outer for loop becomes "for each tile in the green list"

# Answer
> 0 votes
Do you have edge connectivity? If so pick an edge you know to be on the boundary and add to your list. Working in a consistent winding order (clockwise or counter clockwise) pick a vertex of that esge. Look at all neighbouring edges that share that vertex. If an edge is on the boundary travel down it and add to your list. Rinse and repeat. Eventually you will return to the original edge. Now the contour is complete.

For this to work you need dat on vertices and which edges of which tiles share them. As you traverse some edges will be on the same tile and some will take you to neigjbourinf tiles. In the end you have a polyline in the order of the boundary which would let you smooth it like civ does.

---
Tags: turn-based-strategy, hexagonal-grid, dynamic-mesh, outline
---


# Question
Title: How can I edit the components of an instantiated prefab?
Is it possible to edit one or more components of an instantiated prefab ?

For example if you instantiated five cube prefabs. Is it possible to reference each of the cube prefab and change a value individually ? Such as changing its position or even its scale.

If possible how can it be done ? Another request is, if this can be done. Could it be in the `Update()` function so when the game is running values can be experimented with.

# Answer
Yes, unless you click "Apply" in the editor any changes made to a prefab instance are considered as overriding the prefab and do not affect either the prefab or the other instances of the prefab.

Once you instantiate the prefab you can change all aspects of that instance at your discretion. You do it the same exact way you manipulate any other object.

**EDIT**: To address the specific example you provided.

```
List<GameObject> cubes = new List<GameObject>();
// Instantiate 5 cubes.
for (int i = 0; i < 5; i++)
{
    cubes.Add((GameObject)Instantiate(MyCubePrefab));
}

// Place them in a row, each one bigger than the last.
for (int i = 0; i < cubes.Count; i++)
{
    float newScale = 0.5f * i;
    float newX = 10 * i;
    cubes[i].transform.position = new Vector3(newX, 0, 0);
    cubes[i].transform.localScale = new Vector3(newScale, newScale, newScale);
}

```

All of the above could've (should've) been performed within the same loop but in this example I wanted to stress that each instance is completely separate and manipulating them isn't tied to instantiating them. Note that none of these changes I've made here are carried across to the either the prefab or the other instances of the prefab
> 2 votes

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