# Question
Title: Conceptual - What is the optimal way to combine steering behaviors with rigid body physics?
I am working on a simple 3D space simulator that makes use of the Bullet physics engine. The spaceships are rigid bodies that have a mass and hitbox so that they can be considered for collisions. At the same time, I am trying to implement simple steering A.I. as detailed in numerous tutorials across the web. However, all of these tutorials assume zero-size points in 2D space with no orientation.

For the most part, I have succeeded in implementing the behaviors by applying a force to the rigid body in the direction of desired steering. The spaceship moves, turns, and accelerates smoothly and correctly navigates to the desired position in 3D space:

```
currentVelocity = body.getLinearVelocity();
tempVector = body.getWorldTransform().getTranslation();
desiredVelocity = targetPosition.sub(tempVector).normalize().scale(maxVelocity);
steeringForce = desiredVelocity.sub(currentVelocity);

body.setGravity(steeringForce); *[see footnote]

```

However, the spaceship does not change its orientation at all. The problem I am trying to solve is simple - **to make the spaceship face in the direction that it is currently travelling.**

From my research, it seems that simply setting the orientation of the object to face the direction of its velocity is really bad when using a physics engine because it may cause a rigid body to become stuck inside another one. On the other hand, using a more realistic navigation system based on thrusters is prohibitively (and needlessly) complex because the number of spaceships will be very high.

What is the best way of overcoming this problem?

Edit: Also of note is that the Bullet physics library does not allow setting the orientation of a body.

\**Note: I used the function setGravity() instead of applyForce() as suggested by an admin at the Bullet physics forums because applying a force is dependent upon frame-rate. On the other hand, gravity is applied evenly according to Bullet's simulation steps, not to mention that gravity otherwise unused in a space simulator.\*

# Answer
As a mechanical engineer whose also interested in game development I appreciate how difficult this problem can become; anything more than the naive solution I am about to describe requires a sound understanding of control systems.

**Simple Solution**

I am developing a 2d game where players have control over a spaceship (approach should work just as well for AI ships in 3d). I can get the ship to smoothly change directions if I **apply the force (thrust vector) to a point slightly in front of the center of mass of the ship**:

The above gif is just me pressing combinations of `A``S``D``F` to change the desired heading. When the game updates it applies a pre-defined thrust force to the ship's 'thrust point' in the direction of the heading vector. This is what the white line is showing.

If and when you implement this you can scale back the thrust force as the ship gets closer to the destination as you have already been doing.

Notice that, at the end of the gif, I do a ~180 degree turn to face downward. This shows (IMO) the only problem with this approach: the ship rotates slowly at first, then 'snaps' downward and overshoots the desired angle. The true behaviour of a ship with thrusters would be to circle around and gradually orient the ship towards the desired heading, which can't be achieved with this approach. For my game this departure from realism is acceptable, but for you it may not be.

This system can be tuned by changing:

* The thrust magnitude
* The moment of inertia of the ship (density and/or shape)
* The angular damping coefficient of the ship
* The linear damping (drag) coefficient of the ship
* The distance between the 'thrust point' and the center of mass

Here ends the core of my answer. However, I feel the following discussion is necessary to shed light on the complexity of a more sophisticated control system.

**Sophisticated Approach**

When working with basic (single-input, single-output (SISO)) control systems, it is often sufficient to manually tune the critical parameters, such as the proportional, integral, and derivative gains manually by changing relevant properties (density, thrust power, angular damping, etc...) manually to subjectively determine what 'feels right'.

The current problem has *multiple* output variables: 2 angles describing the orientation, and 3 vector components describing position. To maneuver in 3d space you must have at least three independently functioning thrusters (*multiple* input variables). This is what is known as a multiple-input, multiple-output (MIMO) system. When working with MIMO systems, it is possible adjust input parameters 'by feel' as before without knowing mathematical relationships between the input and output variables, but there are two issues (that I can see):

1. The number of control parameters can become very large. For each parameter you add, you can spend exponentially more time figuring out how changing each parameter affects the output variables given various combinations of the other parameters.
2. Some (or all) of the control parameters will influence multiple output variables (e.g. distributed mass influences both the linear and angular acceleration of the ship), so those variables will be very difficult to tune.

The wikipedia article above should give you a good intro to MIMO systems. I have also found this presentation to be a good introduction.

**My Advice** would be to go with something simple (just try and control one variable). I haven't found any documentations online of MIMO systems for video game design to copy and learn from. If anyone has found some resource of this nature, please comment.
> 4 votes

---
Tags: 3d, physics, libgdx, bullet-physics, steering-behaviors
---


title: libGDX SpriteBatch reuse

text:
# Question
Title: libGDX SpriteBatch reuse
Using libGDX, sprites or simply texture regions must be inserted into the batch for drawing:

```
void render()
{
    batch.begin();

    batch.draw(...);

    batch.end();
}

```

Is the VBO being uploaded to the GPU in every frame? Is there a way to reuse the batch once any of the data changed?

# Answer
LibGDX already binds the textures for you under the hood: Texture.java

For 99% of cases you can just let the SpriteBatch draw everything for you; it does so with very good efficiency. I would suggest referring to the extensive documentation on the wiki.

Additionally, if you use the AssetManager, textures will be re-bound even after an OpenGL context loss.

Regarding "re-using" the batch, the same SpriteBatch can render every frame as long as you are calling begin() and end(). You shouldn't create more than one SpriteBatch.
> 2 votes

---
Tags: java, libgdx, spritebatch
---


title: How to glow a UIButtons in sequence

text:
# Question
Title: How to glow a UIButtons in sequence
I am working on a memory based matching puzzle game. For that I need to glow buttons in a sequence that's generated randomly.

I am glowing the buttons by changing its background images. I'd like to get the buttons to glow in a randomly defined sequence, then have the player enter that sequence in.

Game Screen for better understanding

After flashing of coloured light

How do I properly glow the buttons from the sequence?

# Answer
Any one looking for answer can check this link

Hope it helps someone

Thanks all for concerns and suggestions :)
> 0 votes

# Answer
*Okay, I'm assuming you've got general issues with game logic and how to implement it properly (i.e. it not working as expected). If that isn't the case, let me know and I'll remove this again.*

While I can't help you with the actual code implementation, from what I got from your code you might have chosen an implementation strategy, that makes it slightly more difficulty than actually required.

The following is to be considered pseudo code. I'm pretty sure you should be able to get it working though:

* First of all, you'll need one array or list (or some other collection) supporting either FIFO or full random access.
* To start you generate the pattern and fill your array. In my example I'm going to use a character array:

```
char solution[256];

for (int i = 0; i < solution_length; i++)
    solution[i] = rand() % number_of_buttons;

```
* This gets me an array with the solution. For simplification, let's say we've got the buttons one through four, then the array could contain `1, 2, 3, 4`, which would essentially mean that the solution is hitting the buttons in exact that order.
* Checking player input and playing the animation now are pretty much similar. You'll either need some index (to know which entry is next) or you drop the very first entry in your list (which might be problematic in case you'd like to repeat a pattern upon failure; you could just work with a copy as well though).
* Basically, wen it's time to light up a button, you have a look at the array to see what's the next button. In the example above, first will be `1`, so your code triggers the first button lighting up. Then your index is moved to the second entry (or the first entry is dropped altogether).
* Now you're having a look at the next entry, which would be `1` again (and after this it would be `3`).
* You just keep repeating this process.
* If you're lighting up the buttons, once you reach the end you're done.
* If you're checking player input and you reach the end, the player has won. If some entry doesn't match the input, you know that the player used the wrong key.
* Organizing the game logic like this makes it rather easy to implement different game modes. For example, your *rapid mode* simply won't wait forever for the player to hit a button. If they don't tap in time, you just assume failure - done.
> 2 votes

---
Tags: iphone, puzzle, memory
---


# Question
Title: How to smooth the model/texture look from a distance?
*(First of all, I really didn't know how to title my question so it tells exactly what I mean so if anyone has a better title feel free to edit my question or leave a comment.)*

Look at the water in the screen:

See all the annoying white pixels? That's the specular. It looks nice up close:

But when I move the camera away from water it starts to look bad. Actually, the same problem occurs elsewhere (e.g. with grass or rocks) but it's not as bad as with the specular.

I think I know why it looks the way it does but I don't know how to make it look better, more smooth, something like this:

Well, blur helps but blur is an expensive post-process and it's not the way I want to do it.

How can I make it look better, less pixelated and more natural?

Edit: I mentioned that I have the problem with e.g. grass. The grass' shader only uses a texture. The water's shader, however, uses normal mapping and based on the mapped normal it calculates light's specular component.

Update: Following Tording's advice I've used NVIDIA DDS plugin to generate mipmapped normal map DDS file and I've used that instead in my project. Although I'm not sure if I prefer the result to the previous one:

I realize that my normalmap texture and/or my water shading technique might be to blame, though. :P **But my point is - using mipmapping might solve my problem (a lot of sharp pixels/noise) but it also introduces new problems.**

# Answer
This is called mipmaping, It looks like you are missing out on mipmaping for your textures. this causes a huge impact on visuals. And when it comes to mipmaping Normals, Specular and other "information" textures, it gets quite tricky.

the reason for this is that when objects gets further away, the gpu has to take this into account and calculate the corresponding texel. So, in practice, it will start skipping bigger pieces of your huge texture because it cant map it to the relative size. The mipmap is the solution to this since the gpu then knows how to handle those faraway pixels since it got a down scaled version of your texture. And now the problem of having textures with information ( Like normals ) is that, when you are scaling down, you are effectively averaging the values of four neighboring pixels. which can cause incorrect values for normals for example. For plain color it´s okay, but not with information.

My best experiance with this has been to use the DDS plugin for Photoshop that nvidia have made. it´s fully free and REALLY efficient.

This is the link to DDS plugin

Other than that, you could create some sort of distance function to your shader that knows when you are further away to take a bigger sample area of your water plane.

here is an link that you can read about mipmaps on wiki, it´s really good explaining on whats going on. MIPMAPING wiki link
> 6 votes

---
Tags: pixel, mipmaps, specular
---


title: WebGL wrong scaling of rectangle

text:
# Question
Title: WebGL wrong scaling of rectangle
I'm working with this tutorial http://www.html5rocks.com/en/tutorials/webgl/webgl\_transforms/

and my result is, that the rectangle moves in the direction of it's scaling values, and also scales at the same time. So if I scale (2.0, 1.0) it moves right and stretches, but I only want to strecht/scale it. This is my vertex shader, it is nearly the same as in the tutorial (declarations omitted):

```
void main(void) {
vec2 scaledPosition = a_position * u_scale;

vec2 rotatedPosition = vec2(
    scaledPosition.x * u_rotation.y + scaledPosition.y * u_rotation.x,
    scaledPosition.y * u_rotation.y - scaledPosition.x * u_rotation.x);

vec2 pos = rotatedPosition + u_translation;

vec2 zeroToOne = pos / u_resolution;
vec2 zeroToTwo = zeroToOne * 2.0;
vec2 clipSpace = zeroToTwo - 1.0;

v_texCoord = a_texCoord;

gl_Position = vec4(clipSpace, 0, 1);
}

```

What could be the mistake if it is not in the shader? Thanks in advance.

# Answer
> 1 votes
Vertex shader goes through each vertex individually, and applies maths to it.
Here you take position of your vertices, and multiply it by scale. That means if you multiply X by 2.0 (scale), then when you move all vertices right in vertex buffer by 2.0 in shader it will turn into 4.0 (as you multiply then).

What you really want is to have position of entity, and then position of vertices expressed by vertex buffer.
Then you will scale vertices the way as you do, but then will add position of entity (vec2 in your case) to move object around.
So vertex position will be local and scale will be so.

Some pseudo code (for shader):

```
scaled_vertex_position = vertex_local_position * scale;
scaled_and_rotated_vertex_position = ..rotate..;
final_vertex_position = scaled_and_rotated_vertex_position + entity_position;

```

---
Tags: opengl, javascript, graphics, webgl
---


# Question
Title: Way to avoid excessively bright objects with specular lighting?
I have a typical Phong shading with specular light. I have all the parameters tuned so to give appropriate highlights from a point light source. Now the problem I have is a new object that has a large flat surface which tends to face directly towards the light source (which is a bit offset from the camera). It also has a normal map which is primarily in one direction (steel panels). This results in a pure white object.

I have a lot of options to try and work around the problem, but I was wondering if this is a common issue and perhaps there is a clean workaround. The various options I see (and am trying) are:

* Reduce specular map intensity. There are two problems here, first when the object is not facing the camera it looks dull, second on a low quality setting I don't use specular maps.
* Clamp the range of specular light. This of course limits the highlights for the entire scene. It also limits the highlights when the object isn't facing the camera.
* Put a per-object specular light limit. This at least doesn't affect the whole scene, but does dullen this object when not facing the camera.

# Answer
> 2 votes
I've seen many variants of lighting code over the years, 90% of the time it just comes down to artistic tweaking, either the specular power, or the specular colour to gain the desired effect (and balancing that with the diffuse colour and ambient).

I've also seen a few cases where the specular factor is additionally multiplied by the diffuse factor as well.

But ultimately if you have a bright specular colour, and a low power, or a very distant point with no fall off (basically a directional light) you'll always get 'lit up' when the normal is close to the half-vector between your view/light vectors. Think of solar panels on a satellite or glass-fronted buildings.

Also be sure to look at Blinn-Phong instead of pure Phong as the specular effect is subtly different for reflections off of objects at an angle to the viewer.

---
Tags: glsl, lighting
---


# Question
Title: What is the component for the AI system in a component-based entity implementation?
In order to wrap my head around component-based systems, I started making my own little framework. Unfortunately I am not completely sure how systems are supposed to be used in some specific cases.

For example I can understand the use of a `RenderSystem` or a `CollisionSystem` but how would one implement AI and how would the component look like? I am especially confused when it comes to actions. Could actions be stored in the components as objects?

# Answer
> I am not completely sure how "systems" are supposed to be used in some specific cases.

However you *need* them to be used. There is no single correct way to build a component-based entity system (not all of them even include the concept of a "system"), and even among implementations that use similar terminology, not all the details are alike.

You need to focus on building the system that accomplishes the goals you have set for your project.

> How would one implement AI and how would the component look like? I am especially confused when it comes to actions. Could actions be stored in the components as objects?

AI in games is about the modeling of behavior more than anything else. Interfaces that implement AI on a per-entity basis (entity system or not) are typically called "agents" or "actors," and typically contain code or data to control behavior of an individual creature/person/NPC/object/et cetera in the game. With that in mind, a common way to put AI into a component-based entity system is to have `BehaviorComponent` (or `AgentComponent` or `ActorComponent`, et cetera) which are associated with entities. Such a component implements an entire class of behavior for an entity and *generally* you don't attach multiple (although you could). For example, you might have an `FollowPlayerBehavior` component or an `AttacksFromCover` component.

In many games, "AI" typically just means executing behavior scripts, so often you won't even see dedicated AI systems or components since such behavior is normally just handled by more general scripting components that allow designers to attach arbitrary Lua (or whatnot) scripts to entities.

I would *not* recommend an approach where you implement individual actions an entity can take as components and shove a bunch of them on to an entity, as that is too fine-grained and doesn't afford you the ability to easily order the actions without enforcing an overly-rigid update order on your entity component system. It also makes branching decisions difficult, and implies you're going to do a lot of adding and removing of components at runtime which isn't always very common (and thus not always very efficient).

As always, the specifics of what goes into an "AI component" are going to depend heavily on your game itself: what it needs from AI, how your AI works in absence of the component system (the component system, remember, is a high-level object composition system and something like AI, rendering, physics should all be usable *without* also requiring the use of the component system; keeping that in mind will help you design better systems that work in isolation and help avoid the design paralysis that so often comes with building component systems for some reason).
> 8 votes

---
Tags: entity-system, entity-component
---


# Question
Title: How do I convert the coordinates of a click to a tilemap position?
How do you turn a tilemap (produced by TileD) for cocos2d where I can click on individual items and get a callback?

Is it just a case of converting captured touch and finding out where it is on the tilemap and then converting that to pixels -- but that doesn't say what item was clicked on.

I have a tilemap of a city with buildings on it, and I'd like to be able to click or press on a specific building, get a callback.

What would be the best way to accomplish this?

# Answer
I think you're getting your *pixel coordinates* and *tilemap coordinates* confused.

*Tile coordinates* count tiles.

*Pixel coordinates* count pixels.

To convert from a pixel coordinate to a tile coordinate, divide the `click_x` by the tile `w`idth and the `click_y` by the and tile `h`eight, to get the tile coordinates `x` and `y`. (Discard the remainders to get an integer.)

The reason this works is pretty clear if we overlay the two coordinate systems:

In this above case, the pixel coordinates of the click would correspond to `6,4` in tile coordinates.

Once you know what tile position a click corresponds to, it should be trivial to find the contents of that tile.
> 3 votes

---
Tags: cocos2d-iphone, tilemap, touch
---


# Question
Title: How to project spherical coordinates to canvas
I have objects with coordinates in a spherical coordinate system (altitude alt and azmiuth az). I want to project those to my canvas with a given size (128 x 128 pixels²) and resolution (about 6 px/°).

The canvas looks at the sphere from the inside and can be rotated in alt, az and around its normal. The canvas normal direction is known in the same coordinate system as the objects, and the view is centered around that canvas' center.

How do I find an object's x and y position on the canvas? I know this is almost the same as an orthogonal (or similar) map projection, but the examples I found all have a view fixed at alt = 0. That's not what I have here, and I'm having difficulties figuring this out.

I can not use any ready-made projection tools, as I'm programming an embedded system. The existing questions here at gamedev seem to be centered around frameworks that provide such functionality.

---

As DMGregory pointed out, I need a simple perspective projection matrix for a gnomonic projection. Wikipedia also has an article about perspective (camera) projection, I'll try to implement that and see if it does what I need.

# Answer
> 3 votes
In games, we often work with a variety of coordinate spaces. Geometry is defined in **model-space**. Different objects don't have to share the same model space. Coordinates are then converted to **world-space** using a transformation matrix. Usually this is just a combination of translation and/or rotation matrices, but can also include things like scaling, or even non-affine transformations.

Usually everything in the scene is considered to exist in the same Cartesian world-space. Another transformation is then used, called the **view transform** representing the position and orientation of the camera. This results in **eye-space** (also known as camera space), a Cartesian space where the Z axis represents the direction the camera is "looking".

Up until now, we haven't taken into account the nature of the camera or eye's lens. Cameras generally attempt to image the world in the same way as the human eye, using something called rectilinear perspective projection. We use another matrix for this step, called the **projection transform**. Now, a perspective projection can't be implemented entirely using only a 4x4 tranformation matrix. We also need another step, called the **perspective divide** where we divide the X, Y, and Z coordinates by W to make distant objects smaller. This gives us what we call **normalized device coordinates** (NDC) which are usually multiplied with the width and height of our canvas to yield **screen-space** (technically this is called the **viewport transform**).

On top of all this, in games we have other things to worry about. Normals may need to be transformed differently than points and tangents, and we often need to be able to reverse all of the above operations, for instance, to know what the player clicks on. The list could go on, but none of that sounds like it is applicable to your situation.

If you want it to look like you're inside a sphere looking at it's inside surface\*, the model transform converts from spherical to Cartesian world coordinates (You can't actually do this with a transformation matrix, but the formulas are availble here). The view transform rotates the camera, and the the projection transform handles the perspective calculations. The latter two can be combined into a single 4x4 matrix. Then you just multiply that matrix by each vertex after converting to Cartesian coordinates - but don't forget the perspective divide and viewport calculation!

---

\*In this case, this is known as a Gnomonic projection. (Thanks DMGregory!)

---
Tags: coordinates, transformation, sphere
---


# Question
Title: How to make a smooth circuit path in Universal tween engine?
I tried to make a circuit by starting at point A, with waypoints B and C and final target at A again, and infinite repeats. What happens is that the path from A to B, B to C is smoothed, but path C to A ends with a "sharp" edge

Is there any way to make it totally smooth?

# Answer
When dealing with splines, how your interpolation works at a point is determined by the continuity of the spline at that location.

This will vary depending on the type of spline you are using but at the very least you want your incoming and outgoing tangents to have the same direction at point A.

If you make sure the tangents are also the same length at that point, then you will also have constant velocity through point A as well as a smooth direction.

Assuming you can't change the tangents manually (catmul-rom splines for example that work entirely from the positions of the points) then if you replace A with a set of points so that you have two points at the start and two points at the end all lying on the same line, then your tangents between the final point and A will have the same tangent.

Note: A and F are at the exact same position as each other. B and E lie on the same line through A/F and are some small distance apart - exaggerated in the image for effect, the distance in reality can be quite small)
> 1 votes

# Answer
As long as your smoothing function only relies on 3 points (this, next and prev) you can just ensure that your loop has more than 3 points for it to work seamlessly for a loop.
> 0 votes

---
Tags: libgdx, tweening
---


# Question
Title: In Android, is saving game data in a binary file a good approach?
I am nearly finished with my Android game, but I want to make sure my save format is good. I am working on a fairly large game, so data such as high scores, stars, etc. are stored for around 80 levels, along with data for purchased items. Currently I save this data sequentially in a binary file. So when I need to load it, I have to go through all of the previous data to get to the data that I actually need. It seems to work fine, but I question how well this format will hold up for game updates. Is this is a bad approach to take? I considered using SQLite, but after trying to implement it into my game it didn't seem very effective. Updates seem as if they would be even more complicated.

# Answer
How much is all your data? If all your achievements and stars fit within 1 MB, you'll be pretty much safe to save all this in one binary blob.

I would avoid easily-readable formats like XML, because this allows your players to read and edit anything they like, like getting through levels and get the stars they don't deserve.

Something like binary format, compressed with `zip` if you care about the size and encrypted if you care about the security would work just perfectly.
> 0 votes

# Answer
A human-readable format like XML would likely make debugging the data easier. However, binary data is generally much faster. It really depends on how often you are reading and writing the data, and how much data you are loading and saving.

If you have a small amount of data, you should just consider keeping all of the data in memory while the game is running and only reading from the file when the app is started.
> 1 votes

---
Tags: android, data, savegame
---


title: assets access with index offsets

text:
# Question
Title: assets access with index offsets
My question if about resource management. Is it a good idea to store resources like Sounds in an array and then make a second array(lets call this SoundCollections) as a sort of reference table(name + index of sounds array).

The SoundCollection structure looks like this:

```
struct SoundCollection{
    unsigned char name[64];
    unsigned int offset;
    unsigned int count;
};

```

GameObjects can aqcuire a SoundCollectionHandle and use the `SoundCollection[SoundCollectionHandle].offset` in the `Sounds` array. `GameObjects` then can call

```
Audio.playsound(Sounds[SoundCollection[SoundCollectionHandle].offset + PlayerSounds::Jump])

```

for playing a jump sound.

The `SoundCollection::count` is used as offset for next `SoundCollection` and bound checking. The same thing I want to use for Sprites and Textures.

Are there any other methods you usually use in your games?

# Answer
> 0 votes
There's absolutely no reason to store your sounds into the same array, since you need to devise an elaborate scheme to get them back. Basically you cannot make it smaller, because your sounds take the most space, and indexes make it only bigger. You cannot make things go faster, because additional level of indirection does not make thing go smoother.

You'd be much better off saving every sound into its own file and into its own array and them have them called explicitly by name.

---
Tags: c++, data-structure, assets, asset-management, dataflow
---


# Question
Title: Can I use quaternions and do a partial multiplication?
I have some code that rotates an object around an axis. It does this by creating a quaternion for a rotation and then multiplying by the old orientation:

```
nextRot = QuaternionRotationAxis( axis, rotSpeed * elapsed )
newOrient = QuaternionMul( oldOrient, nextRot )

```

This need to create the rotation quaternion each time seems like it may be redundant. Is it possible to somehow create a quaternion and somehow apply `elapsed` to it? That is I would prefer code like this:

```
nextRot = SomeOp( fullRotationQuat, elapsed )

```

In this way I can store `fullRotationQuat` in my object and simply apply it partially on each time step.

I know that if I apply `nextRot` twice, it would be like doulbing the ellapsed time. So I'm guessing I might want some kind of quaternion exponentation. Is this a define op? More importantly, is its performance still acceptable (or faster) than creating from an axis/angle each time?

# Answer
> 2 votes
If the axis is fixed, then you can directly construct the orientation quaternion by supplying that axis and the angle. The angle argument is then the only one that changes, just like you want.

If your `elapsed` factor is constant as well, then you may consider storing the incremental rotation as a quaternion and multiply the old quaternion by this new one each frame (should be faster than evaluating `sincos`).

In terms of performance, creating a quaternion from angle axis is not a bad idea, but if you can avoid trigonometric functions and square roots, then by all means do it.

As to your "bonus" question on whether it makes sense to think of an exponential operator on the quaternion space, your hunch is right. The only problem I see with this operator is that it's not going to help you in this particular case since it resolves to actually extracting the rotation axis from the quaternion and then building it back again. For more details, consult this short article http://web.mit.edu/2.998/www/QuaternionReport1.pdf . It is here where the properties of the `log` and `exp` are explained for quaternions. But their applications usually involve quaternion calculus or storing compressed animation tracks in more complex game engines.

---
Tags: mathematics, quaternion
---


title: How to animate two interacting objects

text:
# Question
Title: How to animate two interacting objects
I'm not very familiar with animations but as far as I know, most of the animations are done frame by frame. For example animating a character walking etc. However, let's imagine this scene:

There's a man coming from the left towards the sign. It's easy to animate this. But when he comes to the sign, he picks it up and starts waving with it. Now this is something I don't know how to do. What is generally the recommended way to do this kind of animation (two separate objects)? Specifically we're talking about android live wallpaper here (probably made with libgdx but I can use anything if it's better for me).

# Answer
If you use skeletal animation it is quite trivial - your just attach your signpost to your character hand bone, and your engine does the rest. Assuming you use 2d frame-per-frame animations, well, you shouldn't. This is a case where that approach simply fails. Workarounds like defining a hand position in your animation file, and then attaching your sign to that are just complicated, and essentially trying to do the same as skeletal animation.
Btw, that there are 2d skeletal animation libraries available, like Spine for libgdx(and other engines).
> 0 votes

---
Tags: android, animation
---


# Question
Title: Calculating Per Vertex Normal in Geometry Shader
I am able to calculate normals per face in my Geometry Shader but i want to calculate per vertex normal for smooth shading. My Geometry shader is

```
#version 430 core
layout ( triangles ) in;
layout ( triangle_strip, max_vertices = 3 ) out;

out vec3 normal_out;
uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;

uniform mat4 modelTranslationMatrix;
uniform mat4 modelRotationXMatrix;
uniform mat4 modelRotationYMatrix;
uniform mat4 modelRotationZMatrix;
uniform mat4 modelScaleMatrix;

void main(void)
{
    // Please ignore my modelMatrix and NormalMatrix calculation here
    mat4 modelMatrix = modelTranslationMatrix * modelScaleMatrix * modelRotationXMatrix * modelRotationYMatrix * modelRotationZMatrix;
    mat4 modelViewMatrix = viewMatrix * modelMatrix;
    mat4 mvp = projectionMatrix * modelViewMatrix;
    vec3 A = gl_in[2].gl_Position.xyz - gl_in[0].gl_Position.xyz;
    vec3 B = gl_in[1].gl_Position.xyz - gl_in[0].gl_Position.xyz;
    mat4 normalMatrix = transpose(inverse(modelViewMatrix));
    normal_out = mat3(normalMatrix) * normalize(cross(A,B));
    gl_Position = mvp * gl_in[0].gl_Position;
    EmitVertex();
    gl_Position = mvp * gl_in[1].gl_Position;
    EmitVertex();
    gl_Position = mvp * gl_in[2].gl_Position;
    EmitVertex();
    EndPrimitive();
}

```

Since i don't have access to adjacent faces here, i cannot calculate per vertex normals.
**How can i calculate per vertex normals in my Geometry Shader?**

# Answer
> 2 votes
You can't do this if you want smooth shading.

Calculating per-vertex normals involves calculating per-triangle normals, then averaging those normals (optionally giving each a weight) for each triangle that shares a given vertex.

So you need additional information that you just don't have: which triangles share each vertex.

As you will see from a diagram of triangles-with-adjacency (below), even that isn't sufficient to calculate per-vertex normals. Take the vertex numbered "2" in the image below; it should be obvious that there could be any arbitrary number of triangles that also share this vertex but which aren't in the adjacent set.

You'll have to calculate them on the CPU and add an additional input attribute, I'm afraid.

---
Tags: opengl, shaders, geometry-shader
---


# Question
Title: How do I find the intersection of a ray and a cylinder?
I'm looking for the algorithm to find the intersection (or lack of) between a ray and a cylinder. I have rotating coin like objects in my game world and need to check for a collision on that object. I also need to know the location of intersection to determine which part of the coin was hit.

The cylinder has an arbitrary rotation. I can provide as input the direction (vector) it is facing, a centre point, and a radius.

For the ray I can generalize to a line, as it'll be easy to check within the segment afterwards. Ideally I'd like the array to be an infinite cylinder, but I can easily fudge this aspect once I have the collision for a line.

# Answer
> 8 votes
This breaks into two distinct pieces: testing collisions against the endcaps, and testing collisions against the body of the cylinder.

The simplest way to handle both is to first transform your way into object space — the ideal 'object space' for a cylinder is with the origin at the center of one endcap and one axis (for concreteness' sake, we'll say the Z axis) running along the 'body' of the cylinder, orthogonal to the endcap planes. In this space, your cylinder is then a pair of discs of radius R in the xy plane, capping a cylinder that runs from z=0 to z=L.

To intersect the ray with one endcap, then, you need to find the point on your ray where it intersects the xy plane: assuming that your ray's equation is **r**(t)=**r0**+**d**\*t (I'm using boldface here for vector quantities), then by solving rz(t)=0 for t, you find t=-(r0z/dz) (note that this breaks down if dz=0; in other words, if your ray is parallel to the xy-plane. In that case, you can skip the endcap test and just test against the cylinder, along with a check to make sure that r0z is between 0 and L). (Similarly, if you were trying to intersect with the z=L endcap, you'd find t=(L-r0z)/dz ). Plugging this value of t into your ray equation then gives you a point **p** where the ray intersects the plane of the endcap; now you just need to test whether this point is within your disc or not - in other words, whether px2+py2 ≤ R2.

Testing against the body of the cylinder works similarly, but is a bit more complicated: in this case, you'll *project* your ray down to the 2d plane (since we're working in object coordinates, this is as simple as dropping the z component of your ray equation — you can see why these coordinates are so useful!) and then doing a 2d line-circle intersection: essentially you want to find the points where |**r**xy(t)|2=R2 (here **r**xy(t) is the ray equation 'projected' down to the xy plane by dropping the z component); this equation is just a quadratic in t, and you can solve it for the two possible values of t. One big caveat, though: once you find the two values of t that solve the equation (and note that there may be none, which means that your ray doesn't intersect the cylinder at all), you'll have to plug them back into your original equation to make sure the corresponding z values fall in the 0..L range.

Finally, you'll have (up to) four distinct t values: the two possible intersections with the endcaps, and the two possible intersections with the sides of the cylinder. (Of course, in practice there can only be two, but that's a separate matter). Just choose the smallest of these that's greater than zero, and that's your intersection point.

# Answer
> 1 votes
Ray intersection usually starts with a faster check against the bounding box of the cylinder, before you do the more expensive check against the cylinder geometry. Either way, it boils down to a line-plane intersection test (since the cylinder is comprised of a bunch of polygons, which are themselves bounded planes).

The math for that is explained here (hope you're good at math!) http://geomalgorithms.com/a05-\_intersect-1.html#Plane-Intersections

(incidentally I'm assuming you need to do the math from scratch and aren't using a framework with raycasting already in it, since you don't mention that)

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


# Question
Title: Is a game engine actually needed to make games?
I see Game engines like Ogre are just software wrappers or software systems to enable easier access to certain features provided by other programmers that are relevant to game development.

However, isn't it true that no game engine is needed to program games at any scale?

# Answer
You are correct. There is no need to use an engine to make your game. But in many cases it's just a matter of "why reinvent the wheel?"

There are for example frameworks such as lib gdx that abstracts away the most low level OpenGL stuff, so that you can focus on the things that actually matter.

I really recommend this blogpost by Dennis Gustafsson to get an insight in to what frameworks and engines does for you! It also gives some insight into what you really have to do if you want to cram out the last bit of performance from the hardware you are working with, which often is the reason some people stay away from "real engines". http://tuxedolabs.blogspot.se/2013/01/development-environment.html

With all this said, if it makes you excited to write things from the ground up, you should absolutely try it!
> 1 votes

---
Tags: software-engineering
---


title: Trouble getting shadow maps working

text:
# Question
Title: Trouble getting shadow maps working
I am trying to implement shadow maps in my game following this tutorial. For some reason, the light is not being occluded.

In the above screenshot, the big white sprite in the foreground is a rendering of what the occlusion map looks like. In the background, you can see the result does not produce any shadows. It's hard to see, but in the top left it shows the shadow map.

Enlarged version of the shadow map:

The occlusion map and the shadow map seem to be generating correctly, so it must be an issue with how I'm taking it into account when rendering the light. Here is the fragment shader for the light:

```
#version 330

uniform sampler2D uDiffuseTexture;
uniform sampler2D uNormalsTexture;
uniform sampler2D uShadowMap;

uniform vec4 uLightColor;
uniform float uConstAtten;
uniform float uLinearAtten;
uniform float uQuadradicAtten;
uniform float uColorIntensity;

uniform vec4 uAmbientColor;

in vec2 TexCoords;
in vec2 GeomSize;

out vec4 FragColor;

float sample(vec2 coord, float r) {
    return step(r, texture2D(uShadowMap, coord).r);
}

float occluded() {
   float PI = 3.14;

   vec2 normalized = TexCoords.st * 2.0 - 1.0;
   float theta = atan(normalized.y, normalized.x);
   float r = length(normalized);
   float coord = (theta + PI) / (2.0 * PI);

   vec2 tc = vec2(coord, 0.0);
   float center = sample(tc, r);

   float sum = 0.0;

   float blur = (1.0 / GeomSize.x) * smoothstep(0.0, 1.0, r);

   sum += sample(vec2(tc.x - 4.0*blur, tc.y), r) * 0.05;
   sum += sample(vec2(tc.x - 3.0*blur, tc.y), r) * 0.09;
   sum += sample(vec2(tc.x - 2.0*blur, tc.y), r) * 0.12;
   sum += sample(vec2(tc.x - 1.0*blur, tc.y), r) * 0.15;

   sum += center * 0.16;

   sum += sample(vec2(tc.x + 1.0*blur, tc.y), r) * 0.15;
   sum += sample(vec2(tc.x + 2.0*blur, tc.y), r) * 0.12;
   sum += sample(vec2(tc.x + 3.0*blur, tc.y), r) * 0.09;
   sum += sample(vec2(tc.x + 4.0*blur, tc.y), r) * 0.05;

   return sum + smoothstep(1.0, 0.0, r);
}

float calcAttenuation(float distance) {
    float linearAtten = uLinearAtten * distance;
    float quadAtten = uQuadradicAtten * distance * distance;

    float attenuation = 1.0 / (uConstAtten + linearAtten + quadAtten);

    return attenuation;
}

vec3 calcFragPosition(void) {
    return vec3(TexCoords*GeomSize, 0.0);
}

vec3 calcLightPosition(void) {
    return vec3(GeomSize/2.0, 1.0);
}

float calcDistance(vec3 fragPos, vec3 lightPos) {
    return length(fragPos - lightPos);
}

vec3 calcLightDirection(vec3 fragPos, vec3 lightPos) {
    return normalize(lightPos - fragPos);
}

vec4 calcFinalLight(vec2 worldUV, vec3 lightDir, float attenuation) {
    float diffuseFactor = dot(normalize(texture2D(uNormalsTexture, worldUV).rgb), lightDir);

    vec4 diffuse = vec4(0.0);
    vec4 lightColor = uLightColor * uColorIntensity;

    if(diffuseFactor > 0.0) {
        diffuse = vec4(texture2D(uDiffuseTexture, worldUV.xy).rgb, 1.0);
        diffuse *= diffuseFactor;
        lightColor *= diffuseFactor;
    } else {
        discard;
    }

    return (uAmbientColor + diffuse + lightColor) * attenuation;
}

void main(void) {
    vec3 fragPosition = calcFragPosition();
    vec3 lightPosition = calcLightPosition();

    float distance = calcDistance(fragPosition, lightPosition);
    float attenuation = calcAttenuation(distance);

    vec2 worldPos = gl_FragCoord.xy / vec2(1024, 768);
    vec3 lightDir = calcLightDirection(fragPosition, lightPosition);

    lightDir = (lightDir*0.5)+0.5;

    float atten = calcAttenuation(distance);
    FragColor = calcFinalLight(worldPos, lightDir, atten) * vec4(vec3(1.0),
    occluded());
}

```

# Answer
Okay, I have solved the problem. The problem was that I wasn't binding the shadow map to a correct texture attachment.
> 0 votes

# Answer
I think the problem is this line, at the end of `occluded()`:

```
return sum + smoothstep(1.0, 0.0, r);

```

That probably should be just

```
return sum;

```

In the tutorial, the line uses the `smoothstep` call for attenuation (and also multiplies by it, but I'm guessing that's just a transcription error on your part). You have your own attenuation, so it seems like you'd want to just leave that out.
> 0 votes

---
Tags: opengl, 2d, glsl, shadows, deferred-rendering
---


title: Frustum culling vs draw calls

text:
# Question
Title: Frustum culling vs draw calls
In a more performance-sensitive environment than a desktop CPU/GPU (namely a mobile device) is there really a point in determining whether or not to skip drawing non-visible objects vs reducing the number of draw calls?

I'm working with a scenario of an environment model that has ~10,000 triangles. I could split it up into 30 or so separate mesh such that less than half of those would be visible at any given point. However, would ~15 draw calls be more efficient than vs one draw call for all 10,000 triangles?

# Answer
Why is this a *versus* question? One of those things usually follows from the other. Also, 15 draw calls are not terribly expensive. If you are in a scenario where you would be able to collapse those 15 draw calls into 1 then you obviously do not have (***m***)any state changes between the draw calls. The states you do have to change are probably just vertex buffer states, and those are very cheap compared to things like changing render targets.

In modern graphics APIs it is the states you change between draw calls (*particularly the validation that follows*) that make them expensive. In D3D9 on Windows XP, each draw call lead to a kernel-mode switch irrespective of the states changed and that added a fixed amount of time to each draw call that is no longer relevant. D3D10 / Windows Vista (WDDM) addressed this problem by creating a user-mode component to the Direct3D driver to more efficiently handle command batching and also by reducing the amount of validation by shifting much of it to resource creation time.

You will probably have to profile your solution to come up with any definitive answer, but draw calls themselves are not the enemy.
> 1 votes

---
Tags: directx11, performance, culling, frustum-culling
---


# Question
Title: How do I import service references to Unity3D?
I'm attempting access a service reference in Unity. I need two: the SOAP framework and a separate service called `ContentVault`.

The respective service URL's are:

Both services import fine in to Visual Studio. I've tried everything I can think of but they won't work with Unity. I just get various errors (changing depending on which solution I'm trying out).

I've attempted using `svcutil` to export the services as external scripts, but all I got was a bunch of using errors. I've tried converting the code to work with .NET 2.0 to no avail, I've even tried making the services in to .DLL's to no success.

How could get these services working with Unity?

# Answer
If you are getting NotImplementedException exceptions, then you are likely out of luck.

Unity uses Mono, and, sadly, Mono is not a full implementation of the .net framework.

There are many features of .net that have not been added to Mono yet.

BasicHttpBinding is one of those features that has not been added.

I've had some limited success with named pipe bindings and I know of others that have successfully used tcp/ip bindings.

Much of WCF doesn't work with Unity, which is a huge let-down!

For more info on what is implemented from System.ServiceModel and what isn't, you could check this page:

http://go-mono.com/status/status.aspx?reference=4.0&profile=4.0&assembly=System.ServiceModel

Keep in mind, for this to ever get implemented, it would first have to be added to Mono and then Unity would have to adopt the new version of Mono.
> 1 votes

---
Tags: unity, .net, dll, plugin
---


title: Gradle desktop build not finding assets

text:
# Question
Title: Gradle desktop build not finding assets
Whenever I run my game using the DesktopLauncher I am able to find my files, but if I build an executable using Gradle I get an error that the files are not within the specified folder.

This may be linked to the fact that for some reason the assets I place into the Android project's asset folder, which is linked to my Desktop project, are being placed in the bin folder of my Desktop project. Currently to get around this I have a check that looks for whether I am executing as an Android game or Desktop (and applies a prefix accordingly, either "bin" or "").

# Answer
You shouldn't be doing that check in your game code about whether to append the "/bin" folder path. Are you using the function `Gdx.files.internal()` for accessing the files in your asset directory?
> 1 votes

---
Tags: libgdx
---


# Question
Title: OpenGL 2.0 - How to swap buffers for color picking
I'm trying to reproduce color picking on iOS, following the technique described here: http://www.lighthouse3d.com/opengl/picking/index.php3?openglway2, with OpenGL ES 2.0.

When the user touches the screen, I need to draw the objects on a buffer different from the one displayed on the screen, which seems to be done by glRenderMode(GL\_SELECT); how could i do the same with OpenGL ES 2.0?

Should I create a support buffer as described here? https://developer.apple.com/library/ios/documentation/3DDrawing/Conceptual/OpenGLES\_ProgrammingGuide/WorkingwithEAGLContexts/WorkingwithEAGLContexts.html#//apple\_ref/doc/uid/TP40008793-CH103-SW6

Thanks for any suggestion,

DAN

# Answer
> 2 votes
Yes you can do it that way. This is how I do color picking in iOS and it works really great. Also, I've ported my code to android using apportable and the color picker works on other devices as well.

1. Create a scratch or temp framebuffer. I create a specific color picker frame buffer. It's just like creating a dynamic texture. It's done the same way. I pick a buffer size that is square and large enough to fit the whole screen. You don't have to do it that way, but that's how I do it. Alternatively you could do one that's half size and the picker sample resolution might be good enough. You have to play with that for your app. If you need code let me know.
2. Attach a depth buffer if you need to. I do only if my 3d objects I'm picking need it.
3. Each item that you want to be pickable needs a unique color:

```
-(vec4) colorVec4FromItemID: (int)itemID
{
    if (itemID<0) {
        return vec4Make(0.0, 0.0, 0.0, 1.0);
    }
    float r = itemID % 255;
    float g = (itemID / 255) % 255;
    float b = (itemID / (255 * 255)) % 255;
    return vec4Make(r/255, g/255, b/255, 1.0);
}

```
4. I track items one of two ways. Either I have my objects in a struct array and the itemID I pass to the above method is the index number of that array. Or I keep a colorPickerID and ++ it each time I grab a color. Either way I store the color in a vec4 pickerColor in the array of struct. I avoid objective-c ns-stuff for color picking and use a c array of structs. In my games I also multiply my input id by 30 to give some space between the colors - but this probably isn't needed.
5. Render using a solid color shader. So I re-renader the pickable objects in my scene to the color picker frame buffer/texture when needed (Not every frame). I have blending off for as hard an edge as I can get. You don't want interpolated colors. And I use a shader like this:

```
 void main(void)
{
    gl_FragColor = u_baseColor;
}

```
6. That also means that I keep my shaders and support code very compatible with each other. I can flip to a solid color shader from a texture shader without having to redo a bunch of code. Then you can reuse the same draw routines for both passes. And when drawing the color picker pass I also use the exact same matrices. And if you cache them you don't have to recalc them.
7. When the user touches that's when I set `processColorPicker=TRUE`. In my drawView loop **AFTER** drawing my scene I check that bool and then (if the scene has changed) I draw the color picker and process it. Obviously don't draw the picker each frame.
8. Read the pixel:

```
-(void)processColorPicker
{
    //if (colorPickerNeedsRedrawn) {
    [self drawColorPicker];
    //}
     glBindFramebuffer(GL_FRAMEBUFFER, pickerFramebuffer);
     glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureInfo[TEX_PICKER].texture, 0);
     Byte pixelColor[4] = {0,0,0,0};
     glReadPixels(colorPickerTouchPosition.x * backingScale, (backingHeight - (colorPickerTouchPosition.y * backingScale)), 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, pixelColor);
     vec4 pickerColor = vec4Make((float)pixelColor[0]/255, (float)pixelColor[1]/255, (float)pixelColor[2]/255, (float)pixelColor[3]/255);
     NSLog(@"what is pixelColor at %f,%f = %f %f %f %f", colorPickerTouchPosition.x, colorPickerTouchPosition.y, pickerColor.r,pickerColor.g,pickerColor.b,pickerColor.a);
    ...

```
9. Interpret the read. You can see if the color matches a picker color stored in your struct or you can check each id using the colorVecFromItemID again for each item number.

Some tips: If you keep only reading `0,0,0,0` and it's not working chances are either your buffer is set up wrong or you're not really drawing to that buffer. You could always draw the texture to the screen instead of processing the color.. then you can see if the colors are drawing correctly. They'll be dark and reddish.

Also, since you're not reading from the screen but from a scratch buffer you don't have to worry about `kEAGLDrawablePropertyRetainedBacking`. That only matters if you're reading pixels from the screen buffer. Also I'm not sure Brad Larson's alternative to glRead will work for this either since I believe that only works reading from the screen.

IF you want to speed things up.. divide the size of the color picker texture by 2 or 4. The buffer will theoretically draw 4 times faster at /2 and 16 times faster at /4. Chances are you don't need a retina pixel accurate color picker buffer.

Make sure you don't start drawing to the picker buffer (or any dynamic texture) in the middle of when you're drawing to the main screen buffer. The way I do that is to not jump directly into `processColorPicker` but instead to set a bool and then do it in my drawView loop after the main buffer has been presented.

*** UPDATE \****

Here's my color picker buffer code. Note that I keep information on all my textures in a textureInfo array, including if it's been generated, the size, etc.

```
-(BOOL)createPickerFramebuffer
{
    glGenFramebuffers(1, &pickerFramebuffer);
     glBindFramebuffer(GL_FRAMEBUFFER, pickerFramebuffer);

     glGenTextures(1, &textureInfo[TEX_PICKER].texture);
     textureInfo[TEX_PICKER].generated = YES;

     glBindTexture(GL_TEXTURE_2D, textureInfo[TEX_PICKER].texture);

     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

     glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, backingWidth, backingHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);

     textureInfo[TEX_PICKER].width = backingWidth;
     textureInfo[TEX_PICKER].height = backingHeight;

    // bind renderbuffer and create a 16-bit depth buffer
    // width and height of renderbuffer = width and height of
    // the texture
     glGenRenderbuffers(1, &pickerDepthRenderbuffer);
     glBindRenderbuffer(GL_RENDERBUFFER, pickerDepthRenderbuffer);
     glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, backingWidth, backingHeight);

    // bind the framebuffer

    // specify texture as color attachment
     glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureInfo[TEX_PICKER].texture, 0);

    // specify depth_renderbufer as depth attachment - only if you need it
     glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, pickerDepthRenderbuffer);

    // test the framebuffer
     GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
     if(status != GL_FRAMEBUFFER_COMPLETE) {
         NSLog(@"***************************failed to make complete picker buffer object %x", status);
         return NO;
    }
    //else {
   //   NSLog(@"*************************** MADE complete picker buffer object %x", status);
    //}

     glBindTexture(GL_TEXTURE_2D, 0);
     glBindFramebuffer(GL_FRAMEBUFFER, 0);

     return YES;
}

```

And here's how you start drawing to it:

```
-(void) startDrawingPickerTexture
{
    // set the framebuffer to the textureFramebuffer
      glBindFramebuffer(GL_FRAMEBUFFER, pickerFramebuffer);
      glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureInfo[TEX_PICKER].texture, 0);

    // reset the viewport just in case
      glViewport(0, 0, backingWidth, backingHeight);

      glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
      glClear(GL_COLOR_BUFFER_BIT); // and GL_DEPTH_BUFFER_BIT if necessary

      glDisable(GL_DEPTH_TEST);
      glEnable(GL_TEXTURE_2D);

      glBindTexture(GL_TEXTURE_2D, 0);
    // And now it's ready and you can start rendering to it....
}

```

# Answer
> 1 votes
The answer is Yes.

Creating a temporary framebuffer is the solution and Apple's documentation is just fine.

---
Tags: ios, opengl-es2, picking
---


# Question
Title: How to randomly spawn object using instantiate
I'm trying to spawn objects which move in one direction until they hit a player or the barrier. The spawner is a cube which moves between two points to spawn the object at different locations.

The code I am using is:

```
#pragma strict
var speed : int = 1;
var direction : int = 1;
var shot : Transform;

var lastSpawn : float;
var nextSpawn : int;

function Update () {
    transform.Translate(Vector3(0, direction * speed * Time.deltaTime, 0));
    if (Time.time > lastSpawn + nextSpawn){
        Instantiate(shot, new Vector3(transform.position.x - 1, transform.position.y, transform.position.z), Quaternion.identity);
    }

    lastSpawn = Time.time;
    nextSpawn = Random.Range(1, 3);
}

```

All the prefabs and gameObjects are assigned correctly. Should this code work or am I doing something wrong?

# Answer
I am not sure to understand *completely* what is your problem.

Although, `lastSpawn = Time.time` should not be called at every frame but rather when you create a new object. I don't see a reason to have `nextSpawn = Random.Range(1, 3);` out of the braces but that should not be a problem.

```
function Update ()
{
    transform.Translate(Vector3(0, direction * speed * Time.deltaTime, 0));
    if (Time.time > lastSpawn + nextSpawn)
    {
        Instantiate(shot, new Vector3(transform.position.x - 1, transform.position.y, transform.position.z), Quaternion.identity);

        lastSpawn = Time.time;
        nextSpawn = Random.Range(1, 3);
    }
}

```
> 0 votes

---
Tags: unity, javascript, random
---


# Question
Title: What is the difference between Unity's Sprite and Texture2D classes?
Unity has both a `Texture2D` class and a `Sprite` (with related `SpriteRenderer`). What is the difference between these two classes? Both represent an image, for 2D games should I favor one over the other?

Is the main difference between the two that using `Sprite` I don't need to create the "billboard" quad myself? And that the `Sprite` is always rendered directly against the camera?

# Answer
You are correct - somewhat. Sprites, by default are rendered directly against the camera, however you can easily change this if you are using the Sprite Renderer in a 3D scene.

Sprites are physical objects in your scene, whereas Texture2D is exactly what it says it is. A texture. A texture must be attached to a material, and the material to a game object(e.g a plane).

Back in Unity 3.x days you didn't have sprite support right out of the box so you had to roll your own Sprite Manager/Class(or you had the option of buying an asset off the asset store that attempted to remedy this annoyance). Unity was really never meant to support 2D games(nevertheless developers found ways to make it happen), until 4.x, when the Unity Developers finally provided built-in support for 2D games(sprites, sprite sheets, 2D physics).

If you're doing a 2D game, always try to use the Sprite class. It's better than rolling your own, and offers more than enough.
> 17 votes

# Answer
These are some of the advantages I love about Sprite :

1. All SpriteRenderer use the same material by default, Sprite-Default even though they all have different image/atlas thus satisfying one condition of Unity's dynamic batching automatically.
2. You can apply different color tint (via SpriteRenderer's inspector) to each sprite even though they all have the same Sprite-Default material. This is not possible in Texture2D based approach which 'color' property will be tied to the material. This is also very useful for fading out sprite via alpha value of color.
3. Supports dynamic batching with non-uniform scaling.
4. Has single mode/multiple mode so you can grab each image as separate sprite from your texture atlas with the multiple mode.
5. You can grab the corner of sprite in scene view to scale or rotate it without changing to scale/rotate gizmo tool.
> 6 votes

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


# Question
Title: Drawing cube in SharpDX, wrong perspective
I want to draw a cube. This is what i currently have:

As you can see, the perspective is VERY wrong. The the size in the z-direction is too small and the difference between the front and back size is wrong.

My code:

```
worldprojMatrix = Matrix.Identity;
worldprojMatrix *= Matrix.Translation(0, 0, 10);
//float ratio = ScreenWidth/ScreenHeight;
worldprojMatrix *= Matrix.PerspectiveFovLH(1f, ratio, 1f, 100f);
//worldprojMatrix *= Matrix.RotationY(1.3f);

worldprojMatrix.Transpose();

//update the matrix with a constant buffer
DeviceContext.UpdateSubresource(ref worldprojMatrix, worldprojBuffer);

```

Vertex Shader:

```
struct VOut
{
  float4 position : SV_POSITION;
  float4 color    : COLOR;
};

cbuffer meshBuffer  :  register(b1)
{
  float4x4 worldprojMatrix;
}

VOut VShader(float4 position : POSITION, float4 color : COLOR)
{
  VOut output;

  output.position = mul(position, worldprojMatrix);
  output.color = color;

  return output;
}

```

I tried an ortho perspective, but there is the same problem: the z dimension is too small.

How can i fix that?

# Answer
> 3 votes
I don't know what vertex data you're using to draw that, but supposing it is a cube, I wouldn't say that the perspective is VERY wrong, or even wrong at all, on the left picture.

Based on your commented-out code, your ultimate view-projection matrix is getting calculated like this:

```
identity * translation * projection * rotation

```

Your drawing is getting distorted because you're rotating *after* applying the perspective matrix. Your view-projection matrix should be more like:

```
identity * rotation * translation * projection

```

Remember that matrix multiplication is not commutative.

# Answer
> 0 votes
OpenGL uses Right Handed coordinate system. But you are using `Matrix.PerspectiveFovLH` which creates a Left Handed perspective matrix. That is probably what causes the error.

---
Tags: c#, matrix, sharpdx, perspective
---


# Question
Title: Using real football player photo in a trivia quiz game, is it legal?
I don't know whether this question was already been asked before, but my team is currently developing a trivia quiz game about football (soccer not NFL). And we want to put player's images or club emblems as part of the questions and answers. My question is, is it legal? Or should we just put text without the images? Please your help is much needed. Thank you.

# Answer
> 0 votes
I'm not a lawyer but it is probably not legal -- minimally, the players did not agree to you using their portraits for your own purposes. Then you can assume that the photographer holds the copyright for the photo (or some third party does who acquired the copyright). In addition, there's a good chance that logos, emblems etc. are trademarked so you cannot use those either.

---
Tags: legal
---


title: Scaling HUD and Camera

text:
# Question
Title: Scaling HUD and Camera
I wanted to display an **HUD**, similar to the strategic games' one (like in *DotA 2, Warcraft III, Starcraft II or Age of Empires*). I didn't really know how to do it, so I managed to create a Texture Object and placed it in front of the scene. The image attached is the HUD itself, with some transparent "holes" in which I placed the cameras. I don't know if this description explains well what I'm trying to say, so I made this screenshot:

The HUD is just a *png* image with a greater z-index. The image has three "holes": one for the gameboard, one for the dice, and one for the spells you can see on the right. The holes are filled with the cameras, so we can see the objects beyond the transparency. Everything looks quite nice.

But if I change aspect ratio (which was *Free Aspect*), my layout gets completely screwed up.

Notice that the HUD borders are not fully displayed; the spells on the right are misplaced, and so are the dice.

I managed to get the free aspect resolution, it is 1440x720, a perfect 2:1. But, even if I change my resolution to 800x400, things are not getting better.

I've read something about *pillarboxing* and *letterboxing*, but I'm not sure that those techniques will help me with this issue. Is there something I can do to resize my objects and my cameras dynamically to fit the screen for every resolution like in the first screenshot?

Of course, if you have any other solutions for the HUD, I'll be glad to learn!

# Answer
> 1 votes
GUI system is THE annoying aspect of Unity3D. What missing is anchoring to camera's bound (thus anchoring to different screen size automatically) or automatic stretching according to some kind of 'panel' Here are some possible alternatives :

1. Use GUITexture/GUIText game object since the position property of that object is special : it uses 0~1 scale mapped to current screen position. But you can't do things like right-align to the edge of your screen.
2. Use third party plugins like NGUI or DFGUI. Both is one of the most grossing item on the asset store and you can also have older version (2.7.0 I think) of NGUI for free here. But some learning will be required.
3. Wait for Unity 4.6 where the promised Unity GUI will comes to light. (Also this. lol)

---
Tags: unity, hud
---


# Question
Title: TiledMap resizing and aspect ratio with LibGDX
I'm making a game and I don't know how to resize my TiledMap when the window is bigger but keeping its squared shape.

Here is a screen:

When I change window size, here's what happens:

I want to see all the map with all window sizes.

Here's my GameScreen file

http://pastebin.com/rgKgHskN

Thank you for your help and I'm sorry for those big screenshots and for my english.

# Answer
> 2 votes
LibGDX 1.0 provides what you need : Viewports.

The idea is to work with a known virtual screen size and then have it resized to fit your real screen.

I recommend you to give a look at this tutorial that explains how to handle game screen resizing with Viewports : https://github.com/libgdx/libgdx/wiki/Viewports

---
Tags: java, 2d, graphics, libgdx
---


# Question
Title: Unifying Texture-, Bump- and Lightmapping
I would like to implement a rendering component that makes use of texture-, bump- and light mapping. Unfortunately, I am a little bit stuck on some implementation details. In particular,

1. Does each different map require individual texture coordinates? (I assume at least a light map would)
2. Is there a simple file format that stores all the information needed? ( I guess .obj's are missing support for light maps)

I would be grateful for advice on this.

# Answer
Usually, for texture based lighting techniques such as normal mapping and specular mapping, the same set of texture coordinates is used, because the textures are the same, only holding different contents. See this image:

The first is the normal map, then the diffuse map (object color), then a couple specular maps. As you can note, they have the same "shape", just different colors. So the texture coordinates should be the same.

Light maps in the other hand normally use a separate set of texture coordinates, since they are images that simulate the shape of a light source projected on a surface.

As for a file format that stores information for all normal/specular/light maps, the Collada format is probably a a good place to start looking. It is a XML based format, so it is very extensive.
> 2 votes

---
Tags: textures, lightmap, bump-map
---


title: List of GLSL ES built-in variables

text:
# Question
Title: List of GLSL ES built-in variables
I am writing an article on WebGL and three.js, I'm trying to search all the built-in variables available in the vertex and fragment shader.

I've found many sites mentioning some, for example:

**Vertex Shader**

* modelMatrix
* modelViewMatrix
* projectionMatrix
* viewMatrix
* normalMatrix
* cameraPosition
* position
* normal
* uv
* uv2
* color
* gl\_Position

**Fragment Shader**

* viewMatrix
* cameraPosition
* gl\_FragColor

But I know there are more, I just can't find a resource that mentions all the built-in variables. Also, some of these variables are passed by three.js classes, I need to distinguish the built-in variables from the ones which are created by the `ShaderMaterial` class. Does someone have a list?

# Answer
Your best bet is to look at the official quick reference card for the version of OpenGL you're working with. It has a page for the shader language and shows all the variables.

I googled "opengl reference card" and found PDFs of all of them on the Khronos website. For example the one I use is for OpenGL ES 2.0 and is at:

http://www.khronos.org/opengles/sdk/docs/reference\_cards/OpenGL-ES-2\_0-Reference-card.pdf

The 1.0 WebGL PDF is at:

http://www.khronos.org/files/webgl/webgl-reference-card-1\_0.pdf

Also, I think you might be confusing Uniforms, Attributes, and Varyings with variables. The only built in OpenGL / WebGL variables would start with gl\_. All the other ones in your list are probably part of an implementation library (three.js?).
> 0 votes

---
Tags: shaders, glsl, webgl, three.js
---


# Question
Title: Making particles accelerate toward a mouse point
I'm currently working on a particle simulation program that makes pixels move towards a mouse point continually accelerating, but i'm running into some math issues. Currently my particle will accelerate in the **direction** of the mouse point, but will not actually accelerate towards a given point(only in it's direction).

To get an idea of what I'm trying to accomplish, my older program does just this but uses the fixed function pipeline. I want to recreate this program using the programmable pipeline and as a result changed around a lot of the program, there is really no similar code between the two at this point. Example of my problem:

As you can see the particle only accelerate in the direction of the cursor, my main equation I'm using is:

```
//if left mouse button is pressed
if(sf::Mouse::isButtonPressed(sf::Mouse::Left)){
        p.speed += glm::vec3(-pos.x * 30, -pos.y * 30 ,0.0f);   //increase speed in direction
}
//update position of particle with a little bit of spread -- speed(dt) * DRAG * Rand
p.pos += p.speed * (float)(delta) * DRAG * glm::vec3(rand()%5,rand()%5,0);

```

where my particle struct is:

```
struct Particle{
    glm::vec3 pos, speed;       //position, speed
    unsigned char r,g,b,a;      //color
    float size, angle, weight;  //?
    float life;                 //remaining life of a particle, if <0 it's super dead
    float cameradistance;       //squared distance to camera : -1.0f if dead

    //used for std::sort, needs an overloaded comparison operator
    bool operator<(const Particle& that) const {
        return this->cameradistance > that.cameradistance;
    }
};

```

how would I go about simulating the behavior of my first program with this second program I'm writing? I can't seem to wrap my head around doing this as the program structure is so drastically different.

# Answer
> 2 votes
Well if I understand well as @user8363 explained in the comments, your problem is that you are making one direction for all the particles, which makes the particles move in that direction. If you want the particles to accelerate toward the point you need to make a direction vector for each particle. For instance:

```
foreach particle:
    acc = particle - mousePosition; // assuming mousePosition is actually a vec3.

```

Then updated each particle accordingly.

---
Tags: opengl, c++, physics, particles, glm
---


# Question
Title: SDL2 - Ignoring repeated key input until key is released
I'm currently using **SDL\_GetKeyboardState** to capture key states once per frame. This works great for input that I want to handle for as long as a key is pressed (i.e character movement) but creates a real problem when I want to respond to a key press only once while the key is held down. Currently, even a rapid key press+release occurs over 2-3 frames, meaning the input is handled that many times instead of just once.

In short, is there a simple way to handle input once when a key is pressed, and then ignore that key until it's released and pressed again?

Just to mention, I've already looked at using **event.key.repeat** to see if a key has been repeated, but this only seems to work when the key has been pressed for a certain period of time (in my case 10+ frames)

Thanks in advance

# Answer
The usual way to process most input is to set up your game loop to poll for events. For your specific case: set a flag on the `SDL_KEYDOWN` event for the key you want to listen to. When you want to process the input, check if the flag is set and if it is, do your action and unset the flag. Example:

```
// ... main loop initialization

bool left_down = false;
SDL_Event event;

while(SDL_PollEvent(&event)){
switch(event.type){
    // look for a keypress
    case SDL_KEYDOWN:
        if(event.key.keysym.sym == SDLK_LEFT){
            left_down = true;
        }
        break;
    }
}

// ... main loop stuff

// ... later (in some entity's update() function?)
if(left_down == true) {
    // do whatever
    left_down = false;
}

```

I couldn't find a great tutorial for this for SDL2, but I don't think the API for this has changed much since SDL 1.2, so you can most likely take a look at some tutorial on events for 1.2 and still follow along. Here's the documentation on SDL\_PollEvent.
> 3 votes

---
Tags: input
---


# Question
Title: How should I handle sound in a split-screen game?
In a split screen multiplayer game, sound events may be heard by more than one player, and they might sound different to each player.

For example, player one might hear the sound of the car they're driving low-pass filtered. Player two might hear the engine sound doppler-shifted as player one drives past at speed. Player three, observing from a distance might hear the unfiltered engine sound at a low volume.

In such a game, the "obvious" approach is to just play all the sounds at once. What methods can I use to improve on this, to prevent sound overload/"cacophony" while maximizing immersion for each player?

# Answer
You have to make sacrifices, you cannot have the same immersion when some sounds aren't supposed to be heard by all the players. Some engines have built in solutions to this problem (example) but I couldn't find any information about the way it works.

# Use stereo to separate the sound

*(wiz3kid idea in the comments)*

If the screen is split in the vertical way you can manage the different sounds to be played on the side of the proper player. It has been described here(Use Case 1).

In this example the sounds are attenuated by -96dB on the other side, which is equivalent to muting. (If my calculus are right, -96.3dB is like dividing by 15 million). I think it doesn't have to be so brutal. If you play each sound *mostly* on the side of the player who is supposed to hear them, the players will be able to distinguish a sound coming from their half or not and there will still be a bit of stereo.

This works the best when there are only two players, but in case of 4 players you can combine the sounds from the players vertically to use the same method.

## Select the played sounds

I think the *cacophony* effect comes from the sounds that are long. In mario kart for example, the drifting sound volume is very low compared to the sound when an item is picked. The game sound may sound messy, but it isn't so much considering the sounds that are played. It could have easily been unlistenable.

Therefore the solution might be to filter out the long or repeated very often sounds. By attenuating the general noise, the important sounds will be easier to distinguish. I don't think it is a problem for a player to hear sounds that he isn't supposed to hear as long as he can easily hear the sounds that are important to him.

## Relative to the closest player

In this thread they all agree that the sounds should be played once in total (not once for every player) relative to the most concerned player, the closest for example.

## Tinus' point of view

Link.

I don't know him but he makes a unity plugin to handle split screen audio. He explains the method he would use on one of his post. I don't know if it is a valid approach since I don't understand most of it.

> First go for the naive approach, just superimpose the listening perspectives and send them to the stereo output. This will not work for aurally intense games, but there's also plenty games for which this should be fine.
>
> Next, introduce extra tools with which you can control the mix better. How you would use these depends on the game you're making, and how you think it should sound, but there's some possible common patterns. Of the top of my head:
>
> * Compressor/Limiter/Sidechaining effects on listeners and stereo outputs. It's hard enough to keep aurally dense Unity games from clipping, let alone when you add multiple listeners to the mix. A simple compressor at the end of the signal chain wouldn't be an elegant solution to this problem, but it would be a quick fix. I might try my hand at implementing a Compressor component using OnAudioFilterRead, actually.
> * High Dynamic Range audio. The newer entries in the Battlefield series use this to great effect. Again, it's no magic bullet that automatically cures your mix. But the HDR paradigm does seem like a powerful tool to help you organize dense and very dynamic mixes. Culling and prioritization are handled elegantly this way, which would no doubt come in handy for splitscreen setups as well. Caveats: DICE use custom software (not sure if FMOD could be juryrigged for this), and demands on audio asset creation become heavier.
> * Allow sound artists to prioritize sounds, and have some kind of mixer that manages sound priority between listeners. If player 2 really, really needs to hear this rocket that's about to hit him, perhaps you can duck the sound of player 1.
> 2 votes

---
Tags: multiplayer, sound
---


title: Dynamic Quad/Oct Trees

text:
# Question
Title: Dynamic Quad/Oct Trees
I've recently discovered the power of Quadtrees and Octrees and their role in culling/LOD applications, however I've been pondering on the implementations for a Dynamic Quad/Oct Tree.

Such tree would not require a complete rebuild when some of the underlying data changes (Vertex Data).

Would it be possible to create such a tree? What would that look like? Could someone point me in the correct direction to get started?

The application here would, in my scenario, be used for a dynamically changing spherical landscape with over 10,000,000 verticies. The use of Quad/Oct Trees is obvious for Culling & LOD as well as the benefits from not having to completely recompute the tree when the underlying data changes.

# Answer
> 1 votes
I have a few 2d implementations of dynamic spatial structures located here:

https://github.com/ClickerMonkey/Steerio/tree/master/Java/src/org/magnos/steer/spatial

As far as quad/octrees go, each iteration you check on everything in the database to see whether it has changed which node it belongs to. In my tree implementations I keep an entity in the highest node in which it is fully contained. That involves some simple logic:

```
am I fully contained in the current node?
   try to push up parent node
else if this node has children?
   can any of the current node's children contain me?
      push down to child

```

I'll make it more efficient by having flags for whether an entity has moved... the ones that don't can be skipped.

---
Tags: data-structure, octree, quadtree, c++
---


title: ECS and life management of entities

text:
# Question
Title: ECS and life management of entities
I am done with my game's framework and I am trying to implement a life-management system. My framework so far has:

* Systems that hold pointers to the Entities they are interested in.
* An Engine class that owns the different systems.
* An EntityManager that owns the Entities.

Now every time you add/remove a Component to/from an Entity, the Entity notifies the engine class to run a(n) (un)registration routine that passes the Entity to the Systems which in turn decide whether they want to (un)register the Entity or not.

Say that I have a DestroyerSystem that remembers all Entities with a HealthComponent and is responsible for deleting the ones with no life:

```
void DestroyerSystem::update(float dt = 0)
{
        for (auto& entity : registered_entities)
        {
                if (entity.getComponent<HealthComponent>().hp == 0)
                {
                        EntityManager.destroy(entity);
                }
        }

}

```

The problem is that the Systems are supposed to keep valid pointers to the Entities and I am not sure how I can achieve that cleanly.

The only solution that I have so far is to make the Systems have an unregister() function that takes the pointer to the deleted element and erases it from the registered\_entities container. The Engine class would also have an unregister() function that would call the unregister() functions of the Systems. This works good for the other systems but creates problems when applied to the DestroyerSystem because it breaks iteration. To tackle this I copy the container and iterate on that one instead:

```
void DestroyerSystem::update(float dt = 0)
{
        auto entities = registered_entities;
        for (auto& entity : entities)
        {
                if (entity.getComponent<HealthComponent>().hp == 0)
                {
                        entityManager.destroy(entity);
                        engine.unregister(entity);
                }
        }

}

```

Does anyone have any better proposals for this?

# Answer
> 6 votes
I had the same problem in my implementation of the Entity Component System but I solved it with the use of an Event Manager.

Briefly, you can make an *EventManager* class that allow Systems to register some of their methods to a particular event. Then you can send an event and all the registered methods will be called.

**Here are the prototype of the two methods :**

```
void addHandler(const std::string &type, ISystem *obj, void (ISystem::*e)(IEvent *));
void sendEvent(IEvent *event); // IEvent::getType() is called to match with the type of EventManager::addHandler

```

With this, instead of instantly deleting the entity in your *DestroyerSystem* and thus breaking the iteration, you can send an event through to say "This entity should be deleted".

Another system, let's call it *EntityDeleterSystem*, can register for this event and store all the entities that must be deleted in a list. This System should be processed last and during the process, it will iterate through his list and delete all the entities that must be deleted.

---

Here is an example for better understanding :

**LifeSystem.cpp**

```
void LifeSystem::update()
{
    auto entities = _registered_entities;
    for (auto& entity : _registered_entities)
        if (e->getComponent<LifeComponent>()->getLife() <= 0)
            this->_world->sendEvent(new EntityDeletedEvent(e));
}

```

**EntityDeleterSystem.hh**

```
class EntityDeleterSystem : public ISystem
{
    private:
        std::vector<Entity *> _toDelete; // Used to store entities that WILL BE deleted.
};

```

Of course I've hidden all the unrelated code like constructor and other methods as you only need the implementations below.

**EntityDeleterSystem.cpp**

```
void EntityDeleterSystem::init()
{
    world.addEventHandler("EntityDeletedEvent", this, &EntityDeleterSystem::addEntityToDelete);
}

void EntityDeleterSystem::addEntityToDelete(IEvent *event)
{
    EntityDeletedEvent *entityDeletedEvent = dynamic_cast<EntityDeletedEvent *>(event);

    if (!entityDeletedEvent)
        return ;

    if (!(Entity *entity = entityDeletedEvent->getEntity()))
        return ;
    std::vector<Entity *>::iterator it = std::find(this->_toDelete.begin(), this->_toDelete.end(), entity);
    if (it == this->_toDelete.end())
        this->_toDelete.push_back(entity);
}

void EntityDeleterSystem::update()
{
    for_each(
        this->_toDelete.begin(),
        this->_toDelete.end(),
        [this] (Entity *entity) {
            this->_world->removeEntity(entity);
    }
    );
    this->_toDelete.clear();
}

```

---

The downside of this solution is that entities are not instantly deleted and thus could still be used in the next systems after your DestroyerSystem, so you have to make sure the systems are well ordered.

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


# Question
Title: Is there a good cross-platform C++ vector graphics library out there?
I'm making a game and want to use vector graphics. I started re-coding it using Cairo and the performance is horrific. So, I'm looking for a different library. It needs to be for C++ and cross-platform (e.g. no Direct2D). There's another question someone asked before like this, but there weren't any suitable answers. There's got to be something...?

# Answer
I fear the subject is quite tricky, few multi platform solutions seem to have launched, and even fewer seem to have survived on their own. I was looking into the subject a few months ago. I had a constraint as I needed the engine to run on iOS and Android. Didn't find anything that suited me really at the time.

But a few pointers from what I remember: each GUI system has some form of drawing API. So you might find something of interest within the ones that are cross platform like QT.

An equivalent of cairo would be AntiGrain You might want to compare the performance.

OpenFrameworks has support for vector graphics.

A very big library which has some vector graphics support - and a language dedicated to it - is ImageMagick.

Lower level you'll find Libxmi and Libart from the gnome project.

Not a high level API - and I'm not sure what are the odds it will suit you - but there is the standard OpenVG. There are multiple ports of OpenVG over software OpenGL and OpenGL ES renderers. Mesa 3D also seems to have an OpenVG implementation. But for some platforms only commercial solutions will be available.

There are way higher level libraries which integrate APIs for vector graphics. Among these there is an open source one named Clutter for GUI design and used in serious game design there is scaleform (Not Open Source). This game engine has some functions to draw vector graphics: 2DEngine

---

**EDIT**: clutter uses cairo apparently.
> 22 votes

# Answer
MonkVG is a cross platform OpenVG emulation on top of OpenGL ES 1.1 and 2.0. See: https://github.com/micahpearlman/MonkVG

Note: I'm the original author and maintainer of this library. It has a very liberal BSD license.
> 3 votes

# Answer
I ended up not bothering and just going with high-res images and scaling with OpenGL. It works well enough for my situation.
> -2 votes

---
Tags: c++, graphics, vector
---


# Question
Title: Stormy water like Temple Run 2 for Mobile
How can I make stormy water like they did in Temple Run 2. I've tried with Unity Water Pro to achieve the same result but when I include it in the project the frame rate crashes to 3 frames per second.

Unity Water basic doesn't fulfill the requirements at all. So is there any other way?

# Answer
> 0 votes
We end up with having a static mesh and animating it. Add some particle effects and we can make it stormy and mobile ready. I didn't require any real water reflection so this worked for me.

# Answer
> 0 votes
There's an asset for that. The asset also has a web player demo. Check out the unity store :)

Here's your link. https://www.assetstore.unity3d.com/en/#!/content/7768

https://www.assetstore.unity3d.com/en/#!/content/14109

---
Tags: unity, water
---


# Question
Title: Connecting two arbitrary points with 2 lines
**DEFINITIONS:**

Any "Point (x, y)" mentioned below is really the bottom left coordinates of a 1 unit by 1 unit rectangle. A "Line" is a defined as a rectangle that is either 1 unit tall and 1 unit or greater wide, or 1 unit wide and 1 unit or greater tall. These rectangles are constructed given a Rectangle(bottomLeftX, bottomLeftY, width, height). The height and/or width can be negative. If either are it will shift the start x or y accordingly as so:

```
public Rectangle(int x1, int y1, int width, int height) {
  _left = x1;
  _right = x1;
  if(width < 0)
    _left += width;
  else
    _right += width;

  _bottom = y1;
  _top = y1;
  if(height < 0)
    _bottom += height;
  else
    _top += height;
}

```

**THE GOAL:**

Given two arbitrary points, define two lines (as rectangles) connecting the two points. **The two lines need to randomly 'bend' at one of the two possible connections (see below).** The two points aren't in any specific order. Point A's X and/or Y can be above, below or even the same as Point B's X and/or Y.

**THE PROBLEM:**

I have made a solution that only partially works. There is a bug in my method below where sometimes the two lines do not connect at the bend/junction. It seems to only be when the bend/junction is in the bottom right of the points' bounds.

**WHAT I HAVE NOW:**

A little background: I'm working on a random dungeon generator. I create rooms randomly, and then I am going to connect them using the described point and line system above. Here's what I have now. "graph" is a Map\>, technically it's directional, but the reason was so that I wouldn't draw the same lines twice.

```
int x, y, dx, dy;
Rectangle a, b;
// loop through each edge of the graph
for(Rectangle outer:graph.keySet()) {
  for(Rectangle inner:graph.get(outer)) {
    // randomly set a and b
    if(random.nextBoolean()) {
      a = outer;
      b = inner;
    } else {
      a = inner;
      b = outer;
    }

    // generate the origin points based on a
    x = (int) a.getCenterX();
    y = (int) a.getCenterY();
    // and the delta of b to a
    dx = (int) b.getCenterX()-x;
    dy = (int) b.getCenterY()-y;

    // create line starting at a, then
    // create line starting at end of above line
    lines.add(new Rectangle(x, y, dx, 1));
    lines.add(new Rectangle(x+dx, y+dy, 1, -dy));
  }
}

```

Here's what it produces. Most of the time it works, however there are cases where the corners do not line up. I'm not sure how to fix this.

Any input is much appreciated.

# Answer
> 1 votes
So, the problem was occurring due to the fact the A could be on either side of B, thus adjusting the width would fix the cases where A was to the left of B, but break the cases where A was to the right of B. So I ensure A is always to the left of B, allowing the additional width to always produce the desired result.

This could have been done reverse as well, whether A was always to the right of B, or even to the Top or Bottom, but having that guarantee allows the logic to work 100% of the time.

**THE SOLUTION:**

```
// define variables
int dx, dy, x, y;
Rectangle a, b;
// loops through each "edge"
for(Rectangle outer:keys) {
  for(Rectangle inner:graph.get(outer)) {
    // ensure A is never to the right of B
    if(outer.getCenterX() < inner.getCenterX()) {
      a = outer;
      b = inner;
    } else {
      a = inner;
      b = outer;
    }
    // the starting points
    x = (int) a.getCenterX();
    y = (int) a.getCenterY();
    // the deltas to get from A to B
    dx = (int) b.getCenterX()-x;
    dy = (int) b.getCenterY()-y;
    // randomly bend clockwise or counter clockwise
    if(random.nextInt(1) == 1) {
      halls.add(new Rectangle(x, y, dx+1, 1)); // start at a
      halls.add(new Rectangle(x+dx, y, 1, dy)); // start at the end of the last line
    } else {
      halls.add(new Rectangle(x, y+dy, dx+1, 1)); // same as above
      halls.add(new Rectangle(x, y, 1, dy)); // swapped horizontal and vertical
    }
  }
}

```

# Answer
> 1 votes
I think the problem comes from the rectangle **width**. See on the image below, the two lines are suposed to connect at the red cross. The dark blue lines represent the rectangles if they had no width. When you enlarge the line it creates a gap.

To avoid this, you can make the horizontal line larger.

```
lines.add(new Rectangle(x, y, dx+lineWidth, 1)); // here lineWidth = 1

```

Although my code creates a *problem*. I don't think it is very important but when the lines are like the image below the darker area is covered twice (by both line).

---
Tags: algorithm, geometry
---


# Question
Title: Adding an existing script to a gameobject programmatically
Is there a way to take a script and apply that specific script to an object through code? In pseudocode, what I'm trying to do is essentially as follows:

```
ObjectOne.MyScript = ObjectTwo.GetComponent<MyScript>();

```

The closest thing I've found to doing this is `AddComponent()`, but that only takes either a string or a type and I'd assume it just finds the relavant script and instantiates a clean copy of it. That could work for what I want to do as I could just fill in the relevant information, but that would be tiresome and there should be an easier way to do this.

# Answer
Yes, the only way is using `AddComponent()`:

```
var myScript = gameObject.AddComponent<MyScript>();

```

I don't see how this can be tiresome. There's no way to instantiate a *MonoBehaviour* so you cannot have multiple instances of your script instantiated by yourself and added them to the game objects on the go - if that's what you thought.

---

*Update*

There's really no way to reparent or move a component, so you'll probably have to copy.

However, there's another approach! Instead of having this component in your main Game Object you could instantiate a child Game Object that would just act as a container for your component, and you would move this child to other Game Objects as necessary. Of course the viability of this idea depends on the complexity of the relationship between the main Game Object and the component: if the component uses too many variables of the main Game Object it may be tiresome to reposition it to a child Game Object.
> 15 votes

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