# Question
Title: Can GJK be used with the same "direction finding method" every time?
In my deliberations on GJK (after watching http://mollyrocket.com/849) I came up with the idea that it ins not neccessary to use different methods for getting the new direction in the doSimplex function.

E.g. if the point A is closest to the origin, the video author uses the negative position vector `AO` as the direction in which the next point is searched. If an edge (with A as an endpoint) is closest, he creates a normal vector to this edge, lying in the plane the edge and `AO` form. If a face is the feature closest to the origin, he uses even another method (which I can't recite from memory right now)

However, while thinking about the implementation of GJK in my current came, I noticed that the negative direction vector of the newest simplex point would *always* make a good direction vector.

Of course, the next vertex found by the support function could form a simplex that less likely encases the origin, but I assume it would still work.

Since I'm currently experiencing problems with my (yet unfinished) implementation, I wanted to ask whether this method of forming the direction vector is usable or not.

# Answer
Actually, the negative vector of the most recently added point will *not* always be a good search direction. I can understand if your intuition brought you to this conclusion, but it's wrong.

Search directions are about finding support points that are furthest along a Voronoi region, away from the current simplex. Search directions are not only about vertices. Besides just watching Casey's video you should study GJK more formally to make sure you really understand what is going on.

In the case of Casey's video, he's just trying to find any axis of separation between two convex hulls in order to early out GJK, not even caring to find the distance between the two objects. This is actually not the original GJK algorithm, but a modified one that quickly finds separating axes.
> 1 votes

---
Tags: collision-detection, algorithm
---


# Question
Title: How can I read a portion of one Minecraft world file and write it into another?
I'm looking to read block data from one Minecraft world and write the data into certain places in another.

I have a Minecraft world, let's say "TemplateWorld", and a 2D list of Point objects. I'm developing an application that should use the x and y *values* of these Points as x and z reference coordinates from which to read constant-sized areas of blocks from the TemplateWorld. It should then write these blocks into another Minecraft world at constant y coordinates, with x & z coordinates determined based on each Point's *index* in the 2D list.

The issue is that, while I've found a decent amount of information online regarding Minecraft world formats, I haven't found what I really need: more of a breakdown by hex address of where/what everything is.

For example, I could have the TemplateWorld actually be a .schematic file rather than a world; I just need to be able to read the bytes of the file, know that the actual block data starts always at a certain address (or after a certain instance of FF, etc.), and how it's stored. Once I know that, it's easy as pie to just read the bytes and store them.

# Answer
Minecraft uses a tree-structured file format known as "NBT" (kind of like JSON or XML, but not text-based). **There are no fixed offsets which you can rely on.** You will need to use a library to parse NBT (or write your own parser) and then extract the information you want from the parsed structure.
> 0 votes

# Answer
Easiest way for you to achieve that would be to use already created world engine.

McEdit allows you to write plugins in python. You could write two plugins: First would load a file with points, create schematics of those regions. Second would load file with points and folder with schematics and paste them in.
I don't know if McEdit can be used in a scheme: automatically run a plugin and exit.
> 0 votes

---
Tags: minecraft-modding, data
---


# Question
Title: How to make an object move again after being stopped by collision in Unity?
I have a player object which position is always centered on the main camera's viewport. This object has a Rigidbody 2D, a box and circle collider. The player moves around a level, the level has a polygon collider attached.

I move the camera until the object hits against the collider, which stops the movement of the camera by setting its speed to 0. The problem happens when I want to move the camera / player object away from the collider. As the speed is already at 0, it cannot move away from the collider.

The script attached to the player object, checks for collisions and applies the speed to 0 on the main camera's test script.

```
using UnityEngine;
using System.Collections;

public class move : MonoBehaviour {
public float speed;
public test testing;
// Use this for initialization
void Start () {
     speed = 10F;
    testing = Camera.main.GetComponent<test>();
}

// Update is called once per frame
void FixedUpdate () {
    Vector3 p = Camera.main.ViewportToWorldPoint(new Vector3(0.5F, 0.5F, Camera.main.nearClipPlane));
    transform.position = new Vector3(p.x, p.y, -1);

}

void OnCollisionEnter2D(Collision2D col) {

    testing.speed = 0;

}
void OnCollisionExit2D(Collision2D col) {

    testing.speed = 10F;

}

```

}

This is the script attached to the main camera; just a simple script that changes the camera's position.

```
using UnityEngine;
using System.Collections;

public class test : MonoBehaviour {
public float speed;
public float translationY;
public float translationX;
// Use this for initialization
void Start () {

    speed = 10F;
}

void FixedUpdate () {
     translationY = Input.GetAxis("Vertical") * speed * Time.deltaTime;
     translationX = Input.GetAxis("Horizontal") * speed * Time.deltaTime;

    transform.Translate(translationX, translationY, 0);
}

```

}

The player object isn't kinematic and is a fixed angle, the colliders aren't triggers and the polygon collider isn't a trigger either.

The player is the red square, the collider is the pink area.

-- EDIT --

From the latest change the collider set up for the player

So if the X speed was disabled. It wouldnt move into the side of the polygon colider which is good, but yet you couldnt move away from it. And moving down would move inside the colider.

# Answer
> 2 votes
Add a flag to determine if the player has been stopped. At that point, stop setting the players position to the camera's, and instead some other input.

```
public float speed;
public test testing;
bool stopped = false;
// Use this for initialization
void Start () {
    speed = 10f;
    testing = Camera.main.GetComponent<test>();
}

// Update is called once per frame
void FixedUpdate () {
    if (!stopped)
    {
        Vector3 p = Camera.main.ViewportToWorldPoint(new Vector3(0.5F, 0.5F, Camera.main.nearClipPlane));
        transform.position = new Vector3(p.x, p.y, -1);
    }

    else
    {
        //move away here
    }
}

void OnCollisionEnter2D(Collision2D col) {
    stopped = true;
    testing.speed = 0;

}
void OnCollisionExit2D(Collision2D col) {
    stopped = false;
    testing.speed = 10f;
}

```

### Edit

Seeing how you move the camera, in your camera script I would have two different speeds

```
public float speedX;
public float speedY;
public float translationY;
public float translationX;
// Use this for initialization
void Start () {
    speedX = 10F;
    speedY = 10F;
}

void FixedUpdate () {
     translationY = Input.GetAxis("Vertical") * speedX * Time.deltaTime;
     translationX = Input.GetAxis("Horizontal") * speedY * Time.deltaTime;

    transform.Translate(translationX, translationY, 0);
}

```

Then you can omit the flag I talked about previously, and only modify `speedY` so the player can still move to the side.

```
public float speed;
public test testing;
// Use this for initialization
void Start () {
    speed = 10F;
    testing = Camera.main.GetComponent<test>();
}

// Update is called once per frame
void FixedUpdate () {
    Vector3 p = Camera.main.ViewportToWorldPoint(new Vector3(0.5F, 0.5F, Camera.main.nearClipPlane));
    transform.position = new Vector3(p.x, p.y, -1);
}

void OnCollisionEnter2D(Collision2D col) {
    testing.speedY = 0;

}
void OnCollisionExit2D(Collision2D col) {
    testing.speedY = 10F;

}

```

### Edit 2

Using this SO question we can determine where the collision was. We can then modify our code to be

```
void OnCollisionEnter2D(Collision2D col) {
    var relativePosition = transform.InverseTransformPoint(col.contacts);
    if (abs(relativePosition.position.x) > abs(relativePosition.position.y))
        testing.speedX = 0;
    else
        testing.speedY = 0;
}

void OnCollisionExit2D(Collision2D col) {
    testing.speedY = 10F;
    testing.speedX = 10F;
}

```

---
Tags: c#, 2d, unity, collision-detection, camera
---


# Question
Title: How can I compile and distribute a Torque2D game as an executable?
Is it possible to compile a Torque2D into a executable rather than having to run Torque2D.exe from the project folder (where all the `modules` and `artwork` are)?

What would be the normal procedure to distribute a game written with Torque2D?

# Answer
Well the Torque2D executable IS the game and the rest of the files including all your script files are just resources that the game loads when it runs. To make the executable look like your game with it's own icon and name you'll need to compile the executable yourself after changing the name of the executable and the icon. Even after doing this the script files will still be separate from the executable. Before you release your game you should also remove all the .cs files and just leave the compiled .cs.dso files.
> 1 votes

---
Tags: torque-x
---


title: Fix joint length in Box2D?

text:
# Question
Title: Fix joint length in Box2D?
I'm having some difficulties with Box2D DistanceJoints, I'm trying to create a rope using DistanceJoints connecting some bodies together but the length of joints between bodies change due to weight of bodies, is there any way to prevent joint lengths from changing?

# Answer
For those who may encounter this problem in the future: I just changed my approach, I used some `Revolute Joint` to connect bodies together and mark all bodies as sensor so that they don't collide with each other (tell me if you any better way to avoid collision of the rope parts), and use boxes to fill the space between joints (previously it was Distance joints connecting circle shapes). Having density set to non-zero value the result looks like a real rope.
> 2 votes

# Answer
DistanceJoints can be soft spring like joints, or rigid and firm joints depending on your choice of `frequencyHz` and `dampingRatio`.

Set `dampingRatio` to 1.0 for zero oscillations (i.e. inflexible distance).

You may need to set `frequencyHz` to 0 as well.
> 5 votes

# Answer
I've faced the same problem, and what I've done was using DistanceJoint, with the **frequencyHz set to 60** (or more) and the **dampingRatio set to 0**.

Imagine your distanceJoint as a rubber thread.

* Higher frequencyHz makes thread more persistent.
* Lower dampingRatio make it sooner for the thread gain original length after being stretched.
> 3 votes

# Answer
I was struggling with ropes in Box2D until I discovered that a joint's "strength" is proportional to the mass of the bodies it is connected to. The solution that worked for me was just to increase the density of the rope until it was strong enough to hold other objects up.
> 0 votes

---
Tags: box2d
---


title: Box2D body rotation with setTransform

text:
# Question
Title: Box2D body rotation with setTransform
I' having a problem rotating a body with `setTransform()`, The body has multiple sensors that should rotate with the player. The rotation works but it rotates around the bodys local 0,0 position instead of the center. Note that the game is in a top-down perspective and the player can go in four different directions, thus I need to rotate him immediately (in one tick) in 90 degrees steps.

Up:

Down:

I can't find a way to set the rotation center.

Here's the code I use to rotate it:

```
float angle = direction * 90 * MathUtils.degRad; // direction is an int value from 0 to 3
body.setTransform(body.getPosition(), angle);

```

I also tried `body.getLocalCenter().set()` and `body.getMassData().center.set()` but it didn't seem to have any effect. How can I rotate the body around its center?

EDIT (added code to create fixtures):

This is the method to create a fixture:

```
private Fixture createFixture(FixtureDef fixtureDef, Body body) {
    PolygonShape ps = createPolygon(); // creates a polygon shape from XML config
    fixtureDef.shape = ps;
    Fixture fixture = body.createFixture(fixtureDef);

    if (fc.filter != null) {
        fixture.setFilterData(fc.filter);
    }
}

```

This is the simplified code to create the fixtures (they are really loaded with xml config but these are the values I set):

```
FixtureDef sensorDef1 = new FixtureDef();
sensorDef1.friction = 0;
sensorDef1.restitution = 0;
sensorDef1.isSensor = true;
sensorDef1.center = new Vector2(0.8f, 1.6f);
// and some filters

FixtureDef sensorDef2 = new FixtureDef();
sensorDef2.isSensor = true;
sensorDef2.center = new Vector2(0.8f, 1.6f);
// and some filters

FixtureDef sensorDef3 = new FixtureDef();
sensorDef3.isSensor = true;
// and some filters

createFixture(sensorDef1, body);
createFixture(sensorDef2, body);
createFixture(sensorDef3, body);

```

# Answer
> 1 votes
I fixed the issue by changing the global coordinate system to the box2d one. Now the local 0,0 coordinates of my entities correspond to their center coordinates and they represent meters instead of pixels.

EDIT (some clarifications):

I now translate them in the render system (because this is really the only place where I need pixel coordinates):

```
// get the position from the entity, scale it by PIXELS_PER_METER
// and subtract half the dimension (which is also scaled by PIXELS_PER_METER)
Vector2 scaledPos = pos.cpy().scl(Config.PIXELS_PER_METER)
            .sub(dimension.cpy().scl(0.5f * Config.PIXELS_PER_METER));

```

Not that in my case `Config.PIXELS_PER_METER` is equal to `10.0f`.

In every other place where I use coordinates, they are already configured as meter and the coordinate represents the center of a body, just like in Box2D. This way the body rotates around the center of the body instead of 0,0.

---
Tags: libgdx, box2d, rotation
---


# Question
Title: What is the maximum value for a leaderboard entry in Google Play Services?
What is the maximum value an entry in a leaderboard using the Google Play Services can have?

# Answer
The leaderboard documentation doesn't explicitly say (as of this writing).

However if you look at the documentation for the C++ API's `Score` object, you can see that the value of the score is exposed as a `uint64_t`, which means you have 64 bits of storage for your scores (as integers, times, or currencies).

As an integer this value is 18,446,744,073,709,551,615.

Note that you can also set explicit upper and lower limits on scores allowed on the leaderboard via the API.
> 2 votes

---
Tags: google-play-services
---


title: Material tiling and offset in unity

text:
# Question
Title: Material tiling and offset in unity
***Ambiguity:*** What exactly is the difference between Tiling the material and Offset of material?

***Need to do:***

I need the material to be repeated `n` times on the object where I need to set the value of `n` via script.How do I do it?

It seems to happen through Tiling(tried via inspector) but again what is difference between `mainTextureOffset` and `setTextureOffset`?

*Tried:*

Following is the line of code that I tried to repeat the texture `n` number of times on an object(repeat across the width of object), but it does nothing significant that I can see.

# Answer
> 3 votes
> What exactly is the difference between Tiling the material and Offset of material?

Those parameters set by the inspector are used inside the shader to scale the texture coordinates. A `uniform float4` in the shader with the name of the texture and `_ST suffix` is populated with those values. For example considered the main texture:

```
float2 scaled_uv = tex.uv * _MainTex_ST.xy + _MainTex_ST.zw;

```

Let's say the offset basically translate the texture in the uv space meanwhile the scale, scales it.

**mainTextureOffset**: set the texture offset of the main texture (texture binded to the name `_MainTex` inside a shader)

SetTextureOffset let you specify the texture name. `SetTexureOffset(_MainTex, offset);`is equivalent to use the facility `mainTextureOffset`.

An alternative is setting directly the uniform vector. The used convention for built-in shaders is using the suffix \_ST to the texture name. So you can also use SetVector:

```
material.SetVector("_MainTex_ST", scaleAndOffset);

```

---

EDIT

For repeat the texture you have to modify the scale not the offset. If you set for example a scale of 2 along an uv axis you will obtain to repeat the texture twice along it.

# Answer
> 1 votes
Documentation on the website which also happens to be the first search result for the term `SetTextureOffset` or `mainTextureOffset` seems to sum up the issue nicely.

# `Material.SetTextureOffset`

> ```
> function SetTextureOffset (propertyName : String, offset : Vector2) : void
>
> ```
>
> # Description
>
> Sets the placement offset of texture `propertyName`.
>
> Common texture names used by Unity's builtin shaders:
>
> * `"_MainTex"` is the main diffuse texture. This can also be accessed via ***`mainTextureOffset`*** property.
> * `"_BumpMap"` is the normal map.
> * `"_Cube"` is the reflection cubemap.

# `Material.mainTextureOffset`

> ```
> var mainTextureOffset: Vector2;
>
> ```
>
> # Description
>
> The texture offset of the main texture.
>
> The same as using `GetTextureOffset` or `SetTextureOffset` with `"_MainTex"` name

A material has a main texture, which is the one you see. Additionally, it can have other textures, such as a bump or cube map which affect how the object's appearance is calculated. `mainTextureOffset` only affects the material's main texture. `SetTextureOffset` lets you specify the name of the texture to offset, so `SetTextureOffset("_MainTex", .05)` would be eqivalent to `mainTextureOffset = .05;`

---
Tags: unity, textures, shaders
---


title: What to do with input during movement?

text:
# Question
Title: What to do with input during movement?
In a concept I'm working on, the player can move from one position in a grid to the next. Once movement starts it can't be changed and takes a predetermined amount of time to finish (about a quarter of a second).

Even though their movement can't be altered, the player can still press keys (perhaps in anticipation of their next move). What do I do with this input?

Possibilities i've thought of:

* Ignore all input during movement.
* Log all input and loop through them one by one once movement finishes.
* Log the first or last input and move when possible.

I'm not really sure which is the most appropriate or most natural. Hence my question:

**What do I do with player-input during movement**?

# Answer
Reaction to your proposed methods:

* valid choice, but your the controls may feel unresponsive - player has to wait before he can do next step.
* Imagine what would happend if he smashed the keyboard(cat walked over it): half a hour of uninterruptable random movement.
* Sound ideal, doesnt it? Controls are responsive and no trips all over map are included. You are probably best with the last input. I would probably choose this as a player.
> 2 votes

# Answer
It all comes down to your very own game/project **AND** playtest results.

If your game mechanics aren't strictly affected by this, ignoring input would be the best solution in terms of Occam's razor: *"the simplest solution is probably the best one"*.

However, evaluate your game mechanics and If you're able to develop the three approaches, run a playtest process to each one, see the reactions, ask questions to your players and see the results.
> 1 votes

# Answer
## If your game is real-time:

You should make sure that **as soon as a movement is completed, if a key is currently pressed, the character will immediately start moving in that direction.** This ensures that the game does not require the player to have exact keypress timing to move efficiently, which in my experience is very frustrating.

There are two possible ways to do this:

1. Any time there is no movement in progress, check the movement keys' state and start another movement if one is down. (If you only have key events, then remember the last one seen for a movement key.)

This is sort of like "ignoring input", but note that it will *not* ignore a key which was pressed before movement finished but is *still down* when it does finish.
2. Any time a movement key is pressed, remember its direction. Any time there is no movement in progress, use the single recorded keypress to start a new movement.

The difference between these two cases is whether a key which is pressed *and released* before movement becomes possible will still cause another movement. I recommend trying both to see which feels better.

## If your game is turn-based:

I recommend, for turn-based games, that you take your second approach: use all the keypresses you got, in sequence. Furthermore, if you have keypresses buffered like this, speed up your animations. This allows the player to quickly move through parts of the game they're replaying without it getting tedious.

If it is infeasible to speed up the game when there is buffered input, then you should either ignore input or buffer exactly one keypress (first or last doesn't matter much).
> 0 votes

# Answer
Process the input immediately. Start the animation and ignore further input for gameplay-affecting commands (but let the player inspect objects or do other things that aren't gameplay commands). Once the animation is complete (if it ends abruptly and has a clear point) or nearly complete (if it has a "softer" ending), allow new inputs.

Also be absolutely sure to communicate the input state to the user via the UI. If a button can't be clicked, draw it differently to signify this. Change the mouse cursor. Highlight objects when moused over differently. Make it very, very clear when you are ready to accept new input and when you aren't. 100% absolutely unquestionable clear.

You want to accept new commands in a timely manner but not absurdly early. e.g., if a character is animating movement along 12 steps, accepting new input as the animation is completing the last step may be acceptable. Better to just have a clear animation (and a clear UI) so the player knows when to enter more input.
> 0 votes

# Answer
Logging all user input for movement could create problems. An easy work around to that problem would be to put a cap and simply stop logging input if there is too many logged already.

However, I would simply ignore input while they are moving, or just ignore the input oof certain keys.
> -1 votes

---
Tags: input
---


# Question
Title: What is the easiest and fastest way to display an SDL_Surface in a window with SDL2?
I would like to have an SDL\_Surface representing the contents of the window, just like in the old days with SDL1.2. What is the best and fastest way to do it in SDL2?

What I found is that I need an SDL\_Window, an SDL\_Renderer for that window, an SDL\_Texture to render, and an SDL\_Surface to create a texture from. This seems a bit too much to me, since I just want to display a single image on the screen.

Not to mention the impact on the performance. On my machine (Lenovo Y510p laptop) this whole procedure takes 9ms, without any memory allocation, only using pre-allocated variables and totally black SDL\_Surface.

Is there a way I could speed up things?

# Answer
> Is there a way I could speed up things?

No, there isn't.

The slowest part of your system is the time it takes for the image to be displayed on the monitor, which presumably is in the vicinity of 24 milliseconds. (The monitor takes 16 milliseconds to draw the frame, plus 8 milliseconds because on average the monitor will be halfway through drawing a frame when your code finishes preparing the window and its image, so there will be an 8ms extra pause while the monitor finishes drawing the previous frame). In practice, the delay will actually be even higher than this due to other sources of latency; often monitors are working an extra frame or two behind their input sources for one reason or another.

The upshot of this is that even if you somehow manage to optimise things so that your code runs instantaneously -- 0 ms instead of 9 ms -- it still won't actually be any faster, since your code wasn't the slow part of the system; the monitor is the slow part. Anything you do to try to "optimise" the code will produce no faster output from the user's point of view, because your code's output is being limited by how quickly the monitor can display it, and the monitor is already substantially slower than your code is now.

So don't worry about trying to speed up your current code. Really. Obsessing over this small stuff is a total waste of your time.
> 1 votes

# Answer
From what I know the fastest way to render something in SDL 2.0 is using textures. You can use SDL\_BlitSurface so you don't need to use renderers and convert to textures but that is slower and it is also a bad habit to use it. I would say to stick with textures because it is probably the fastest way to do it. Plus that it is also not so much harder to use textures. It is basicly the same.
> 0 votes

---
Tags: 2d, graphics, sdl
---


# Question
Title: What problem does double or triple buffering solve in modern games?
I want to check if my understanding of the causes for using double (or triple) buffering is correct:

A monitor with 60Hz refresh's the monitor-display 60 times per second. If the monitor refresh the monitor-display, he updates pixel for pixel and line for line. The monitor requests the color values for the pixels from the video memory.

If I run now a game, then this game is constantly manipulating this video memory.

If this game don't use a buffer strategy (double buffering etc.) then the following problem can happen:

The monitor is now refreshing his monitor-display. At this moment the monitor had refreshed the first half monitor-display already. At the same time, the game had manipulated the video memory with new data. Now the monitor accesses for the second half monitor-display this new manipulated data from the video memory. The problems can be tearing or flickering.

Is my understanding of cases of using buffer strategy correct? Are there other reasons?

# Answer
> 74 votes
Fundamentally, a core goal in rendering is for each frame displayed on the monitor to present a single, coherent image. There are several different strategies which are, or were, used in order to achieve this.

In the following, I mention "vsync". Vsync is the moment at which the monitor begins drawing a new screen image; it's the point at which "vblank" begins on a traditional CRT screen, where the scanline momentarily stops drawing and moves back to the top of the monitor. This moment is very important for many of the approaches to frame coherence.

"Tearing" is what we call it when a screen renders from two different images, within a single frame. If, for example, I've drawn two screen images which are intended to be displayed one after the other, but the monitor has instead displayed the top half of frame one, and the bottom half of frame two, that's "tearing". This happens due to changing the data the monitor is reading from while the monitor is drawing, instead of during vblank. (In modern programs, this typically happens because the user disabled waiting for vsync in their driver settings)

**Zero-Buffer**

On the oldest hardware, there often wasn't enough memory to hold a full screen image, and so instead of drawing a screen image, you needed to specify colors for each scanline individually, while the monitor was in the process of drawing that line. On the Atari 2600, for example, you had just 76 machine instruction cycles to specify what color went into each pixel of the scanline, before the television started to actually draw that scanline. And then you had 76 instruction cycles to provide the contents for the *next* scanline, and so on.

**Single-Buffer**

When drawing in a "single-buffer" context, you're drawing straight into the VRAM which is being read from by the monitor. In this approach, you "race the scanline". The general idea is that when the scanline starts drawing the previous frame's contents at the top of the screen, you draw into VRAM *behind* it. So while the scanline is drawing the screen image for the last frame, you're drawing the next frame behind the scanline.

In general, you're trying to finish drawing the next-frame image before the scanline "laps" you by coming around again and overtaking the pixels that you're drawing, and also to never get *ahead* of the scanline, or else your new frame might draw into what should have been the previous frame.

For this reason, single-buffer rendering typically worked itself by drawing scanlines, from top to bottom, and from left to right. If you drew in some other order, it was likely that the scanline would come around again and spot bits of the "next" image which you hadn't gotten around to drawing yet.

Note that in modern operating systems, you typically never have an opportunity to draw single-buffered, though this was fairly common thirty years ago. (gosh do I feel old right now -- this is what I was doing when I first started out in game development)

**Double-Buffer**

This is much, much simpler than either of the strategies that came before.

In a double-buffering system, we have enough memory to store two different screen images, and so we designate one of them as the "front buffer" and the other, the "back buffer". The "front buffer" is what's currently being displayed, and the "back buffer" is where we're currently drawing.

After we finish drawing a screen image to the back buffer, we wait until vsync, and then swap the two buffers. This way, the back buffer becomes the front buffer, and vice versa, and the whole swap happened while the monitor wasn't drawing anything.

**Triple-Buffer**

One issue often raised with double-buffer approaches is that after we finish drawing to the back buffer, we have to just sit around waiting for vsync before we can swap the buffers and continue working; we could have been doing calculations during that time! What's more, all the time that we're waiting to swap between the buffers, the image in that back buffer is getting older and older, thus increasing the user's perceived latency.

In triple-buffer systems, we create ourselves three buffers -- one front buffer and two back buffers. The idea is this:

The monitor is displaying the front buffer, and we're drawing into back buffer #1. If we finish drawing into back buffer #1 before the monitor finishes drawing the front buffer, then instead of waiting for vsync, we instead immediately start drawing the next frame into back buffer #2. If we finish and vsync still hasn't come, we start drawing back into back buffer #1, and so on. The idea is that when vsync eventually happens, one or the other of our back buffers will be complete, and that one can be swapped for the front buffer.

The benefit of triple-buffering is that we don't lose the time that we spent waiting for vsync in the double-buffering approach, and the image swapped onto the front buffer may be "fresher" than one which had been waiting for vsync for 8ms. The down-side of triple-buffering is that we need extra memory for storing the extra screen image, and that our CPU/GPU usage will be higher (again, since we don't slow down to wait for vsync).

Typically, modern drivers will often perform triple-buffering transparently, behind the scenes. You write your code to do double-buffering, and the driver will actually return control to you early, and just internally handle swapping between however many back buffers it wants to use, without your code ever being aware of it.

GPU vendors currently recommend that you not implement triple-buffering yourself -- the driver will do it for you automatically.

---
Tags: rendering, double-buffering
---


title: Timed player collision

text:
# Question
Title: Timed player collision
I'm trying to make the player loose one heart then cool down for a second after being hit. For an example

```
if(a.overlaps(b)) {
p.health--;
}

```

would lower the health while being touched. In my old game I used a thread algorithm to wait a second, but that took a while. Besides doing some kind of complicated timer method, what can I do to keep to the player hit one at a time?

# Answer
Give the player a number in their class called `hitCountdown` or something. Every time they are hit, set that number to the amount of time you want to give the player to escape. Then, where you update the player, decrement the countdown

```
if(hitCountdown > 0) hitCountdown--;

```

Now, when you hit the player and damage him, write this:

```
if(a.overlaps(b)) {
    //if it has been a while since we got hit
    if(hitCountdown <= 0){
        p.health--;
    }
}

```
> 0 votes

---
Tags: java, algorithm
---


title: Libgdx, find Vector3 direction

text:
# Question
Title: Libgdx, find Vector3 direction
I am using Libgdx along with Bullet physics. I have a vehicle moving. I would like to use a ray from the vehicles origin and in the vehicles forward direction.

How can I create the forward Vector3 so I can apply it to the ray?

# Answer
If you want the ray the vehicle is currently moving upon, you want the difference between the current position and a previous position, then normalize it for the direction of the ray (the start of the ray being the current position). Alternately, you can make a normalized copy of the velocity vector for the direction with and current position as the start of the ray.
> 0 votes

# Answer
thanks for the answer, I'm sure it would have worked perfectly.

however as i was implementing it i came across a Bullet Physics built in function.

BtRayCastVehicle has

```
vehicle.getForwardVector()

```

thanks for your help in this matter
> 0 votes

---
Tags: java, libgdx, bullet-physics, raycasting
---


# Question
Title: How do you create a .XNB Font file for use with CocosSharp?
I know the .XNB file format is an XNA thing and that CocosSharp inherits this from its MonoGame roots. However there doesn't seem to be any information on how to create your own .XNB fonts to use with CocosSharp. I've tried searching but can find any information.

Could someone explain it here or point me to a tutorial on how to create .XNB font file for use with CocosSharp?

A site to download already compiled .XNB Fonts would also be acceptable.

Update: Another thing that makes this tricky is that I guess XNA Game Studio could be used, but it's not compatible with Windows 8.1; which is what I currently use for my dev machine...

# Answer
Unfortunately Monogame cannot (yet) generate XNB files so you will need to use the original content builder from XNA 4.0 https://github.com/xupefei/XNA-4.0-Content-Compiler.
> 3 votes

---
Tags: xna, monogame, fonts
---


# Question
Title: How can I apply a "genie animation" to a CCSprite?
I am new to Cocos2D and following this tutorial.

I want to animate a `CCSprite` with the genie effect that OS X uses for hiding windows to the dock and showing them again.

Here's an example from an iOS library:

How can I do this in Cocos2D?

# Answer
Use ccsprite with ccbadgenode in order fire number of frame of spite with moveto postion can change each frame interval with time .cccallfuntion is

```
-(void)playStarAnimation
{
    Animation *anim = [Animation node];
    sp = [anim playAnimCCSpriteWithFileName:@"STARS~ipad" frameName:@"STARS" Layer:physicsLayer From:1 To:42 Delay:1.0/20.0 Loop:4 Position:CGPointMake(512, 750) TAG:STARS_ANIM];
}

CCSequence *seq5 = [CCSequence actions:[CCDelayTime actionWithDuration:5.3],
        [CCCallFunc actionWithTarget:self selector:@selector(playStarAnimation)], nil];
[self runAction:seq5];

```
> -1 votes

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


title: UDK: Toggle Material on Brushes?

text:
# Question
Title: UDK: Toggle Material on Brushes?
I'm attempting to change / toggle the material that's applied to a BSP brush. I've seen where it's possible on static meshes, but I can't seem to get it to work on brushes. Below is an example scenario.

1. The ground (BSP Brush) is covered in a stone material
2. The player hits a trigger.
3. A new "moss" material is applied to the brush, removing the old stone material.

Any assistance you could offer would be greatly appreciated.

# Answer
Did quite a bit of research and it looks like this isn't possible in UDK. A material applied to a BSP is static and cannot be changed dynamically in game.
> 1 votes

---
Tags: udk
---


title: MCP 1.7.10 Java class navigation

text:
# Question
Title: MCP 1.7.10 Java class navigation
So, I'm new to the Minecraft modding community and trying to understand where to start. I've attempted to do it before, but dropped it to the complexity of starting and the lack of a site like this to help (Mind that I'm also semi-new to Java, but have worked extensively in Javascript and Python. I understand how Java is different from the two).

I have downloaded MCP 9.08 (Decompiles 1.7.10), and deobfuscated Minecraft. I'm looking to mod client, so I didn't supply it with a server jar. Everything seemed to work fine in decompile (Only error was it couldn't find the server jar). I can find my files in /mcp908/src/minecraft/net/minecraft. However, if I open up one of the classes in, say, block, I see a bunch of variables starting with p\_ and ending with \_. Is there any way to make these variables more decipherable, to understand what's going on so I can learn by example? Thank you.

# Answer
Mojang obfuscate their code whenever they bundle it into a .jar, which is essentially renaming all their variables and methods to gibberish, presumably to prevent others from cracking or modding it

The MCP team has done a great job of deobfuscating this code and deducting what each variable roughly means, but there are still some that are too arbitrary to understand what they do. Hence they remain obfuscated, and are just assigned a random number or string etc.

So in short, if you want to get a proper name for these variables you'll need to find out what they do/change and rename them yourself
> 1 votes

---
Tags: minecraft-modding, modding
---


# Question
Title: How to implement Fog Of War with an shader?
Okay, I'm creating a RTS game and want to implement an AgeOfEmpires-like Fog Of War(FOW). That means a tile(or pixel) can be:

* 0% transparent (unexplored)
* 50% transparent black (explored but not in viewrange)
* 100% transparent(explored and in viewrange)

RTS means I'll have many **explorers** (NPCs, buildings, ...). Okay, so I have an 2d array of bytes `byte[,] explored`. The byte value correlates the transparency.

The question is, how do I pass this array to my shader? Well I think it is not possible to pass an entire array. So: **what technique shall I use to let my shader know if a pixel/tile is visible or not?**

# Answer
Yes it is possible. And it is called texture.
Textures are not just pictures \- it can be any kind of data\*.
Another option would per-vertex data - if you dont mind smooth border between (un)explored. Or just as other post suggested - pass it as per-tile uniform.
* *Ofcourse, you need to stay in reasonable array size, defined by maximum texture size. Also note that editing such texture would mean sending it all over again, which could be slow.*
> 2 votes

# Answer
I'd simply provide a uniform per tile. For example a simple float that indicates the transparency.
Before you render the tile, you simply set the uniform. If that's not possible, try using vertex attributes (also using a simple float).
> 2 votes

---
Tags: unity, shaders, hlsl, fog-of-war
---


title: Blender DirectX exporter to Panda3D

text:
# Question
Title: Blender DirectX exporter to Panda3D
I have been experimenting with Panda3D lately. I have a character made in Blender with various bones and currently with one animation that I wish to export to a \*.x format for Panda3D. My current attempt was to export the model was to first export with bones \[Armatures\] by checking the "Export Armatures" button in the export menu (file name: `char.x`). Thanks to the `*.x` file format, I read the file and it seems to have the same bone structure format as the model (with parenting and matrix positional data). The second export was selecting Animations -\> Full Animation to provide just the animation (file name: `char_idle.x`). The models exported just fine. I am not sure about the animation yet, but the file seems to be just fine.

This is my code for loading the model into python & Panda3D: `self.model = Actor("char.x",{"char_idle.x"})`

When I run the program the command line provides a couple of errors, the main errors of interest are:

`:Actor(warning): char.x is not a character!`

and

```
...
  File "C:\Panda3D-1.8.0\direct\actor\Actor.py", line 284, in __init__
    if (type(anims[anims.keys()[0]])==type({})):
  AttributeError: 'set' object has no attribute 'keys'

```

The first error is the most interesting to me. The model works if I leave the animation dictionary blank. With no animations loaded the character appears in its un-animated T position, however the actor warning still shows up. The character should include the various bones when I exported the model right? I am not that experienced with blender, I'm just a programmer. So if the problem lies in blender please try to keep that in mind when posting a reply. I'll try my best to keep up.

I also tried to print out the bone structure without any animations loaded and it provides a similar error with the line `print self.model.listJoints()`:

```
 File "C:\Panda3D-1.8.0\direct\actor\Actor.py", line 410, in listJoints
    Actor.notify.error("no part named: %s" % (partName))
  File "C:\Panda3D-1.8.0\direct\directnotify\Notifier.py", line 132, in error
    raise exception(errorString)
StandardError: no part named: modelRoot

```

I really hope it is a simple exporting fix.

# Answer
> 2 votes
The first error means you are passing a set (ie. `{1, 2, 3}`) to the Actor constructor whereas it expects a dictionary (ie. `{'a': 1, 'b': 2, 'c': 3}`).

The second error about missing `modelRoot` means that the model you are trying to load is not rigged; Panda3D does not recognise it as a character. That, or you are trying to load the animation data as an actor in itself.

I would suggest that you try a dedicated exporter like YABEE (Blender 2.5+) or Chicken (\< 2.5).

---
Tags: models, blender, panda3d
---


title: Algorithm to find average position

text:
# Question
Title: Algorithm to find average position
In the given diagram, I have the extreme left and right points, that is -2 and 4 in this case. So, obviously, I can calculate the width which is 6 in this case.

**What we know:**

The number of partitions:3 in this case The partition number at at any point i.e which one is 1st,second or third partition (numbered starting from left)

**What I want:**

The position of the purple line drawn which is positio of average of a particular partition

So, basically I just want a generalized formula to calculate position of the average at any point.

# Answer
How about: `(width/amountPartitions) * partitionNo + (width/amountPartitions/2) + posFirstPartition`

So for your example for the first partition (counting from 0) this would be:
`(6/3) * 0 + (6/3/2) - 2`
`1 - 2`
`-1`
Which should be what you indicated in your picture.
*This is assuming all partitions are the same size.*
> 1 votes

---
Tags: algorithm
---


# Question
Title: Taking fixed direction on hemisphere and project to normal (openGL)
I am trying to perform sampling using hemisphere around a surface normal. I want to experiment with fixed directions (and maybe jitter slightly between frames). So I have those directions:

```
vec3 sampleDirections[6] = {vec3(0.0f, 1.0f, 0.0f),
                            vec3(0.0f, 0.5f, 0.866025f),
                            vec3(0.823639f, 0.5f, 0.267617f),
                            vec3(0.509037f, 0.5f, -0.700629f),
                            vec3(-0.509037f, 0.5f, -0.700629),
                            vec3(-0.823639f, 0.5f, 0.267617f)};

```

now I want the first direction to be projected on the normal and the others accordingly.

I tried these 2 codes, both failing. This is what I used for random sampling (it doesn't seem to work well, the samples seem to be biased towards a certain direction) and I just used one of the fixed directions instead of s (here is the code of the random sample, when i used it with the fixed direction i didn't use theta and phi).

```
vec3 CosWeightedRandomHemisphereDirection( vec3 n, float rand1, float rand2 )
    float  theta = acos(sqrt(1.0f-rand1));
    float  phi = 6.283185f * rand2;

    vec3 s = vec3(sin(theta) * cos(phi), sin(theta) * sin(phi), cos(theta));

    vec3 v = normalize(cross(n,vec3(0.0072, 1.0, 0.0034)));
    vec3 u = cross(v, n);
    u = s.x*u;
    v = s.y*v;
    vec3 w = s.z*n;

    vec3 direction = u+v+w;
    return normalize(direction);
}

```

\** EDIT \**

This is the new code

```
vec3 FixedHemisphereDirection( vec3 n, vec3 sampleDir)
{
    vec3 x;
    vec3 z;

    if(abs(n.x) < abs(n.y)){
        if(abs(n.x) < abs(n.z)){
            x = vec3(1.0f,0.0f,0.0f);
        }else{
            x = vec3(0.0f,0.0f,1.0f);
        }
    }else{
        if(abs(n.y) < abs(n.z)){
            x = vec3(0.0f,1.0f,0.0f);
        }else{
            x = vec3(0.0f,0.0f,1.0f);
        }
    }

    z = normalize(cross(x,n));
    x = cross(n,z);

    mat3 M = mat3(  x.x, n.x, z.x,
                    x.y, n.y, z.y,
                    x.z, n.z, z.z);
    return M*sampleDir;
}

```

So if my `n = (0,0,1);` and my `sampleDir = (0,1,0);` shouldn't the `M*sampleDir` be (0,0,1)? Cause that is what I was expecting.

# Answer
> 1 votes
You can do this easily with quaterions:

```
vec3 sv=normalize(sampleDirections[x]);
vec3 hv=normalize(sv+vec3(0, 1, 0));
vec4 q=vec4(cross(sv, hv), dot(sv, hv));
vec3 rot_n=2*(cross(q.xyz, cross(q.xyz, n) + q.w*n) + n;

```

Instead of storing sampleDirections, you should store the quaternion/matrix rotations of the vector to optimize computations in a shader.

# Answer
> 0 votes
In order to transform the hemisphere points into the space of the normal, you need to set up a coordinate frame. Your second example is closer to something which will work, but keep in mind that you should only construct M once. Basically, your code fails because it makes a comparison between vectors. Such operations make very little geometric sense, because round off errors mean two vectors are rarely the same. (Your normal will almost never be exactly `vec3(1,0,0)`.)

To specify a coordinate frame in 3D, you only need two vectors orthogonal to each other. The third can be computed via the cross product. You already have one, which is the normal, and will become the eventual "Y" axis. To find the "X" axis, we need to pick a vector with a low absolute value of the dot product (i.e. close to orthogonal) with our "Y" axis, take their cross product and normalize, which gives us "Z", and then compute the true "X" from the cross product of "Y" and "Z".

We observe if the normal is `n` then the dot product between some `X` and `n` is `n.x * X.x + n.y * X.y + n.z * X.z`. Let us select `X` from `<1,0,0>`, `<0,1,0>` and `<0,0,1>`. Then to minimize the dot product, we just select the one of these three which corresponds with the minimum component of `n`. For example, if `|n.x| > |n.y| < |n.z|`, we would choose `<0,1,0>` because `n.y` has the smallest value. An alternative is to take the maximum component, zero out the others, and then shift it by 1 component cyclically (e.g. `<0.4,-.2,0.6> -> <0,0,0.6> -> <0.6,0,0>`.)

This technique means that you will have discontinuities in the orientation of the samples where the smallest component of the normal changes. (This pattern will look like a cube with X's across the faces.) Due to the hairy ball theorem, discontinuities are unavoidable.

---
Tags: opengl, multisampling
---


# Question
Title: State of the art Culling and Batching techniques in rendering
I'm currently working with upgrading and restructuring an OpenGL render engine. The engine is used for visualising large scenes of architectural data (buildings with interior), and the amount of objects can become rather large. As is the case with any building, there is a lot of occluded objects within walls, and you naturally only see the objects that are in the same room as you, or the exterior if you are on the outside. This leaves a large number of objects that should be occluded through occlusion culling and frustum culling.

At the same time there is a lot of repetative geometry that can be batched in renderbatches, and also a lot of objects that can be rendered with instanced rendering.

The way I see it, it can be difficult to combine renderbatching and culling in an optimal fashion. If you batch too many objects in the same VBO it's difficult to cull the objects on the CPU in order to skip rendering that batch. At the same time if you skip the culling on the cpu, a lot of objects will be processed by the GPU while they are not visible. If you skip batching copletely in order to more easily cull on the CPU, there will be an unwanted high amount of render calls.

I have done some research into existing techniques and theories as to how these problems are solved in modern graphics, but I have not been able to find any concrete solution. An idea a colleague and me came up with was restricting batches to objects relatively close to eachother e.g all chairs in a room or within a radius of n meeters. This could be simplified and optimized through use of oct-trees.

Does anyone have any pointers to techniques used for scene managment, culling, batching etc in state of the art modern graphics engines?

# Answer
> The way I see it, it can be difficult to combine renderbatching and culling in an optimal fashion. If you batch too many objects in the same VBO it's difficult to cull the objects on the CPU in order to skip rendering that batch. At the same time if you skip the culling on the cpu, a lot of objects will be processed by the GPU while they are not visible. If you skip batching copletely in order to more easily cull on the CPU, there will be an unwanted high amount of render calls.

You would usually cull objects first. Only then do you walk your potentially visible set and build batches for rendering.

If culling your objects proves to be slow you could try grouping them into bounding volume hierarchies and cull those first.
> 1 votes

# Answer
There's lots of information about frustum and occlusion culling on the internet. Most of it comes from game developers. Here's a list of some articles that will get you started:

My (pretty fast) renderer works similar to this:

1. **Collection**: Send all props, which you want to render, to the renderer.
2. **Frustum culling**: The renderer culls the invisible props from the list using multiple threads in parallel.
3. **Occlusion culling**: Now you could do occlusion culling on the CPU (I haven't implemented it yet, because I don't need it now). Detailed information on how to do it efficiently can be found in the Killzone and Crysis slides. One solution would be to read back the depth buffer of the previous frame from the GPU and then rasterize the bounding boxes of the objects on top of it to check if the object is visible.
4. **Splitting**: Since you now know which objects actually have to be rendered, because they are visible, you have to split them by mesh (you can also split them by texture instead), because each mesh has a different material or texture (otherwise the modelling software would have combined them into a single mesh).
5. **Batching**: Now you have a list of meshes to render. You can sort them by:
    * depth (this can be done on the prop level instead of the mesh level), to save fillrate (I don't recommend doing this if your fragment shaders are very simple).
    * mesh (because there might be multiple instances of the same mesh and it would make it easy to add instancing).
    * texture, because texture switches are very costly.
6. **Rendering**: Iterate through your partitioned meshes and render them.
> 1 votes

# Answer
Probably the best way to go with a modern DX11 level HW today is to:

1. Do frustum culling using octree or similar on CPU
2. Batch objects in a frustum per frame (i.e. build dynamic instance streams for each object type in the frustum)
3. Perform occlusion culling purely on GPU (i.e. convert the FOV instance streams to renderable instance streams).

For the the last step you need DX11 level HW, i.e. use compute shader to build renderable instance stream and DrawIndexedInstancedIndirect(). Also for the occlusion culling I would go with bounding box test against hierarchical Z-buffer
> 0 votes

---
Tags: opengl, scene-graph, culling
---


# Question
Title: Proper way to encapsulate a Shader into different modules
I am planning to build a Shader system which can be accessed through different components/modules in C++. Each component has its own functionality like transform-relevated stuff (handle the MVP matrix, ...), texture handler, light calculation, etc...

So here's an example:

I would like to display an object which has a texture and a toon shading material applied and it should be moveable.

So I could write ONE shading program that handles all 3 functionalities and they are accessed through 3 different components (texture-handler, toon-shading, transform).

This means I have to take care of feeding a GLSL shader with different uniforms/attributes. This implies to know all necessary uniform locations and attribute locations, that the GLSL shader owns. And it would also necessary to provide different algorithms to calculate the value for each input variable. Similar functions would be grouped together in one component.

A possible way would be, to wrap all shaders in a own definition file written in JSON/XML and parse that file in C++ to get all input members and create and compile the resulting GLSL. But maybe there is another way that is not so complex?

So I'm searching for a way to build a system like that, but I'm not sure yet which is the best approach.

# Answer
There are many ways to handle this kind of logic in a shader:

* Use dynamic branching: Plain `if`s are not that slow on modern hardware. Test and profile it. If it doesn't slow down your application, this is probably the most straightforward and flexible solution.
* Use shader subroutines: This is a new GLSL feature. It is supposed to be faster than dynamic branching and provides a lot of flexibility to shader code writing.
* Use compile-time directives: Write the shader code with `#ifdef`s that enable/disable paths according to the global flags set at compile time. This is also a very common approach that has no runtime cost.
* Build the shader during runtime from code snippets: This is what you are proposing with the XML/JSON idea, I believe. It is pretty much the same as using `#ifdef`s and conditional compilation, but can give you more flexibility to adjust the shader code for providing fallback to older hardware/missing features. This can be a fairly complex approach, which I would try to avoid for a small to mid size project. It can involve a lot of code and maintenance overhead for the programmers. Read this blog post for an interesting discussion on this subject.

Overall, you will probably end up using some or all of the above options.
> 2 votes

---
Tags: opengl, c++, shaders, glsl
---


# Question
Title: Human vs human android chess game design
First of all I am total amateur in game development and sorry for my poor English. I want to make android human vs human chess game. So I am wondering how to design it?

scenario 1: User connect to server, find opponent and send moves to server using socket, so match is running on a server side. I think this is not good idea because move should be validated on client side - or do I have to validate moves on client side? I do not think this is good solution because game is seperated.

scenario 2: Using hole punching technique so server is needed only for connection between players, so game is running on android devices.

which approach do you suggest? Or is there any better solution? Which server is best to use?

# Answer
For most games, most of the game logic should be done on the server to avoid cheating.

However, in games like chess which are turn-based, have no information hiding and no randomness, this is something different. There is just no way to break the rules of chess without the other party being able to notice. This means that it is sufficient in this case to just send the other player the move and have them validate if the move is valid or not. You should still validate the own moves of the player though, so that the player gets immediate feedback and illegal moves aren't even sent to the other player.

Be careful though when you want to have online scoring. Cheaters could try to send you wrong match results to boost their score or reduce that of their opponents. To mitigate this, you could have both players send the recorded moves of the whole match to the server after the match is over. When they differ, they didn't play the same game. That means either that there is a bug in your app or that one of them was cheating.
> 1 votes

---
Tags: android, client-server, chess
---


# Question
Title: Combining pathfinding with global AI objectives
I'm making a turn-based strategy game using Java and LibGDX. Now I want to code the AI.

I haven't written the AI code yet. I've simply designed it. The AI will have two components, one focused in tactics and resource management (create troops, determine who have strategical advantage, detect important objectives, etc) and a individual component, focused in assign the work to each unit, examine its possibilites and move the unit.

Now I'm facing an important problem. The map where the action take place is a grid-based map. Each terrain has different movement cost. I read about pathfinding and I think A\* is a very good option to determine a good route between two points. However, imagine I have an unit with movement = 5 (i.e, it can move 5 tiles of movement cost = 1). My tactical AI has found an objective at a distance d = 20 tiles (Manhattan distance) from my unit.

My problem is the following: *the unit won't be able to reach the objective in one turn.* So the AI will have to store a list of position and execute them in various turns. I don't know how to solve this.

PS. In my unit code, I have a list called `selectionMarks` which stores all the possible places where the unit can go in this turn. This places are calculated recursively using a `getSelectionMarks` function.

# Answer
Your pathfinding should return a list of way points to reach your objective for each unit. Since you are making a turn based game, I am assuming that the unit movement is like a chess piece. It is either on "this" tile or "that tile, and not in between. If this is the case you might end up with the scenario where a units movements runs out in the middle of the next tile. For example, if you have a unit with a movement of 5 and it needs to travel across 3 tiles each with a movement cost of 2. Clearly the unit has traveled across the first 2 tiles, but what about the third tile? Is the unit stopped on the third tile with 1 point left to go, or since the unit doesn't have enough movement left to traverse the third tile, it is stopped on the second tile and the remaining movement point goes unused. Now what happens if the units movement is 4 and it has to travel across the same 3 tiles. Where does it sit at the end of its turn? Is it on the second tile, or the third?

These are game design decisions. Does a unit have to move the full cost to be considered on that tile? Or is the unit considered on a tile if it has spent any movement points in that tile. Also, are all movement points spent each turn, or if the unit can not spend the full cost of movement on the next tile, then the remaining movement points are dumped and the turn ends?

If you are allowing a unit to spend all movement points, you can have a variable like `traveledSoFar` which holds the movement units spent on a tile at the end of a turn.

So, back to your question, your pathfinding should give you a list of way points, in your case, one tile, after another, leading to the objective. At the start, pull the first way point, after traveling through it, pull the next way point from the list. Do this until you have exhausted your movement points for that unit. Then on the next turn resume where you left off.
> 4 votes

---
Tags: libgdx, ai, path-finding, turn-based, strategy
---


# Question
Title: Changing Ogre3D terrain lighting in real time
I'm looking at the Ogre 3D library and I'm browsing through some examples / tutorials. My question is about terrain. There are a few examples showing how great the terrain system is, but I think that the global illumination and shadows of the terrain have to be pre-computed, which kinda makes it impossible to integrate this with a day / night cycle.

Is there a way to change the terrain light sources in real time? If so it is possible to do it and keep a decent FPS?

# Answer
Ogre's TerrainComponent does support a single directional light, in addition to real-time shadows.

However, these will be of lower quality (and potentially, lower performance), than the pre-baked lighting and shadows. And if you opt for pre-baked, then dynamic lighting is not typically an option.
> 1 votes

# Answer
There's one topic on their wiki stating a material generator for deferred shading for terrains, you could take a look on that and see if it is good for your uses.

http://www.ogre3d.org/tikiwiki/tiki-index.php?page=Deferred+Terrain+Material+Generator
> 1 votes

---
Tags: lighting, terrain, ogre
---


# Question
Title: How to handle the different frame rate on different devices?
I am not quite sure how frame per second works on a web page. I have a Canvas game that involves in moving an image from point A to B, and measuring the time elapsed. The code can be as simple as:

```
var timeStamp = Date.now();
function update(){
  obj.y += obj.speed;
  text = "Time: "+ (Date.now() - timeStamp) + "ms";
}

```

The function update() is called every frame. The problem is that the time elapsed is different from device to device. It is pretty short on my PC, but get longer on my iPad, and is much longer on my cell phone. I thought it is because the FPS is smaller on mobile devices, so instead of calling update() every frame, I call it every 1ms by using a setInterval. But this does not solve the problem.

In my understanding, the function for setInterval is invoked based on the increment in system time, other than frame rate, so it should fix the problem. Am I missing anything here? If the setInterval function is called based on FPS, is there any way to get around with the FPS difference across devices?

On a side note, I have sort of a "water simulator" on the same canvas. It involves in redrawing about 60 objects which can be 600x600 pixels for every frame, so it could be a frame rate killer. I am using Phaser.js but not really using much of its functionalities, if that helps.

# Answer
As far as I know, is 60 frames per second only, and you don't have access to the delta time. If you want to simulate 30fps for example, you could skip the `update()` every second frame. Read more here: http://www.html5gamedevs.com/topic/2959-how-to-set-fps-to-30/

It is therefore up to you to make sure that every frame runs within 16ms (1000 / 60) so that things appear smooth, across all devices, otherwise the engine begins to lag. If you want to have better control over such things, it's probably better to try a different framework or maybe a faster language than javascript.

By the way, there's no need to calculate frame rate yourself; phaser has the `Time class` which (when `advancedTiming` is enabled) has fields like `fps`, `frames`, and `elapsedSince()` for you to monitor the performance of your game.
> 3 votes

---
Tags: html5, frame-rate, phaser
---


# Question
Title: C++: Checking if an object faces a point (within a certain range)
I have been working on a shooter game in C++, and am trying to add a feature whereby missiles shot must be within 90 degrees (PI/2 radians) of the direction the ship is facing. The missiles will be shot towards the mouse. My idea is that the ship's angle of rotation is compared with the angle between the ship and the mouse (std::atan2(mouseY - shipY, mouseX - shipX)), and if the difference is less than PI/4 (45 degrees) then the missile can be fired. However, I can't seem to get this to work. The ship's angle of rotation is increased and decreased with the A and D keys, so it is possible that it isn't between 0 and 2\*PI, hence the use of fmod() below.

Code:

```
float userRotation = std::fmod(user->Angle(), 6.28318f);
if (std::abs(userRotation - missileAngle) > 0.78f) return;

```

Any help would be appreciated. Thanks!

# Answer
The easiest way to check if an object faces a point is to use to compare the angle of normalised vectors, in your case, the normalised forward vector of the ship and the normalised fire vector.

To get the forward direction of the ship you can do the following. Assuming the ship is facing down X+ axis when the ship angle is 0, the forward vector is equal to:

```
forward.x = cos(shipAngle);
forward.y = sin(shipAngle);

```

And the fire vector:

```
fireVector.x = mouseX - shipX;
fireVector.y = mouseY - shipY;
fireVector = normalise(fireVector);

```

You can then use the vector dot product to get the angle.

```
float dotProduct = dot(forward, fireVector);

```

Compare the angle between 0 and 90 degrees.

```
if( dotProduct >= 0.0f )
    Fire();

```

By using normalised vectors we can use the fact that the dot product returns the cosine of the angle. As cos(90) = 0 we compare if the dot product is greater or equal to 0 before firing.
> 2 votes

---
Tags: c++
---


title: Creating a top-down spaceship

text:
# Question
Title: Creating a top-down spaceship
I'm creating a top-down 2D space game in LIBGDX for android.

When spaceship is going forward it will look like this:

when it goes upward I want to change it's direction with a nice animation so it seems like a real spaceship. A between frame would be like this:

I have rendered the spaceship in different Z axis degrees from ship0 to ship90. Calculating rotation on XY plane wouldn't be so hard, but I don't know how to calculate the rotation on Z axis so I can choose the right sprite to use.

# Answer
> 1 votes
When you starts going upwards you can start counting X from 0 to 90. For example you can increase X by 1 every 16 ms (for example). Then you can use X to use appropriate shipX frame.

When you stop going upward then decrease X from current value to 0 (for example 2 by every 16 ms). Then the ship should back to its prime position softly.

---
Tags: 2d
---


# Question
Title: XNA: Camera's Rotation and Translation matrices seem to interfere with each other
I've been following the guide here for how to create a custom 2D camera in XNA. It works great, I've implemented it before, but for some reason, the matrix math is throwing me off.

```
public sealed class Camera2D
{
    public Vector2 Origin { get; set; }
    public Vector2 Position { get; set; }
    public float Scale { get; set; }
    public float Rotation { get; set; }
}

```

It might be easier to just show you a picture of my problem: https://i.stack.imgur.com/5lTLI.png

What I want to do is allow the camera to pivot around any given point. Right now, I have the rotations mapped to my shoulder buttons on a gamepad, and if I press them, it should rotate around the point the camera is currently looking at. Then, I use the left stick to move the camera around. The problem is that after it's been rotated, pressing "up" results in it being used relative to the rotation, creating the image above.

I understand that matrices have to be applied in a certain order, and that I have to offset the thing to be rotated around the world origin and move it back, but it just won't work!

```
public Matrix GetTransformationMatrix()
    {
        Matrix mRotate = Matrix.Identity *
            Matrix.CreateTranslation(-Origin.X, -Origin.Y, 0.00f) *  // Move origin to world center
            Matrix.CreateRotationZ(MathHelper.ToRadians(Rotation)) * // Apply rotation
            Matrix.CreateTranslation(+Origin.X, +Origin.Y, 0.00f);   // Undo the move operation

        Matrix mTranslate = Matrix.Identity *
            Matrix.CreateTranslation(-Position.X, Position.Y, 0.00f); // Apply the actual translation

        return mRotate * mTranslate;
    }

```

So to recap, it seems I can have it rotate around an arbitrary point and lose the ability to have "up" move the camera straight up, or I can rotate it around the world origin and have the camera move properly, but not both.

# Answer
Though Fault's comment is correct, what I usually do is to store the rotation and translation and then recreate the view matrix when required. (Full article here).

The gist of the idea is: (btw the type of camera you are creating is often referred to as an Arc-Ball camera.)

```
public class ArcBallCamera
    {

    public ArcBallCamera(float aspectRation, Vector3 lookAt)
        : this(aspectRation, MathHelper.PiOver4, lookAt, Vector3.Up, 0.1f, float.MaxValue) { }

    public ArcBallCamera(float aspectRatio, float fieldOfView, Vector3 lookAt, Vector3 up, float nearPlane, float farPlane)
    {
        this.aspectRatio = aspectRatio;
        this.fieldOfView = fieldOfView;
        this.lookAt = lookAt;
        this.nearPlane = nearPlane;
        this.farPlane = farPlane;
    }

    /// <summary>
    /// Recreates our view matrix, then signals that the view matrix
    /// is clean.
    /// </summary>
    private void ReCreateViewMatrix()
    {
        //Calculate the relative position of the camera
        position = Vector3.Transform(Vector3.Backward, Matrix.CreateFromYawPitchRoll(yaw, pitch, 0));
        //Convert the relative position to the absolute position
        position *= zoom;
        position += lookAt;

        //Calculate a new viewmatrix
        viewMatrix = Matrix.CreateLookAt(position, lookAt, Vector3.Up);
        viewMatrixDirty = false;
    }

    /// <summary>
    /// Recreates our projection matrix, then signals that the projection
    /// matrix is clean.
    /// </summary>
    private void ReCreateProjectionMatrix()
    {
        projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, AspectRatio, nearPlane , farPlane);
        projectionMatrixDirty = false;
    }

    #region HelperMethods

    /// <summary>
    /// Moves the camera and lookAt at to the right,
    /// as seen from the camera, while keeping the same height
    /// </summary>
    public void MoveCameraRight(float amount)
    {
        Vector3 right = Vector3.Normalize(LookAt - Position); //calculate forward
        right = Vector3.Cross(right, Vector3.Up); //calculate the real right
        right.Y = 0;
        right.Normalize();
        LookAt += right * amount;
    }

    /// <summary>
    /// Moves the camera and lookAt forward,
    /// as seen from the camera, while keeping the same height
    /// </summary>
    public void MoveCameraForward(float amount)
    {
        Vector3 forward = Vector3.Normalize(LookAt - Position);
        forward.Y = 0;
        forward.Normalize();
        LookAt += forward * amount;
    }

    #endregion

    #region FieldsAndProperties
    //We don't need an update method because the camera only needs updating
    //when we change one of it's parameters.
    //We keep track if one of our matrices is dirty
    //and reacalculate that matrix when it is accesed.
    private bool viewMatrixDirty = true;
    private bool projectionMatrixDirty = true;

    public float MinPitch = -MathHelper.PiOver2 + 0.3f;
    public float MaxPitch = MathHelper.PiOver2 - 0.3f;
    private float pitch;
    public float Pitch
    {
        get { return pitch; }
        set
        {
            viewMatrixDirty = true;
            pitch = MathHelper.Clamp(value, MinPitch, MaxPitch);
        }
    }

    private float yaw;
    public float Yaw
    {
        get { return yaw; }
        set
        {
            viewMatrixDirty = true;
            yaw = value;
        }
    }

    private float fieldOfView;
    public float FieldOfView
    {
        get { return fieldOfView; }
        set
        {
            projectionMatrixDirty = true;
            fieldOfView = value;
        }
    }

    private float aspectRatio;
    public float AspectRatio
    {
        get { return aspectRatio; }
        set
        {
            projectionMatrixDirty = true;
            aspectRatio = value;
        }
    }

    private float nearPlane;
    public float NearPlane
    {
        get { return nearPlane; }
        set
        {
            projectionMatrixDirty = true;
            nearPlane = value;
        }
    }

    private float farPlane;
    public float FarPlane
    {
        get { return farPlane; }
        set
        {
            projectionMatrixDirty = true;
            farPlane = value;
        }
    }

    public float MinZoom = 1;
    public float MaxZoom = float.MaxValue;
    private float zoom = 1;
    public float Zoom
    {
        get { return zoom; }
        set
        {
            viewMatrixDirty = true;
            zoom = MathHelper.Clamp(value, MinZoom, MaxZoom);
        }
    }

    private Vector3 position;
    public Vector3 Position
    {
        get
        {
            if (viewMatrixDirty)
            {
                ReCreateViewMatrix();
            }
            return position;
        }
    }

    private Vector3 lookAt;
    public Vector3 LookAt
    {
        get { return lookAt; }
        set
        {
            viewMatrixDirty = true;
            lookAt = value;
        }
    }
    #endregion

    #region ICamera Members
    public Matrix ViewProjectionMatrix
    {
        get {return ViewMatrix * ProjectionMatrix; }
    }

    private Matrix viewMatrix;
    public Matrix ViewMatrix
    {
        get
        {
            if (viewMatrixDirty)
            {
                ReCreateViewMatrix();
            }
            return viewMatrix;
        }
    }

    private Matrix projectionMatrix;
    public Matrix ProjectionMatrix
    {
        get
        {
            if (projectionMatrixDirty)
            {
                ReCreateProjectionMatrix();
            }
            return projectionMatrix;
        }
    }
    #endregion
}

```
> 2 votes

---
Tags: xna, 2d, camera, matrix
---


title: Animation in top down 2d

text:
# Question
Title: Animation in top down 2d
How is this usually done? Especially when the character might need to use different animations, for instance at his hands and legs. I noticed some skeletal animation solutions but they were only applicable to platformer games. Any ideas?

# Answer
Animations like in the Minishcap that you showed as an example are generally done frame by frame because rotated body parts just would not look right at that perspective. You could experiment by drawing frame difference frames (i.e. your animation frames aren't full pictures of the character, they just show the difference between the last frame and the current frame, sort of like how videos work), to save space, although this could be negligible depending on the size of the character.

Generally, unless the game's perspective can make other approaches work, 2D animation is done frame by frame.
> 0 votes

---
Tags: animation
---


title: 10% idle time in WebGL

text:
# Question
Title: 10% idle time in WebGL
I'm using `requestAnimationFrame` to handle my frame rate in a WebGL game, and running through the Chrome profile shows that a solid 10% of the time is spent in `(idle)`. Why is that? How can I reduce this time, that, unless I'm misunderstanding, is just wasted?

I'm using raw WebGL. Here's part of my rendering code:

```
Animator.prototype.tick = function() {
  window.requestAnimationFrame(util.bind(this.tick, this));
  if (this.paused) return;
  this.advanceWorld();
  this.drawScene();
};

```

Full code at: https://github.com/nickgeorge/quantum/blob/master/animator.js

# Answer
False alarm here, it turned out to just be an artifact of how I was pausing/unpausing the game to profile it. It turns out I got a lot more accurate data by using the chrome built-in profiling api, with a function like

```
profile = function(t) {
  Animator.getInstance().unpause();
  console.profile();
  setTimeout(function(){
    console.profileEnd();
    Animator.getInstance().pause();
  }, t*1000);
};

```
> 1 votes

# Answer
Idle - is "doing nothing" (that is not bad though).
As you run your game with consistent frame rate, in ideal world requestAnimationFrame will do 60 frames a second. Your game logic + rendering might take less than ~16ms (60 frames a second), then the left over time will be considered "idle".

It is not bad, but good: means you have some reserve in terms of processing power. In fact 10% of idle is quiet low and around 0% - will hit your 60 frames performance boundary and frames will drop. Especially on mobile, that will just lead to quick battery drain, and low performance. Different hardware and software performs differently.
> 3 votes

---
Tags: webgl
---


title: Anti-Aliasing in OpenGL [C++]

text:
# Question
Title: Anti-Aliasing in OpenGL [C++]
I'm trying to make anti-aliasing work inside of OpenGL, here's what I've tried:

```
glEnable(GL_POINT_SMOOTH);
glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);
glEnable(GL_LINE_SMOOTH);
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
glEnable(GL_POLYGON_SMOOTH);
glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

```

But so far none of these have worked.

I have gotten antialiasing to work by enabling it on the control panel for my video card (Catalyst Control Center in my case), but I would like to get it working inside my program instead.

1. This is what the rendering looks like with 4x antialiasing enabled via the video card control panel:
2. And this is what it looks like when I do it with my program:

How do I get antialiasing to work?

# Answer
To get better results you will need to check for MSAA (http://www.opengl.org/wiki/Multisampling)

Define how many samples you want for Anti-Aliasing in **WGL\_SAMPLES\_ARB** attribute passed to the function **wglChoosePixelFormatARB** (for Windows).

You can find code for that here :

http://nehe.gamedev.net/tutorial/fullscreen\_antialiasing/16008/

This paper is also worth reading for Anti-Aliasing :

http://www.cse.iitb.ac.in/~paragc/teaching/2009/cs475/notes/antialiasing\_sumair.pdf
> 5 votes

---
Tags: opengl, c++, antialiasing
---


# Question
Title: How do you map a texture to a sphere in Unity using script?
I am looking to map a texture to a sphere inside of Unity using c# (not in the visual editor)?

dragging a jpg or other image resource onto the sphere is the effect I am looking for -- but I would like to do it at runtime.

# Answer
> 2 votes
This is actually pretty simple. All you need to do is change the Material property of the sphere's renderer.

Simply place the Texture you'd like to use at runtime within your Resources folder. Then you can do the following:

```
Texture2d runtimeTexture = (Texture2d) Resources.Load("Textures/YourTexture");
Material runtimeMaterial = new Material(Shader.Find("VertexLit"));
runtimeMaterial.maintexture = runtimeTexture;
//assuming sphere is a GameObject or Monobehavior
sphere.renderer.material = runtimeMaterial;

```

# Answer
> 1 votes
Raven's answer, while correct, doesn't really explain the underlying concept you need to understand. Textures aren't technically applied to meshes directly; instead, Textures are assigned to Materials, and then Materials are assigned to Meshes. Thus you either need to change the texture assigned to the material that's assigned to the mesh, or (as in his code) assign a different material to the mesh.

(incidentally, dragging an image onto a mesh in Unity is actually a shortcut to generating a new material. Notice how a new material is created when you do that? What's happening is Unity creates a material, assigns the texture to that material, and then assigns that material to the mesh. You could also create a Material yourself and do it all explicitly.)

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


# Question
Title: How to calculate directional light frustum from camera frustum
I'm playing around with OpenGL for a few weeks now.

For the following screenshot I picked the glm::ortho values for my lightsource by trial and error. There are two directional light sources with shadows.

I would like to calculate the values for glm::ortho by creating a bounding box around the camera frustum.

I have the corners of the camera frustum in world space ... what is the next step? I think I should move the camera frustum into light space, calculate the bound box and put the dimensions of that bounding box into glm::ortho. But ... how? :)

The block below is a simplified version of my code with only one light source.

```
// Camera
mat4 cameraViewMatrix = lookAt(
    vec3(1.2f, 1.2f, 1.2f),
    vec3(0.0f, 0.0f, 0.0f),
    vec3(0.0f, 0.0f, 1.0f)
);

mat4 cameraProjectionMatrix = perspective(45.0f, 800.0f / 600.0f, 0.5f, 10.0f);

// Light
mat4 lightViewMatrix = lookAt(
    vec3(3.0f, -2.0f, 2.0f),
    vec3(0.0f, 0.0f, 0.0f),
    vec3(0.0f, 0.0f, 1.0f)
);

// Camera Frustum
vector<vec4> cubeNDC;
cubeNDC.push_back(vec4(-1.0f, -1.0f, -1.0f, 1.0f));
cubeNDC.push_back(vec4(1.0f, -1.0f, -1.0f, 1.0f));
cubeNDC.push_back(vec4(1.0f, -1.0f, 1.0f, 1.0f));
cubeNDC.push_back(vec4(-1.0f, -1.0f, 1.0f, 1.0f));
cubeNDC.push_back(vec4(-1.0f, 1.0f, -1.0f, 1.0f));
cubeNDC.push_back(vec4(1.0f, 1.0f, -1.0f, 1.0f));
cubeNDC.push_back(vec4(1.0f, 1.0f, 1.0f, 1.0f));
cubeNDC.push_back(vec4(-1.0f, 1.0f, 1.0f, 1.0f));

mat4 viewProjectionMatrixInverse = inverse(matProj * matView);

vector <vec4> cameraFrustum;
for(vec4 vertex: cubeNDC) {
    vec4 vertexTransformed = viewProjectionMatrixInverse * vertex;
    vertexTransformed /= vertexTransformed.w;
    cameraFrustum.push_back(vertexTransformed);
}

// Magic

mat4 lightProjectionMatrix = ortho(...);

```

Thanx for your help. :)

# Answer
> 2 votes
Okay. Seems like you just want a single light-camera.
But there are many different approaches. Like using multiple frustum splits (which means multiple light-cameras), which is called "Cascaded Shadow Mapping". Even the way you construct the frustum of your light-camera to encompass the main camera's frustum can be done in various ways.

**First some useful links:**

**Building the matrix:**

How I'd go about the very simple case you have:
You have an orthographic projection for your light-camera. So your frustum is just an Oriented Bounding Box (OBB). That means you can simply feed its world space coordinates (like the width and height) to glm::ortho().

But how do you construct the OBB around the frustum?
Good question. ;D

Here's a simple approach:
First determine the direction of your light (as a normalized vector). Now simply project every vertex of your main-camera's frustum onto that vector and find the nearest and furthest one (simply store the distances along the vector). Now subtract the two distances.
Congratulations! You already have your OBB's depth (Z).
Now repeat that process for the other two vectors. One pointing upwards or downwards (Y) and the other to the right or left (X) relative to your light-camera. Now you have your OBB's orientation (the three vectors) and dimensions. Now simply pass the OBB's dimensions to glm::ortho() and then transform the orthographic matrix so it has the same orientation as your OBB.
You're done. :D

**Projecting a point onto a vector:**
This step is actually very easy. Just take the dot product between your vector and your point (both stored as vec3).
Example code:

```
float distance_on_vector = dot(p, vector);

```

**Vector** should be normalized, because you need the world-space distance. You don't need the actual position of **p** in world space (you just need the projected length) to calculate the dimensions of the OBB. That's why the above code is enough.

**Some free optimization tips:**

* If you do it with the above approach, you already get your three basis vectors. That means glm::ortho() actually becomes quite useless. All you have to do is scale the basis vectors and translate them. Done is your light-camera's projection matrix.
* GLM is not really fast... But don't get me wrong. It's a very good library.

(damn... this answer took me quite some time...)

---
Tags: opengl, lighting, glm
---


# Question
Title: Movement on tile map when player is the size of 4 tiles, moving in 1 tile increment
I understand how to move a square around a tile map: you have a coordinate of the square (say the center), and if they player press the "up" arrow, just increment the y-coordinate by 1.

**Question:** How should I think about tile based movement when the player is the size of 4 squares, and still moves in 1 square increment? E.g. if the player get into a tank, and the tank is now a 2 by 2 block. Would it be significantly different?

I suppose I would have to keep track of the 4 tiles my player's tank is in. And when he presses "up", I would have to check if the forward 2 tiles are empty, then increment all 4 tiles' y-coords by 1.

# Answer
Yes, you'll want to define an "origin" tile for the player (for example, the top-left of his 2x2 set of tiles) and interpret the player's position as being the position of that origin tile.

You will then want to take the tile size of the player's avatar into account when determining if it can be moved to a partition position. For example, if you have a board like looks like

```
....#
.X..#
....#
#####

```

and the `X` represents the position of the player's origin in the world (which is the upper-left of his 2x2 sprite), then the player can't move down even though there is technically a one tile gap between the origin and the wall (represented by the `#` characters). On screen, the player might actually look like

```
....#
.XX.#
.XX.#
#####

```

when rendered.

The good news is that this is easily generalizable so a 1x1-sized entity can use the same code path as a NxM-sized entity: you only need to track the entity's position in the world and the size, in tiles, of the sprite.

If your system provides you the ability to specify entity positions in non-integer / non-tile values, you can simply use the exact center of the sprite as the origin, as it can simplify things just a bit.
> 5 votes

---
Tags: tiles, movement
---


# Question
Title: Vertex shader in OpenGL/GLSL - transformation of the interior of a textured quad
I have a LWJGL project and ran into a problem with a vertex shader I wrote. In my scene I am rendering a map whose ground consists of rectangular tiles. On top of that there are other objects (I used tiny white balls here). Here is a screenshot of my scene:

screenshot of my scene http://110.imagebam.com/download/0-Ktu6XjdWSMpKytTr3Trg/34736/347358711/scene\_static.jpg

You can also click here to see the image.

Each of the four larger rectangles at the bottom is one huge quad drawn in one piece. Every one of them contains four coordinates (the corners: top-left, top-right, bottom-right, bottom-left). Their interior is filled with a texture.

The small white balls on top are single game objects each drawn by itself. Note that I aligned them with the vertical edges of the underlying rectangles.

I used the following vertex shader to render the scene:

```
/* default shader */
#version 120

void main()
{
    gl_TexCoord[0] = gl_MultiTexCoord0;
    gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}

```

---

Now imagine the scene getting covered with water. I modified the shader adding a little water effect:

```
/* water shader */
#version 120

uniform float amplitude;
uniform float phase;

void main()
{
    gl_TexCoord[0] = gl_MultiTexCoord0;

    // transform x
    vec4 a_position = gl_Vertex;
    a_position.x = a_position.x + amplitude * sin(phase + a_position.x);

    gl_Position = gl_ModelViewProjectionMatrix * a_position;
}

```

An animated image of my scene can be found here or here.

You can see that the borders of the rectangles keep aligned with the white balls on top of them. However, vertices inside the rectangles (I marked the most distinct areas red) suffer a displacement relative to the white balls. In the last rectangle you can even see the balls cross the white line in the middle.

---

I need the interior of my textured rectangles to be transformed exactly like the white balls on top and move uniformly when being animated by my shader. Please let me know if my problem is clear and if any other information is needed.

Thank you very much for your help. Greetings Xoric

# Answer
> 2 votes
From your original equation

```
a_position.x = a_position.x + amplitude * sin(phase + a_position.x);

```

We'll just be taking at look at the sin portion as this is where this effect comes from

```
sin(phase + a_position.x);

```

Let's look at the sin function over a half of a period for different positions (phase is in degrees)

```
Position 1 - a_position.x = 0
sin(0 + 0) = 0
sin(45 + 0) = .707
sin(90 + 0) = 1
sin(135 + 0) = .707
sin(180 + 0) = 0

Position 2 - a_position.x = 1
sin(0 + 1) = 0.0175
sin(45 + 1) = .719
sin(90 + 1) = 0.9998
sin(135 + 1) = .695
sin(180 + 1) = -0.0175

Position 3 - a_position.x = 2
sin(0 + 2) = 0.0349
sin(45 + 2) = .731
sin(90 + 2) = 0.9993
sin(135 + 2) = .682
sin(180 + 2) = -0.0349

```

With each increment of the a\_position.x we're almost slowly changing the phase that the sin function is actually using. This is what gives you that expanding and contracting water effect. The problem with this is that it is also what's causing the alignment issues between your quad and the rest of the balls.

Your quads are defined by their vertices which are aligned by the balls. Because the vertices are at different positions their phase is different and so move out of phase from each other causing the quad to grow and shrink. The actual midpoint of the quad can be calculated using the two vertices and simplified to just the sin portion to get

```
sin(phase + pos1) + sin(phase + pos2) / 2

```

Where if you wanted the middle to match up, it'd have to be equal to the ball closest to that which would have an equation which simplifies to its sin portion of

```
sin(phase + posBallMiddle)

```

The first one is dependent upon two positions, not just one like the second equation. The only way you'd get it to line up is if the vertices were one or more periods apart. This means a solution is limited by what you can change elsewhere (lining up the objects with the quad through other means, making sure to keep the rectangles are a certain width based on your period, or something else). Otherwise, you'd need a different equation to model your water.

---
Tags: opengl, textures, glsl, vertex
---


# Question
Title: Move Particle to touch position on android
I am attempting to make a Particle start moving to the position of my finger on the touch of the screen.

I have been using this as the basis so far:

```
public void update()
{
    deltaX *= .9;
    deltaY *= .9;

    this.x += this.deltaX;
    this.y += this.deltaY;
}

public void moveTo(int newX, int newY)
{
    float dx = newX-this.x;
    float dy = newY-this.y;

    float length = (float) Math.sqrt(dx*dx+dy*dy);

    dx/=length;
    dy/=length;

    dx *= 10;
    dy *= 10;

    deltaX = dx;
    deltaY= dy;
}

```

now while it does move the Particle, it is rarely in the direction of my finger. How can I make the particle have the correct amount of velocity to get to the position of my finger, but no farther?

Thanks in advance!

# Answer
> 0 votes
To make a particle track your finger motion you first need to track at least two different events in `onTouchEvent()`, and possibly a third depending on what you want to happen when you lift your finger. You need to check for `MotionEvent.ACTION_DOWN` and `MotionEvent.ACTION_MOVE`, and possibly MotionEvent.ACTION\_UP. The first event you will set the initial target location, and the second event will tell you where to alter the target location to. If you want to particle to travel to the last location of your finger after you lift it you can just ignore MotionEvent.ACTION\_UP.

```
@Override
public boolean onTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN ||event.getAction() == MotionEvent.ACTION_MOVE) {
        particle.moveTo(event.getX(), event.getY());
    } else if (event.getAction() == MotionEvent.ACTION_UP) {
        // add code here if particle behavior changes on finger lift
    }

```

This should make sure the particle has the correct trajectory. Whether or not it has the correct velocity is harder to say without knowing more about how you are controlling the timing of the animation. If you have a fixed time delta then the code you have should be fine. If your delta time between animations frames if variable then you should be factoring this into your update function.

Also, you can calculate the rotation angle of the particle in the moveTo() code if needed.

```
pubic void moveTo(int newX, int newY) {
    float diffX = newX - this.x;
    float diffY = newY - this.y;
    float length = (float) Math.sqrt(diffX*diffX+diffY*diffY);
    float normalizedX = diffX/length;
    float normalizedY = diffY/lenght;

    float angle = (float)Math.acos(normalizedX);
    if (diffY > 0.0f) {
        rotation = (float)Math.toDegrees(angle);
    } else {
        rotation = (float)Math.toDegrees(-angle);
    }

    deltaX = normalizeX * 10;
    deltaY = normalizedY * 10;
}

```

---
Tags: android, particles, touch
---


# Question
Title: Does Unity have a built in pathfinding system?
I know that there a lot of plugins available for pathfinding in unity but I was just wondering if unity has a built in pathfinding system ?

# Answer
> 2 votes
Yes Unity does have a built in pathfinding system. Though there are a few features of the navmesh system that are pro only, like dynamic obstacles, avoidance priority configuration for navmesh agents, and off mesh links.

Byte56 provided a link to the written documentation. Here is the official video tutorial unity released: https://www.youtube.com/watch?v=mP7ulMu5UkU

# Answer
> 2 votes
Yes. You'll find resources for the Unity path finding system by searching for "Unity Navigation Meshes". You can find the documentation for it here

---
Tags: unity
---


title: Compute billboard rotation

text:
# Question
Title: Compute billboard rotation
I'm trying to compute a matrix to have object always facing the camera. For the moment, my result look pretty good, the problem is that my original billboard scale isn't preserved (Every billboard have a size of 1/1).

**Here is what I've done using this post:**

```
glm::vec3 look = glm::normalize(camera->getPosition() - objectPosition);
glm::vec3 right = glm::cross(up, look);
glm::vec3 up2 = glm::cross(look, right);
glm::mat4 transform;
transform[0] = glm::vec4(right, 0);
transform[1] = glm::vec4(up2, 0);
transform[2] = glm::vec4(look, 0);
transform[3] = glm::vec4(objectPosition, 1);

glm::quat q = glm::quat_cast(transform);
objectTransformable->setOrientationFromQuat(q);

```

I've tried to add something like that but the result is a bigger object with bad proportion:

transform = glm::scale( transform, objectScale );

To resume, I would like to extract orientation from result matrix to apply it on my transform object, something like Unity:

```
MyTransform.LookAt(Cam.transform.position, upVector);

```

# Answer
historically billboards matrix just copy the camera view matrix, and replace the last row with their own world position. the scale can be world-fixed if you want trees or hard stuff.
But it can also be screen-fixed for halo effects, in which case you need to scale using the euclidian distance. this can be done in the vertex shader rather than on CPU as an object matrices preparation step. but it doesn't matter much which way is used.

note that using the view matrix partial copy, you will get distortions on the border of the screen caused by perspective projection. another approach to mitigate that is to rotate the billbord so that it faces the view point. This is actually what you are doing right now in the code posted abode. because you use the "eye -\> billboard" ray as a base for the matrix.
> 2 votes

---
Tags: c++, mathematics, sprites, glm, billboarding
---