# Question
Title: Decoupling the entity from whatever controls it
In a lot of games the player can choose whether an entity will be controlled by the AI or by the player. For example in the game Little Fighter 2, the player can choose how many of a maximum of 8 characters would be AI-controlled and how many of them would be human-controlled.

I was thinking how I can achieve this in my game. Currently in my game whatever controls the characters is hardcoded into them. I even have an `AIAgent` abstract superclass that all AI characters derive from, and a `Player` class that represents the player-controlled entity.

I realized that in order to be able to choose dynamically if an entity will be controlled by the player or by the AI, I need to decouple the entity itself from "it's brain", i.e. whatever controls it.

By "the entity itself" I mean the attributes and actions of the entity: it's mass, it's image, the way it implements shooting a missile, etc. By "the brain" I mean the system that decides when, and possibly how, to act.

As I said, currently "the brain" of my entities is hardcoded in their `update()` function. My `Player` class responds to player input in it's `update()` method, and my `AIAgent` subclasses usually delegate to a `StateMachine` of some sort in this method.

So I was thinking: how can I decouple the entities from their "brains", in order to be able to choose dynamically whether a `Monster` is player or AI controlled - and without a lot of ugly code duplication.

The solution that comes to mind is creating an abstract `Controller` class, with subclasses that can be plugged into the entities. Then the entities simply delegate to their controllers in the 'update()\` function, and the controller controls the entity through it's interface.

To demonstrate:

```
abstract class Entity{
    // .. stuff omitted
    Controller brains;

    public void update(){
         brains.update(this);
         // .. non-behavioral physics stuff omitted
    }

    public void setController(Controller brains){
        this.brains = brains;
    }

    // methods that will be called by the controller in order to control the entity:
    public void attack(){
        ....
    }
    public void moveLeft(){
        ....
    }
    // ....
}

```

A `PlayerController` can read user input and control the entity accordingly, while an `AIController` would implement a state machine to control the entity. The controllers would use the entity's public interface to control it.

The only doubt I have about this approach is that it forces the entities to offer a lot of public methods to control them, such as `moveLeft()` and `shootMissile()`.

Conceptually, it doesn't "feel right" that the entity would expose methods like these to the outside world, when 'conceptually' it should be it's own job to control itself. Just like it isn't possible to control a human's legs or heart from the outside. Feels like it breaks encapsulation.

So my question is: what do you think of this approach? Can you recommend a better one? How is this often done in games?

# Answer
I tend to subscribe to the theory that an entity is somewhat abstract and in the general sense doesn't really have much of any logic. If anything, an entity often exists as a wrapper around a complex set of systems that deliver specialized behavior based on outside factors.

For example, two entities are constructed in the same way but one perhaps has an `AIController` where-as the other has a `PlayerController`. The two different controller components dictate which systems the entity is controlled by.

In the case of the player, input from the keyboard/mouse get translated into actions and the player system reacts by setting appropriate `MovementComponent` attributes on the entity that has a `PlayerController`.

In the case of the AI, the various AI systems dispatch actions and the AI system reacts by setting appropriate `MovementComponent` attributes on the entity in which the AI logic is running for.

At this point, a seperate system is responsible for interpretating the information on the `MovementComponent` and causing the entity to actually move in the world simulation.

This very easily lends itself to situations where a player controlled entity may loose control of their entity due to some fear or mind control affect and now be controlled by some AI temporarily or allows a player to temporarily mind control an AI based entity for their own bidding all by simply swapping the controller being used on a given entity.

Want to add networking? Now you might introduce a `NetworkController` which takes input from network packets from the game server, sets appropriate entity state, and the movement system begins to navigate those entities in the world simulation.

Sometimes adding a single layer of indirection (such as the *movement system* above) can easily help decouple code and all the while provide a very flexible way to introduce additional behaviors or alter behaviors in the future without severe system impact.
> 3 votes

# Answer
The way I like to think about this problem is as abstracting the input. In order words, have the AI "press buttons" (not literally). It's pretty much the same as what you're suggesting, with the Entity being a fully functional puppet that can either be controlled by the player (using normal input) or by the AI (using your state machine).

Modern game engines use what's called a Component or Entity architecture where the entities are built out of smaller pieces (components), instead of reusing through inheritance. In this case, the controller would be one of the components, and you'd have components to render the visuals, update the physics, etc. The components communicate directly, and the entity becomes not more than a container.

This might alleviate your concerns about exposing a public interface, but if you don't want to re-architect your game you don't have to. Think about it in terms of code systems, not "real" objects. Your entity is an encapsulated object that implements functionality to draw itself and internal logic to update its position and such. And it offers an interface for other systems to interact with it, effectively to control it. I see no real problem with this.
> 1 votes

---
Tags: architecture, software-engineering, oop
---


title: Help with dropping items in a game

text:
# Question
Title: Help with dropping items in a game
I am making a game where i have items or blocks stacked on top of each other.

What i would like to do is, when the first item(or the item at the bottom of the stack) is removed, i would like to shift all the blocks above, down into the next position below it and add another block to the top of the stack.

Sort of like in a match 3 game.

Could someone provide instructions for doing this? or some type of psuedocode?

Thanks guys

# Answer
Is something like this what you're asking for?

```
Block blocks[][];

void removeBlock(int x, int y)
{
  while (y < blocks[x].length - 1)
    blocks[x][y] = blocks[x][y+1];
  if (y < blocks[x].length)
    blocks[x][y] = generateNewBlock();
}

```

If you're asking about the animations for moving the blocks down, then you probably will want to keep both a logic position (the x,y coordinates above) and a visual position, that interpolates smoothly as the block falls.

You can use simple linear interpolation `pos = pos1 * t + pos0 * (1-t)` where t will go from 0 to 1, to move from pos0 to pos1. Preferably though is to have some kind of animation, for instance, you could use acceleration to speed up the blocks as they fall, then have them bounce once:

```
gravity = 10
velocity.y -= gravity * dt
position.y += velocity.y * dt
if (position.y < destination.y)
{
 if (!bounced)
 {
   velocity.y *= -0.1;
   bounced = true;
 }
 else
 {
   position.y = destination.y;
 }
}

```
> 0 votes

---
Tags: java
---


title: Unity: stop/play only background music

text:
# Question
Title: Unity: stop/play only background music
I have a music sound clip simply drag-n-dropped to my hierarchy. I also have other sound effects in my game. I want to pause/play background music on button press but only music, not all sound effects. How can I reach this music `GameObject` in C# code?

# Answer
> 6 votes
You can access any object in your hierarchy by searching for it:

```
GameObject soundObject = GameObject.Find("BackgroundSoundObjectName");

```

Then you're likely going to want to access the AudioSource component:

```
AudioSource audioSource = soundObject.GetComponent<AudioSource>();

```

Then you can use the `Pause()` and `Play()` methods of the audio source to control the music.

# Answer
> 2 votes
If you have multiple audio sources, `FindObjectsOfType` might be useful (The `UnityEngine.Object` part is unnecessary if called from a `MonoBehaviour`-inherited script):

```
AudioSource[] allAudioSources =
    UnityEngine.Object.FindObjectsOfType<AudioSource>();

```

---
Tags: unity, sound, music, sound-effects
---


# Question
Title: Timestep schemes for physics simulations
The operations used for stepping a physics simulation are most commonly:

* Integrate velocity and position
* Collision detection and resolution
* Contact resolution (in advanced cases)

A while ago I came across this paper from Stanford that proposed an alternative scheme, which is as follows:

* Collision detection and resolution
* Integrate velocity
* Contact resolution
* Integrate position

It's intriguing because it allows for robust solutions to the stacking problem. So it got me wondering...

What, if any, alternative schemes are available, either simple or complex? What are their benefits, drawbacks, and performance considerations?

# Answer
The technique I found which has worked best for me over the years is this:

* Integrate velocity
* Collision detection
* Constraint solver (including contact resolution)
* Integrate position

Apparently this is called 'semi-implicit'. I've found it to be the most stable of all the techniques I've tried. I used this in the physics engine behind Little Big Planet PSP.

Hope it helps!

Cheers, Paul.
> 2 votes

# Answer
Another scheme I encountered is the one from Position Based Dynamics where you:

* Integrate velocity and position (unconstrained)
* Collision detection
* Constraint solver (position based)
* Update velocities from new positions (basically you're integrating them using the computed constraint forces, just like you did for the positions)

This is to show that there are indeed other schemes. Each has its benefits. PBD is good for cloth for example, while the semi-implicit velocity solver is better suited for rigids.

The collision detection step has to be somewhere after the positions were updated, as it doesn't matter if you put it before or after a velocity update (unless you're using velocity for continuous detection). Things can get even messier is you use higher order methods like Runge-Kutta: where do you put collision then and how often? I think Kenny Erleben has some paragraphs on this (lazy and eager approaches) at the beginning of his PhD thesis.
> 0 votes

---
Tags: physics, performance
---


title: Basic Collision Detection Math

text:
# Question
Title: Basic Collision Detection Math
First a bit of background. I have yet to read a book on game development, though I do plan on picking one up sometime.

A long time ago I made a simple pong game, followed by a simple Arkanoid-type game. In both games I figured the collision detection by comparing the x, y, and z of the ball to the paddle. I did this calculation for each side of the ball and each side of the paddle. It was the only way I could think of to do it at the time.

It was something along the lines of:

```
if (thing.x >= otherthing.x) {
    if (thing.y >= otherthing.y) {
    }
}

```

And so on.

Is this the normal way of figuring collision detection? Did I over-complicate it, or is this the basic way that it's done?

# Answer
> 2 votes
No, your way of doing it is exactly how AABB collisions work, being the most basic rectangle to rectangle collision: http://www.opentk.com/node/869. You basically check if any of the sides of a given rectangle are too far from those of a second one.

As you can see here, as soon as a side is too far, the rectangles don't collide.

You would need to take into account the size of the rectangles, which you seem to have forgotten in your little example. Supposing 2 Rectangle structs a and b with fields x, y, w and h:

```
if (a.x + a.w < b.x ||
    a.y + a.h < b.y ||
    a.x > b.x + b.w ||
    a.y > b.y + b.h) {
    return false; // No collision
}
return true; // Collision

```

---
Tags: graphics
---


# Question
Title: Which gesture recognizer should I use to handle multiple simultaneous flicks?
So, if you can picture a game with little ninjas running down at you, and a bunch of shurikens at the bottom of the screen, you're picturing the set-up I'm addressing.

I want the player to be able to flick the shurikens up at the ninjas, but I want them to be able to do it with both thumbs at the same time. Gesture recognizers seem to be the way to do this, but I'm not sure which is the most appropriate. The main ones that seem to fit are the pan gesture and the swipe gesture.

Does anyone have insight into the pluses and minuses of each, or even if a better one exists?

# Answer
> 1 votes
A swipe gesture is a kind of pan gesture. Both gestures start and end when a touch starts and ends, but a pan gesture will track and report input continuously over the duration of the touch. A swipe gesture will "instantaneously" determine if the translation of the touch was fast enough and in the proper direction and report only once.

Consequently, you should probably use a swipe gesture to implement your shuriken-throwing. If that ends up not feeling right, you can use a pan recognizer and re-implement the "swipe detection" heuristics yourself so you have better control over them.

---
Tags: ios, gestures
---


# Question
Title: How can I compute a velocity proportional to the difference between two hand positions?
I'm working on a project with the Kinect SDK and XNA 4. I need take the position of the hands and draw a sprite over it. I'm was doing it directly and because of that I get a "trembling hands" effect. So, I was thinking of making the sprite move from the previous position to the new one given in every frame by the new hand position.

This way, the sprite does not jump from one position to another. This is working just fine, but I'm using a constant value for the velocity, and I really would like to use a variable velocity given by the difference between the previous and the new position. That is: if the hand move more quickly in the reality, the velocity will be higher.

I really don't have a clue on how to make this work. Can somebody point me in the right direction?

# Answer
> 1 votes
By computing the velocity as some factor of the difference between the start and end position, you can achieve the association you want:

```
var velocity = (endPosition - startPosition) * scale;

```

The hard part be will choosing a value for `scale`. You can initially try constants -- such as `1.0f` or `0.5f`. This makes the velocity directly proportional to the start and end distance. If that feels good, great. If it doesn't you may need to try more complex scaling factors to achieve more of an easing curve where the velocity for small movements is low but increases greater than linearly as the movement delta becomes larger. For example, you might compute `scale` as:

```
scale = pow(0.25 * length(velocity)), 2)

```

---
Tags: xna, 2d, sprites, movement, kinect
---


# Question
Title: How portable are OpenGL versions, really?
If I write a game engine that uses OpenGL 1.5 (not assuming what else I do), is it portable now and is it still portable five years from now or are/will support for OpenGL by hardware and drivers (be) exclusive to their (much more farther along) target OpenGL versions?

Lately I've been looking at a lot of answers on this website that direct users to divert their work towards the most recent OpenGL versions, citing hardware surveys of DirectX support and only recommending earlier versions as a last, final resort (as if to imply there is something wrong with them that makes all usage of them invalid or pointless).

If I only have computers that can provide OpenGL \<=1.5 or \<=2.1 contexts should I just give up game programming if I can't afford a new computer with hardware and drivers for 3.x and 4.x? Or should I finish my game engine the way I intended to?

Will by the time I get a 4.x supporting setup will there be new versions and a lack of backwards compatibility that trash all usage of 4.x? Will 4.x ever dominate over earlier versions support wise before a new major version is realized and released?

# Answer
> 7 votes
OpenGL 1.x is not likely going to disappear on PCs. A great number of luminaries in the GL community consider the explicit compatibility mode and deprecated features of GL 3.1 to be a mistake. The last time GL was scheduled for a massive break in compatibility, Khronos backed out and delivered an incremental update.

While nobody can see the future, it's very likely that your GL 1.x code will continue working on PCs for some time to come.

Portability problems will arise only if you want to target a platform that doesn't support GL at all, like mobile devices (which use GL|ES, so it's very similar at least) and most consoles (you can get a GL-like API on Sony's consoles, but it's still going to require porting work to support).

concept3d's answer is very right in that you really should abstract your use of the graphics API. Write a thin bit of code that wraps GL textures in your own `Texture` objects and so on. Then you can later write GL 1.x versions, GL 5.x versions, Direct3D versions, whatever.

# Answer
> 4 votes
The short answer, OpenGL really changes after version 3.1, that being said don't use OpenGL function calls directly, but actually build a small wrapper around it. One way to do it is to make a class that is responsible for all openGL calls, this can be replaced once you want to upgrade to newer versions. You can for example have a Texture resource class that doesn't rely on OpenGL, the mapping happens in the wrapper class this is what Horde3D does.

On the other hand Ogre3D takes a more complicated approach, instead of implementing a single hardware layer class they provide basic abstract classes for any hardware API (DirectX, OpenGL, OpenGL ES etc) each hardware layer is implemented by overriding this interface, this way you can have multiple API support with a more object oriented (but more complicated approach).

Otherwise if your engine directly use OpenGL calls then you probably need to rewrite a lot of the functions to support newer versions. If you're a beginner and this one of your first projects, my main concern won't be about portability/re-usability but actually about how to make the engine, you will mostly figure out that there are better ways of doing it after your first time.

# Answer
> 1 votes
> If I write a game engine that uses OpenGL 1.5 (not assuming what else I do), is it portable now and is it still portable five years from now or are/will support for OpenGL by hardware and drivers (be) exclusive to their (much more farther along) target OpenGL versions?

Currently, all of the features provided by any OpenGL version x \<= 3.0 are explicitly supported by all versions y such as x \<= y \<= 3.0, *and* they (old features) *can be* enabled in versions \>= 3.0 by creating compatibility context and accessing those features through the context.

For example, OpenGL 3.0 includes essentially every feature provided by previous OpenGL versions (some being marked as deprecated) - but you can request OpenGL 1.5 compatibility context from a GPU driver supporting e.g. OpenGL 4.0 natively and use those features (fixed-function pipeline comes to mind).

Also, all the major software vendors (AMD/ATI, nVidia, Intel) provide support to legacy OpenGL features in their newest drivers, though *the efficiency is often very low*, as they are currently unimplemented in hardware, so software emulation is used instead (nb those drivers quite often use code from Mesa project AFAIR); selection mode, old-style (pre-shader) lighting, automagic mipmap generation, display lists and similar features can be considered as such "potentially unsafe" features (though some of them are still quite fast in some cases, as with display lists for example).

**tl;dr** \- yes, it's portable, and *probably* will be portable, unless driver vendors suddenly feel the urge to cut the connection with the past (not likely, until now it hasn't happened in case of OpenGL) *or* some new technology makes old features incompatible (likely, but not in the nearest future). A good example is x86 line - until x86-64, it was almost completely backwards-compatible; with introduction of x86-64, the compatibility was broken and some old apps just wouldn't run anymore.

> Lately I've been looking at a lot of answers on this website that direct users to divert their work towards the most recent OpenGL versions, citing hardware surveys of DirectX support and only recommending earlier versions as a last, final resort (as if to imply there is something wrong with them that makes all usage of them invalid or pointless).

I'd say that, if you're using shaders (OpenGL \>= 3.0, core profile), the difference is actually only minuscule (new features, allowing better gfx quality). The main difference is between fixed-function pipeline and using shaders - because the gap is huge and old code is basically not portable to the new architecture. DirectX is a different beast - you need to *install DirectX 9* even if you have DirectX 11 *just to use DirectX 9 features* (e.g. Direct3D 9) - it makes complete sense to just skip to new DirectX version to avoid the trouble, both for yourself and the application user.

As far as OpenGL goes - if you want your code runnable on pre-shader GPUs, use e.g. OpenGL 2.1 - it's almost 10 years old already, so basically everything supports it. There isn't anything wrong with that, it's just that you won't be able to extend your code to use shaders etc. without much effort (unless your app is already using vertex memory buffers, i.e. vertex arrays - then it's much easier to port).

**tl;dr** \- no, there's nothing wrong with using old OpenGL versions, as long as you're aware that the limitations of pre-3.0 versions can be severe (no "plug-n-play cool water effects" etc).

> If I only have computers that can provide OpenGL \<=1.5 or \<=2.1 contexts should I just give up game programming if I can't afford a new computer with hardware and drivers for 3.x and 4.x? Or should I finish my game engine the way I intended to?

Give up programming? If you're already more than 50% into it - certainly not. Otherwise, I'd reconsider. Anyway, it'd be good for to to avoid all immediate mode calls and move to glDrawArrays etc, since it is essentially nr 1 of what is needed to shade a geometry - storing the data in a vertex array.

> Will by the time I get a 4.x supporting setup will there be new versions and a lack of backwards compatibility that trash all usage of 4.x? Will 4.x ever dominate over earlier versions support wise before a new major version is realized and released?

Nobody can tell that for sure. As already stated above, it's quite unlikely, since backward-compatibility has been largely maintained until now, and, in the worst-case scenario, you can always use a software renderer for old applications -

As a side note: there has been 3D technologies/choices that was expected to thrive (IRIS GL, OpenGL++, DirectX/OpenGL fusion (Fahrenheit project), Glide, GLU, 3dfx GPUs, ARB being the only OpenGL governing body, hardware T&L \[it got obsoleted/incorporated into shading model\]), while some were expected to fail (DirectX first, due to lack of game/application vendor support, being not portabile to non-Windows systems and existence of Glide, OpenGL then due to... *lack of game/application vendor support, being not portable to Windows systems \[see Windows 2000/Vista problems with OpenGL! making OpenGL API a redirect to Direct3D calls didn't help, either...\], Longs Peak controversy, being governed by ARB and existence of Direct3D* \[see the pattern?\], texture compression was expected to be obsoleted due to increasing memory sizes \[it's still used commonly, because texture sizes grow faster than memory sizes\], ATI GPUs were considered obsolete by some and expected to die out the same way 3dfx did \[but then, suddenly, AMD gave them a hand\]) etc etc etc

Also, as far as the very OpenGL API goes (esp. at the times of the all-powerful ARB), there were numerous vendor extensions that have been expected to be incorporated into mainstream API - and they either hadn't been for a long time or not at all, and there were some that appeared with no apparent reason, were seldom used and quickly forgotten - yet nobody exactly knew - *why*? ...

None of those "prophecies" came true, although some people would literally kill other just to prove they're right about them. Some delusional individuals still spread the FUD around, saying "this technology will die!" and/or "that technology will thrive!" - but that's just that, speculations and opinions.

**tl;dr** \- **you can't predict future.** Don't ask speculative questions about the future - nobody can answer a question about the future of technology with much certainty; if it was possible, well, the world would be a different place now (we'd probably still have like 10 computers in the world per IBM prophecy, and we'd not even use phones, as they were considered "a mere fad" in the Bell's days...). You can only speculate - and science shouldn't be based on speculation. Don't choose your technology back/front-end based on speculation. Either use old stuff for compatibility, or new stuff for possibilities - you can't have both at the same time. Either stick with what you know and what you can do already, because it allows you to do what you want already, or go forward to learn new stuff, to be able to achieve more.

Source: Wikipedia, google, internet, opengl.com, own experience.

Also, related: OpenGL: What are the adoption rates of the various versions (And what's a reasonable version to use)

---
Tags: opengl
---


# Question
Title: How do I resolve a sphere-triangle collision in a given direction?
I am trying my hand at game physics.

I understand that the basic way to pull back a sphere when it collided is to negate the penetration distance:

```
// If collided...
// `distance`: distance form triangle face; a negative number
// `normal`  : triangle face, in vec3
// `position`: sphere center, in vec3
position.x -= normal.x * distance;
position.y -= normal.y * distance;
position.z -= normal.z * distance;

```

But I don't want to change y coordinate, while the player is on the ground like this (side view):

How can I calculate the expected translation?

I have these values:

* penetration distance, as a negative number (shown in blue)
* triangle face normal, as a `vec3` (shown in red)
* triangle vertices, as 3 `vec3`s

and

* sphere radius, as a number
* sphere center, as a `vec3`

Answers in any programing language are welcome!

**updated Jul 17, 2014**

I found a hint. It's difficult to explain, I will attach 2 more figures.
It seems, dashed lines in following figures are the translation value what I need, I guess.

and in another case

# Answer
What you have here are two constraints that need to be resolved. On one hand, you need the sphere to stay outside the wall, by pushing it along the normal. On the other hand, you have the constraint that the sphere needs to stay attached to the ground.

If you don't want to try writing fancy solvers, the easiest way to do this is to use an iterative solver.

Essentially, you resolve the position of the sphere by applying the force away from the wall, including the y component. Then you apply the other constraint, and set the y to the correct value to stay on the ground. Now the sphere will intersect the wall again, so you push it away again, place it on the ground again, and so on. It's customary to make the number of iterations configurable, as it will be a tradeoff between performance and correctness.

By the way, I see that you are modifying the position directly in your code. Physics engines typically work with forces, so that if the ball hits the wall it will bounce away. With your code, it will get pushed out but then stay there. That said, if you're working on a character controller, then this approach might work, unless you want to model inertia.
> 7 votes

# Answer
In case you're looking for a pure geometric solution and not a physics one, i.e. you're not using gravity so that the ball falls down basically on an inclined plane, then I suggest you look at it as finding the position of the center after the collision so that the ball is tangent to both the wall and the ground. Unfortunately I cannot make a fancy drawing, but from my own scribbling on paper I get something like this in 2D: C.x = P.x - r * tan(theta/2) where C is the centre, r is the radius, P is the intersection point between the wall and the ground and theta is the angle between the wall and the ground (you can get it I think with a dot product between the normal and the y axis). I'm sure you can get a similar result for a sphere and two planes in 3D.
> 1 votes

# Answer
Finally, I found the geometric solution!

I will share the code in JavaScript with three.js which is a 3d library, provides math stuff to JavaScript.

```
var face      = contactInfo.face,
    normal    = contactInfo.normal,
    distance  = contactInfo.distance,
    point1    = new THREE.Vector3(),
    point2    = new THREE.Vector3(),
    direction = new THREE.Vector3(),
    plainD,
    t,
    translate = new THREE.Vector3();

// find point1 using nomal, radius and center position of the sphere
point1.copy( normal ).multiplyScalar( -this.radius ).add( this.position );
// find horizontal directon from point1 to the wall face
direction.set( normal.x, 0, normal.z ).normalize();
// get plain "d" of the wall face
plainD = face.a.dot( normal );
// t is the Paramater of line which is from point1 to wall face
t = ( plainD - ( normal.x * point1.x + normal.y * point1.y + normal.z * point1.z ) ) / ( normal.x * direction.x + normal.y * direction.y + normal.z * direction.z );
// find point2 on wall face
point2.copy( direction ).multiplyScalar( t ).add( point1 );
// point2 - point1 is the valuse what i needed
translate.subVectors( point2, point1 );

```
> 1 votes

---
Tags: 3d, physics, collision-resolution, sphere
---


title: Unity3d : Animator canceling script

text:
# Question
Title: Unity3d : Animator canceling script
I create a sway script for my flashlight and attached it to the gameobject(flashlight).

Now the problem is that when I enable the animator in the gameobject(flashlight) the sway doesnt work,but when I disable it,it does work. This is the script :

```
#pragma strict

var flashLight : Transform;
var xSwayAmount : float = 0.1;
var ySwayAmount : float = 0.05;
var maxXAmount : float = 0.35;
var maxYAmount : float = 0.2;
private var vector3 : Vector3;
var smooth : float = 3.0;

function Start () {
    vector3 = flashLight.localPosition;
}

function Update () {
    var fx : float = -Input.GetAxis("Mouse X") * xSwayAmount;
    var fy : float = -Input.GetAxis("Mouse Y") * ySwayAmount;

    if(fx > maxXAmount)
    fx = maxXAmount;

    if(fx< -maxXAmount)
    fx = maxXAmount;

    if(fy > maxYAmount)
    fy = maxYAmount;

    if(fy < -maxYAmount)
    fy = -maxYAmount;

    var detection : Vector3 = new Vector3(vector3.x + fx, vector3.y + fy, vector3.z);
    flashLight.localPosition = Vector3.Lerp(flashLight.localPosition, detection, Time.deltaTime * smooth);
}

```

Has anyone got any idea why is this happening ? I need the animator to play my animations so I can't just disable it.Thank you.

# Answer
I assume the `flashlight` object is a child of the model with the Animator component, otherwise it should not be affected.

The solution is to **make all of the scripted changes in `LateUpdate()`** instead of `Update()`. This works because the Mecanim system runs in the `Update()` loop and since you want to overwrite the bone position, you just have to run right after it, ie. `LateUpdate()`.

You can see my question, **Mixing Unity Mecanim and Scripted Bones/States**, I made a while ago over at Unity Answers. It has a long list of other topics dealing with your exact same problem.

If you want to see a successful example in the real world, here is a script that I have written before that mixes scripted and Mecanim animation. The script moves the head bone around according to your mouse input (think FPS camera).

---

Small boilerplate:

## C#:

```
public class MixingScriptedBonesWithMecanim : MonoBehaviour
{
    public Transform flashLight;

    void LateUpdate()
    {
        // Do all bone changes here
        // ex.
        // flashLight.transform.position = new Vector3(Mathf.PingPong(Time.time, 1f), flashLight.transform.position.y, flashLight.transform.position.z)
    }
}

```

## JavaScript:

```
#pragma strict

var flashLight : Transform;

function LateUpdate()
{
    // Do all bone changes here
    // ex.
    // flashLight.transform.position = new Vector3(flashLight.transform.position.x + Mathf.PingPong(Time.time, 1f), flashLight.transform.position.y, flashLight.transform.position.z)
}

```
> 0 votes

---
Tags: unity, unityscript
---


# Question
Title: Bounds Queries for Simplex Noise Function
How do I construct a Bounds Query for 3D Simplex Noise?

---

\[This is more or less a follow-up to my last question\]

Simply put, for an arbitrary octree node (cube) in my volume (a section of Unity3d world space), I am trying to find out whether there is a surface inside the octree node (to determine if I need to subdivide my octree node). As explained in the other question, I cannot rely on edge-crossings to detect if a node contains a surface or not. Right now, I query each Vector3 integer coordinate in my volume (appropriately scaled by ~1/50) for a simplex noise value.

I was directed to bounds queries, where instead of querying for a specific point by supplying specific coordinates, I query for a `[min,max]` of the function in a certain volume (my octree node). If `min > 0` or `max < 0`, I need not subdivide, because the surface is outside my node (the surface intersects edges between vertices with different polarity/signs).

What (I think) I understand so far:

* At every simplex vertex, the value is `0`. This means that my minimum is not greater than 0, and my maximum is not less than 0. Turns out, because of my scaling, a single octave of simplex noise usually just puts 2 simplex vertices in my volume. Does this mean that my bounds query will require I subdivide every node that contains one of these simplex vertices? This is obviously wrong, else I would be subdividing infinitely...
* If I do not have any simplex vertex in my node, I still have to find the vertices' unit vectors of the simplices my node exists in. Then, somehow, I decide on a min/max. I suppose, it would come down to the nature of the simplices I am in...If they both give positive/negative values, then my bounds query would pass, and I wouldn't need to subdivide...right? But how do I calculate this?
* To construct the bounds query, I must find the pseudo-random unit vector assigned to each simplex vertex found in my node. This allows me to view the range of possible values in each simplex found in the node.

(I hope that all wasn't too confusing)

Despite/Because all that, I can't for the life of me think up any algorithm. What am I missing?

If there are any resources on this, please point me to them! I've googled about every keyword-loaded phrase I can come up with, but found nothing.

# Answer
The strategy we will follow is bounding the derivative, as the technique of splitting the query regions is very complex and probably very slow. Consider first a 1D function `f`, for which everywhere, `|f'| < 0.3`. We are given that `f(3)=-2`. What is a bound for `f` over the interval `[1, 5]`? Looking at the derivative bound, we have:

```
| df |
| -- | < 0.3
| dx |

```

So, abusing calculus:

```
|df| < |dx| * 0.3

```

Thus if `|dx| < 2`, then `|df| < 0.3 * 2`, and the range is thus `[-2-0.6,-2+0.6] = [-2.6,-1.4]`. Now of course, this is conservative: unless the derivative actually is 0.3 throughout the range, f will not actually be that large.

So how does this help us? Well we can just sample the simplex noise at the center of our query region, and then based on the "size" of that query we can compute how much the function is allowed to vary away from that central value.

The size we are looking at is the distance from the center to a corner. Now we just need to bound the derivative. We could do this analytically, but it's kind of a pain. (Actually, its a huge pain.) An easy way to do this is to just compute the gradient at a bunch of places (say, 10,000,000 random points) using finite differences, take their lengths, then add about 5%, and call it a day. You only need to do this once. The important bit is we are using this one number as the derivative bound over all of space.

Note that this method involves performing the point query, then doing a simple distance calculation and a multiply, so it is very fast. However, it is quite inaccurate, and will result in more splitting that will eventually be empty. Remember to limit the calculated bounds to the min and max possible values for your noise. Very large queries would otherwise result in huge ranges.
> 1 votes

---
Tags: c#, unity, graphics, algorithm, perlin-noise
---


title: How can I generate biome borders?

text:
# Question
Title: How can I generate biome borders?
I'm looking for ways to generate random biome borders (like what Minecraft has).

One technique involves choosing specific biomes based on (eg) a rainfall map and a temperature map. But that just determines *which* biome to place, not *where* the borders between biomes are.

I don't want to use quantized Perlin noise directly; that would generate certain quantized values strictly within other zones, whereas I'd like finer control over which biomes can abut others. For example, in Minecraft one can see mountainous terrain, forests, plains, *or* deserts right next to the ocean.

Many of the solutions to "the biome problem" propose computing the whole universe in a heuristic manner. I want to generate infinite terrain, and to me that suggests the algorithm be strictly functional: given an X,Y value (and a world seed) the algorithm can easily spit out a biome value.

So, my question: what are some techniques for identifying random, non-trivial-sized, contiguous chunks of terrain to be of a given biome?

# Answer
One possibility is to sample the rainfall/temperature maps at the center of each Voronoi cell, and then assigning that biome to each point within the cell. The biome edges can then be made more interesting by distorting the map, so that they aren't straight lines.

This can be made "functional", because you can compute which Voronoi cell you are in after the distortion in a functional way. The rainfall and temperature maps themselves might use Perlin noise or other functions to make them interesting, rather than depending on terrain.

Most systems generate the terrain all at once because it is much easier to make the terrain or presence of water affect the biomes in a non-local way. You will note that in Minecraft the biomes are not very physically plausible: there is no rain shadow effect, for example, which requires knowing what mountain ranges are nearby, and the wind patterns.

**EDIT:** Voronoi cells are an alternative to perlin noise for making things which have structure. In this case you don't want the biomes to vary too quickly or be contained within one another. Voronoi cells are the region of the plane which is closest to a set of points. So rather than sampling the rain/temp map at each point to determine the biome, all points in an area sample the same center, and thus have the same value. Here is a reference on implementing this. You will need a to modify it so that the noise returns the location of the closest point, not just the distance(s).
> 2 votes

---
Tags: procedural-generation
---


# Question
Title: How to approach in-game character creation system alike Sims
I would like to implement an in-game character creation similar to the Wii/Mii system or The Sims using Blender and Unity. In what ways is this possible, other than (or in conjunction with) using shape keys? The ideal system would have 2-4 body types, ~8 hairstyles, full RGB skin/hair toning (I quite like Terraria's style), and a few styles for faces.

I have been looking into this topic, but so far I have not found a good explanation as to how this would be implemented, and blender shape keys would allow for some aspects of this - namely body and hair manipulation - but would not work for coloring or styling the face.

# Answer
> 1 votes
You kind of summed up what you would have to do to create a ingame character creation screen. Supply different models for hair, face, and body. As for different colors, use a shader when drawing the model. The shader can make your skin color black, white, yellow or whatever stereotype color you would need.

I feel like there is not much to say about this currently as there is not a real problem. Could you emphasize the part you had difficulties with while implementing it. You did try something, right?

---
Tags: unity, 3d, blender, character
---


# Question
Title: How should I structure my code to add enemies?
So I am currently making a 1942-style game in Sprite Kit. I've reached the point where I am finished implementing pretty much everything (movement, shooting (also recognizing a hit and exploding an object), menu,etc..) ..expect for enemies. Since I am not so experienced in programming I wasn't quite sure how I should implement my enemies.

I wanted to have different enemy "classes" in my game (in a way where they have different appearance / weapons, etc) and I also wanted the game to spawn stronger classes in the game with time. (e.g: at the beginning of the game there are green enemies with one-shot weapons; 3minutes in they should be red and fire two-shots)

How should I code my enemies? Should I do different classes (what I am currently thinking) or should I declare them with strings or do the properties with a .plist file? (on a side node: how can I access my plist properties from the scene code?)

Do you have other tips for me regarding enemies/classes/plist files?

Or..are there any other ways specifically in Sprite Kit to do this kind of stuff?

# Answer
> 2 votes
If the only difference between the enemies are sprite changes and simple quantities (number of shots fired, rate of fire, etc), multiple classes would not be needed. This is exactly the sort of game Sprite-Kit was designed to make easily and quickly. Classes would be more appropriate if there was some unique behavior between the different kinds of enemy types.

A common example is that of the player compared to enemies. There are fundamental differences in how those two logical structures behave within the context of most games. Thus, different classes would be more appropriate. Different enemies with different sprites, on the other hand, assuming no fundamental differences between types, would more likely warrant a single "Enemy" class with properties defining the sprite to be used, the rate of fire and number of shots per attack, etc.

With a simple enough game, even an "Enemy" class isn't necessary, which may or may not be applicable to your game. Sprite-Kit has some impressive functionality that can be accessed entirely within the editors.

---
Tags: architecture, ios, objective-c, spritekit
---


# Question
Title: Physics / drag of object falling through atomsphere
Trying to simulate an object plunging into atmosphere. It seems to work, until the velocity falls past terminal velocity... down to zero... and then back up!

Something must be wrong with how I am applying drag? I've looked at the code so long, I've managed to confuse myself.

Here I set variables/constants:

```
Mass = 5;                           //Object Mass
Radius = 7;                         //Radius of the blunt end facing the air stream (too sensitive!!!)
Area = power(Radius,2)*pi;          //The total area of the blunt end facing the air stream
Gravity = 9.8;                      //Earth
DragCoeff = 1.61;
Velocity = 10000;                   //Initial velocity straight down (vector needs to be added)
Acceleration = Gravity * (1/Mass);  //this is acceleration FORCE... subtract drag from this
Altitude = 100000;                  //initial altitude(meters) (atmosphere "begins" at 100Km)

```

Then, in the main loop of the program: (note, delta\_time is provided by the system in microseconds from the last execution of the loop)

```
d_time = delta_time / 1000000;                                          //Convert delta_time to seconds
AirDensity = 1.07* power(2.718,-.00005*Altitude);                       //How dense is the air right now?

TermVel = sqrt(2 * Mass * Gravity / AirDensity * Area * DragCoeff);     //Terminal Velocity at our altitude
Velocity = Velocity + Acceleration * d_time;                            //Acceleration added
Drag = 0.5 * AirDensity * sqr(Velocity)* DragCoeff * Area;              //Drag calculated
Velocity = Velocity - (clamp(Drag, 0, TermVel) * d_time);               //Drag subtracted
Altitude = Altitude - Velocity * d_time;                                //Update the position

```

Thanks ever so much for your kind help in understanding what I've done wrong here.

SS

---

**Edit:** Thanks, Jason... I think I have the correct changes made... but my mass of "5" was causing it to behave really poorly.... the velocity went way negative... so I increased the mass significantly, and it seems to behave better... I will explore it a bit more.

Does it look like I have it right?

Thank you again, ever so much.

SS

# Answer
> 2 votes
There are several errors here:

1. There is not a 1/mass term in the drag calculation. Drag is a force, you need to divide by the mass to turn it into an acceleration before you apply it to the velocity.
2. Acceleration due to gravity is 9.8m^2, regardless of mass. There is no 1/mass term here.
3. You should not clamp drag to the terminal velocity. Drag is a force (or acceleration, if converted using `F=ma`) *not* a velocity. Clamp compares its arguments to each other, and it is simply meaningless to compare a velocity with a force/acceleration.
4. As a corollary to the above, the terminal velocity is a phenomenon where the forces of gravity and air resistance balance. The simulation will converge to this velocity; you do not need to calculate it at any point. It should also be noted that terminal velocity doesn't really apply when objects fall from the edge of space: they build too much velocity early in the fall for drag to slow them down to their nominal terminal velocity before they smack into the ground. This is because the terminal velocity in the thinner atmosphere is much higher than that of the velocity in the lower atmosphere.
5. You need to apply drag to the opposite direction of velocity, and ensure that the application of drag does not change the sign of velocity. Note this does not mean clamping drag to velocity, or to terminal velocity. It should be clear how to achieve this "no changing sign," but you will need to fix the other problems first.

It looks like you are trying to be physically accurate, which means this isn't really something you can construct yourself unless you understand the physics. You should find a physics reference and transcribe those equations rather than trying to synthesize your own.

---
Tags: projectile-physics
---


# Question
Title: Generating a particle effect on top of a GUIElement (Unity)
I am working in Unity on a 2D project which is using C#.

I have a number of guitextures which are hearts in order to create a sort of life meter. I would like when the player loses a heart for the heart to change into a skull in a puff of smoke. I currently have the hearts correctly turning into skulls, and a puff of smoke is generated, however the smoke is created in the wrong location.

The smoke is currently generated by:

```
GameObject smokeObj = (GameObject)Instantiate (smoke, transform.TransformPoint(transform.position), Quaternion.identity);

```

I have also tried:

```
GameObject smokeObj = (GameObject)Instantiate (smoke, transform.position, Quaternion.identity);

```

I know that the reason that the smoke is created in to wrong location is due to GUIElements using a different coordinate system than other gameObjects.

How can I create the smoke in the correct location?

This is a 2D project and I am currently using Unity 4.5of6, with windows 8.1.

Thank you for your assistance, if you have any questions please do not hesitate to ask.

EDIT: I have also tried the following, yet it also works incorrectly:

```
Vector3 worldPos = cam.ViewportToWorldPoint(transform.localPosition + Vector3.forward);
        worldPos.z=0;
        GameObject smokeObj = (GameObject)Instantiate (smoke, worldPos, Quaternion.identity);
        Debug.Log(worldPos);
                //smokeObj.layer = 5;
                smokeObj.transform.parent = this.transform;

```

# Answer
> 1 votes
You can convert viewport space coordinates into world space coordinates using Camera.ViewportToWorldPointSwitch and use the returned position to instantiate your smoke particles at correct position.

---
Tags: c#, unity, gui, particles, unityscript
---


title: Bodies going through the walls of a box

text:
# Question
Title: Bodies going through the walls of a box
I have a game where the user controls a box to collect falling balls. However, very often the balls will just fall through the walls of the box and be flung away. What could be causing the balls to do that?

Here is a video of the issue.

Here's how I'm creating the box and the balls:

```
//BOX CODE

private Body pbox() {

    pbdef = new BodyDef();
    PolygonShape shape=new PolygonShape();
    pbdef.type=BodyType.StaticBody;
    pbdef.position.set(Gdx.graphics.getWidth()/2,100);
    Body body1=world.createBody(pbdef);
    FixtureDef fdef = new FixtureDef();
    shape.setAsBox(30, 5);
    fdef.shape=shape;
    fdef.density=1;
    fdef.friction=0.5f;
    body1.createFixture(fdef);
    //
    shape.setAsBox(5, 20,new Vector2(-25,15),0);
    fdef.shape=shape;
    fdef.density=1;
    fdef.friction=0.5f;
    body1.createFixture(fdef);
    fdef = new FixtureDef();
    //
    shape.setAsBox(5, 20,new Vector2(25,15),0);
    fdef.shape=shape;
    fdef.density=1;
    fdef.friction=0.5f;
    body1.createFixture(fdef);
    body1.setGravityScale(-3);
    body1.setBullet(true);
    return body1;

}
//BALLS CODE

private void spawner() {

    bbdef= new BodyDef();
    FixtureDef fdef = new FixtureDef();
    CircleShape circle = new CircleShape();
    bbdef.type=BodyType.DynamicBody;
    bbdef.position.set(Gdx.graphics.getWidth()/2,Gdx.graphics.getHeight());
    bbody = world.createBody(bbdef);
    circle.setRadius(5);
    fdef.shape=circle;
    fdef.density=0;
    fdef.friction=0;
    bbody.createFixture(fdef).setUserData("ball");
    bbody.setBullet(true);

}

```

# Answer
> 1 votes
I'm assuming that you may be doing setTransform() on PBox to move the player around based on mouse positions. If that's the case, it is bound to happen, since setTransform occurs outside of the physics calculations.

Consider adding a Joint to drag the pBox around (with large force).

---
Tags: java, libgdx, box2d
---


title: How do I find the tile I'm standing on?

text:
# Question
Title: How do I find the tile I'm standing on?
I want to get the specific tile I am standing on. My Tiles are in an `Arraylist` so I can destroy them later. How can I do this?

Here's my `Level`-class (where my `List`s are):

```
public class Level {
    public int width,height;
    public int xScrool,yScrool;

    private Mouse mouse;

    public Random random;
    public List<Tile> tiles;
    public List<Entity> entities;

    public Level(int width,int height,int xs,int ys,Mouse mouse)
    {
        this.xScrool = xs;
        this.yScrool = ys;
        this.width = width;
        this.height = height;
        this.mouse = mouse;
        entities = new ArrayList<Entity>();
        random = new Random ();
        generate();
    }

    public void setScrool(int xScrool,int yScrool)
    {
        this.xScrool = xScrool;
        this.yScrool = yScrool;
    }

    private void generate ()
    {
        int Row = -1;
        for(int y = 0; y < height;y++)
        {
            int RandomHeight = random.nextInt (3);
            for(int x = 0; x < width;x++)
            {
                tiles.add ( new Tile_Dirt ( Sprite.dirtTile,x,RandomHeight) ); // This is where the tiles get added to my list
            }
        }
    }

    public void init(Level level)
    {
        for(int i = 0;i < entities.size ();i++)
        {
            entities.get ( i ).init (level);
        }
    }

    public void update()
    {
        if(mouse.getMouseB () == 1)
        {

        }

        for(int i = 0;i < entities.size ();i++)
        {
            entities.get ( i ).update ();
        }

    }

    public void render(int xScrool,int yScrool,Screen screen)
    {
        screen.setOffset ( xScrool,yScrool );
        for(int i = 0; i < tiles.size (); i++)
        {
            tiles.get (i).render (screen);
        }

        for(int i = 0;i < entities.size ();i++)
        {
            entities.get ( i ).render (screen);
        }
    }

    public Tile getTile(int x,int y)
    {
        return tiles.get (  ); // I have no clue how i can gonna make this one
    }

}

```

# Answer
You're not even using the `y` coordinate when you're storing your tiles. You're just using `x` and some random value: \`( Sprite.dirtTile,x,RandomHeight)'. Which likely means you'll have tiles stacked on top of each other, meaning your list is going to contain some tiles that are occupying the same position.

However, the naive approach to finding the tile at a specific `x, y`, given how you're storing your tiles, is to iterate through the list until you find a tile matching those coordinates.

```
public Tile getTile(int x,int y)
{
    for(Tile tile : tiles) {
       if(tile.x == x && tile.y == y)
          return tile;
    }
    //We didn't find a tile matching that position
    return null;
}

```

Granted, if there are duplicates, this likely won't find the one you're seeing on screen. Since you're drawing tiles by iterating through the list, this means in the case of duplicates, the *last* instance of a tile will be drawn over the others. The code above will find the *first* instance of a tile at a specific position.

All in all, I suggest you try again with this code. Rewrite it with the requirement of accessing an arbitrary position in mind. Think about how a two dimensional array might help in that situation. Also consider how you're placing tiles and if they're actually ending up where you want them to.
> 1 votes

---
Tags: java, 2d, tiles
---


title: Creating A TickRate Class

text:
# Question
Title: Creating A TickRate Class
I need to implement tickrate into my engine to handle timed events such as pushing out entity updates and I don't know where to start.

I have access to a timer which allows me get the time in milliseconds since the device has been initialized.

When I try to brainstorm on the correct approach to take one of the main things that I get stopped up on is that on the client side I should allow the framerate to run as fast as it can, however if I want the tickrate to run at 60 and the client FPS is less than 60 how can 60 ticks execute if the main loop wont run at least 60 times a second due to it being slowed down by the fps?

Can anyone explain how to properly implement tickrate? Thank you for your time.

# Answer
> 2 votes
The approach by *Narrateur du chaos* is commonly called the delta-t approach. But there is also another approach, the game-tick approach. In this approach you keep track of how long the game is running in real-time and how much time the game-world has processed. After each graphics frame you check how far the game world lacks behind the real world and do updates until it has catched up.

```
 MS_PER_TICK = 1000 / 60  // the time one game-tick represents

 PROCESSED_TIME = currentTimeInMs();

 while game is running
      drawFrame()
      while (PROCESSED_TIME + MS_PER_TICK) < currentTimeInMs()
        updateGame()
        PROCESSED_TIME += MS_PER_TICK

```

Personally, I prefer this approach because it makes your update-functions a lot easier to write when you know it always represents a fixed timespan and don't have to take the delta-t into account for every single calculation.

# Answer
> 1 votes
I'm not an experienced developer, but your question seems straightforward enough. Your `main()` must look like this:

```
int main(args)
{
    // Code, declarations, whatever
    MainClass game(arg1, arg2...);

    try
    {
          while (game.continue())
          {
               float ticks = timeSinceThatFunctionWasLastCalled();
               game.update(ticks);
          }

          return EXIT_SUCCESS
    }
    catch (err) { // Ideally, no exception must ever reach this point in
                  // the final version, or it means your game crashed, but
                  // whatever.
          return EXIT_FAILURE;
    }
}

```

Every class in your code whose instances must be altered every tick must then have some sort of function like `void update(float ticks);` that is called once every time `game::update()` is called.

---
Tags: c++, timer, timing, timestep
---


# Question
Title: When and how to apply affine translations to vertices of a mesh with LWJGL
So, I have a rigid body class, containing a list of vertices and a 4x4 transformation matrix. At the moment, I'm applying the transformation matrix to each vertex individually, and am unable to revert the translation after rendering(multiplying the vertices by the inverse causes massive model distortion), so it just keeps stacking up, and eventually the model just violently wobbles back and forth. I understand mathematically how to accomplish the transformation, I'm just not sure where to actually DO the transformation without distorting the model. I'm using Java and LWJGL, and porting the Cyclone physics engine to Java.

# Answer
> 0 votes
Seeing as you want to keep the state of the matrix before the translation, I'd suggest using a matrixstack, this openGL tutorial explains it quite well: http://www.arcsynthesis.org/gltut/Positioning/Tut06%20Fun%20with%20Matrices.html

However, for this method I assume you perform your matrix multiplication with the vertices in GLSL. If that's not the case then you'd have to keep an original of the vertex list as well, unaltered by any translation you'd want to perform. This double management of vertices may be an issue depending on your situation, if so then instead I guess you'd have to create some sort of system that creates "undo-matrices" with each translation.

---
Tags: opengl, java, rendering, lwjgl, transformation
---


# Question
Title: organizing animation in Flash CS6 for sprite sheets
Can I make a sprite sheet of a character which contains animated movies inside the main movie-symbol? I tried to export it, but those movies inside the main one are not animated. Thanks

# Answer
Unfortunately I don't think you can do that. Even if you were to export the animation itself as a sequence of PNGs, nested animation doesn't get exported in Flash, and the same applies to sprite sheets.

You can export sprite sheets for the animated movies inside the main one and, as long as it doesn't rely on movie clips inside it animating, it will export fine. Only the first level animation will export.

Alternatively, you can use graphics instead of movie clips. Then from the top movie clip, select the frame the graphic should be in. Look for the options in the Looping section of the graphics properties.
> 1 votes

---
Tags: spritesheet
---


# Question
Title: How can I run on multiple platforms using a custom engine?
Game engines like Unity and Unreal can run on mutiple platforms. I am wondering how they do this.

I have been using C++ and OpenGL for a while, and what I am looking for is resources to integrate something that will allow me run on different platforms without rewriting. Something like LibGDX where you write code using a base API and then the API converts it to HTML, Android, iOS, et cetera. I am aware that I can use another engine instead of writing my own but I'm interested in the learning experience.

# Answer
Port your engine to each platform. There's nothing special about it. If you have some code that is Windows-only, then either add some #ifdef logic in the file or add a second file (so you'd have `FooWindows.cpp` and `FooLinux.cpp` or whatever) that implements that feature on the other OS(es) you care about.

The one-click publish stuff that an engine like Unity has is allowed because Unity itself is never modified by the end-user. You're just writing scripts and data, so the engine has pre-built binaries for all the platforms and the publish button just bundles those binaries together with the data.

Other engines rely on build systems and cross-compilers to create the compiled game when needed, just like you would do with any non-game cross-platform application.

For things like HTML5, there are tools like emscripten that can compile a C++ application to run in JavaScript. You basically just need to make another port of your engine for emscripten (since it can't use any arbitrary C++ library/feature).

You don't have to rewrite your whole game, but you're definitely going to have to do a lot of development, coding, and porting work for each new platform you want to support.
> 27 votes

# Answer
There's no magic bullet here. If you want your game to run on multiple platforms, you have to write code for multiple platforms (or leverage third-party libraries that already do this for you).

The things you are asking for don't align: you say (emphasis mine)

> what I am looking for is resources to integrate something that will allow me run on different platforms *without rewriting*

but also that (emphasis mine again)

> I am aware that I can use another engine instead of writing my own but *I'm interested in the learning experience*.

You are pretty much going to have to do one or the other: elect to use a third-party library, engine and/or toolchain that provides cross-platform support for you, or build your own by writing cross-platform code (designing your own abstraction over the platforms you have available to you, and implementing that abstraction for each platform).

Game engines like Unreal or Unity that support this either recompile your code against the appropriate platform abstraction, or require you to build a library or DLL against their internal APIs, which they load from a platform-specific driver executable which *they* have compiled for the appropriate platform.
> 14 votes

# Answer
I'm building a cross-platform game engine at the moment. I'm using SDL, which is an excellent (and suitably low level) cross-platform library for building graphics applications, to ease the pain.

Beyond this, though, is a lot of "custom code" for each platform. This you just have to get through. I've found it to be a very small fraction of my development time so far, mostly spent looking up docs for systems I'm not as familiar with as my native Linux.

I'd discourage you from using `#ifdef` everywhere throughout your code. Instead, build abstractions around key primitives (an example of such a primitive might be a TCP socket).

When you encounter a new problem which requires different solutions per-environment, ask yourself *"can I solve this problem using only the cross-platform primitives that I've already constructed?"* If the answer is yes: voila, simple cross-platform code. Otherwise figure out what primitives you're missing and implement them.
> 3 votes

# Answer
Contrary to the other two answers (which are rightfully C++-specific), there is another way. Some architectures that come to mind:

* **Port your engine:** Modify or write code so that it works across multiple platforms. This is addressed in the answers above.
* **Write something above a cross-platform library:** This is the example of libGDX, which runs on Java. Java runs on Desktop, Android, and iOS (via RoboVM). By using something like Java, you get the benefit of free additional platforms when the underlying library/tool supports them. In this case, when RoboVM came out, libGDX (almost) "just works" on iOS.
* **Write a code generator:** This is the approach of Haxe and other tools. You have a core language (eg. Haxe/AS3), and you write converters that generate output for other languages. Eg. Haxe converts to C++ for Desktop, Java (I think) for Android, etc.

Personally, I find the approach of libGDX is the simplest: find a language or platform that meets your needs, and write on top. Code generation and portable engines are complex and hard to write well.

libGDX is actually a great choice, since it hits both major mobile phones, desktop, and web (via applets or Google's web compiler).
> 2 votes

# Answer
If you want to do this "from scratch" as a learning experience then you'll need to use the Win32 API where you can find information about opening a window and an OpenGL context on MSDN and on the OpenGL wiki (http://www.opengl.org/wiki/Creating\_an\_OpenGL\_Context\_(WGL)). For Linux get a second hand copy of the O'Reilly *Xlib Programming Manual* and the *Xlib Reference Manual* and also read up on GLX (OpenGL Extension to the X Window System). See also http://www.opengl.org/wiki/Tutorial:\_OpenGL\_3.0\_Context\_Creation\_(GLX)

Then you just need to provide the same API to your application with functions that do the same thing (e.g. open a window) but have different implementations for each platform. You rewrite parts of your engine for different platforms. Then a game you write using the engine you only have to write once but it will work on different platforms.
> 0 votes

---
Tags: c++, cross-platform
---


# Question
Title: Why do we say things are rotated around the z-axis in a space graph?
I've embarked on a journey of game development. I need to learn lots of 3D terminology, since I want to make 3D games. I learned that X is to the right, Y is up, and Z is towards you. Then why when a spatial is rotated we say it is rotated around the z-axis? I couldn't find a specific answer online.

Thanks for reading, and I look forward to your answer.

# Answer
> 4 votes
All 3D rotation must occur about some axis. That's what 3D rotation *is*. However, not all such rotation occurs about the *Z axis*. Rotation can be about *any* axis: X, Y, Z or an arbitrary axis not aligned with any of the principle axes of the coordinate system.

What it sounds like you're referring to is the convention of rotating 2D shapes in a 2D plane about "the Z axis." 2D rotation occurs about a point, not an axis. However, if you interpret the 2D plane in question as being embedded within a 3D space, the point about which you are rotating becomes a line, and line is perpendicular to the plane you are rotating in: the Z axis, since it is at right angles to the existing X and Y axes of the 2D plane.

That's just a convention, though. In fact, so is the idea that "+X is to the right." It's certainly possible to define a coordinate system where +X is to the left, or towards you. Indeed, even in the conventional system you described, +Z could be towards or away from you depending on the handedness of the system.

# Answer
> 1 votes
They come from two different conventions for aligning the world axes. These conventions are known as Z-up and Y-up.

**Z-up**

In mathematics, engineering and most every field but computer graphics, the convention is for the X axis and Y axis to represent the ground plane and the Z axis to point up.

**Y-up**

When computer graphics was in its infancy, the X axis and Y axis were associated with the width and height of the screen. When the Z axis was added for 3D graphics, it was natural for graphics programmers to think of Z as being "in" and "out" of the screen.

This, in itself, is not incompatible with mathematics and engineering. It just means that the default direction that a camera looks is down towards the ground plane.

However, some of the early computer graphics programmers found it more intuitive to think of the default view of the camera to be parallel to the ground, similar to the way their monitor was arranged in their office. This led to them thinking of Z as being forward/back in the world and Y being up/down.

Modern games use both conventions and major content creation tools like Maya support both.

---
Tags: 3d, rotation, spaces
---


# Question
Title: GLFW3. Destroying and create new window results in a black window
I am trying to write a fullscreen toggle handler and running into an issue.

In order to change between fullscreen and windowed I need to destroy the current window and create a new one with the 'monitor' parameter changed. I have written this and the program changes between windowed and fullscreen fine. However the new window that is created is not being rendered to and is black.

For simplicity I have reduced the code to the following that just creates a new window with the same parameters:

```
/* generic set up stuff */

//main draw loop
while (!glfwWindowShouldClose(window)) {

    /* generic draw stuff */

    if (GLFW_PRESS == glfwGetKey(window, GLFW_KEY_F)){
        glfwDestroyWindow(window);
        window = glfwCreateWindow(g_gl_width, g_gl_height, "Title", NULL, NULL);
        glfwMakeContextCurrent(window);
    }
}

```

When the program first loads everything renders fine. When I hit F, a new window is created but it stays black.

Any ideas?

Kind regards.

# Answer
You need to set up the viewport again, by calling glViewport.

Also, I believe a context is bound to the window and not to the thread, but I could be wrong. If this is the case, then you'll have to set up all your resources, buffers, etc..
> 1 votes

---
Tags: glfw
---


title: User vs Player Model

text:
# Question
Title: User vs Player Model
A lot of the online games out there have this concept of "User" or "Profile", and the concept of "Player". The "User" has username, password, lifetime stats, ... etc. The player concept is per game basis, and holds volatile information around the currently played match. That's how I picture it, at least.

I am puzzled about how is that usually implemented? Does the player class hold a pointer to the User object, or does it inherit from user? or maybe something else?

I can't completely decouple the two, since during the match, I need to send messages back and forth between "user" and "player" (e.g. update achievements)

# Answer
> 13 votes
They're typically not even handled by the same machine, much less the same codebase. The user profile is handing by a service that deals only with users. The simulation server deals with in-game things. There may even be another session server that ties the two together.

The simulation server has an ID that corresponds to each user, so its `Player` class might look something like:

```
struct Player {
  UserId _user;
  PlayerId _player;
  int _health;
  // etc.
};

```

For anything that affects the user account, the server sends a message to the user service telling it what happened, e.g.

```
struct UserAchievementMessage : public UserMessage {
  UserId _user;
  AchievementId _achievement;
  uint64 _timestamp;
  // etc.
};

```

So if the user gets an achievement for something happening in game, the simulation server just lets the user service know (usually via some kind of messaging service, e.g. RabbitMQ or the like) and then forgets about it (since it's not the simulation server's job to care about users).

If the user service has to notify any in-game matches, it can again use a messaging service (or proxy through a match service) to notify any player instances of that user that something changed. For instance, the match service knows about all matches running, who's in those matches, etc., so a user service can just ask the match service to notify all simulation servers that have an instance of that user (a player) about whatever it was that changed. Clever use of RabbitMQ or the like can remove the need for a proxy service, too.

Samller/simpler games often just have one or two servers and overlap a lot of functionality, but this is due to a lack of time/budget and not because of good engineering.

In any case, `User` and `Player` (or whatever terms you use) are two entirely separate things. The coupling, if any, should be as light as possible. Unique IDs are typically the way to go. Each user could have a UUID, for instance, and any `Player` instance just contains that UUID. If something that happens to a `Player` affects a `User`, call a method or send a message to the `UserManager` with the affected UUID and other details. The `UserManager` can then update internal data structures, send network messages, or do whatever other implementation details it needs to do.

---
Tags: architecture, design-patterns
---


# Question
Title: What formula does this projectile velocity code derive from?
```
//Calculate the velocity needed to throw the object to the target at specified angle.
float projectile_Velocity =
            target_Distance / (Mathf.Sin(2 * firingAngle * Mathf.Deg2Rad) / gravity);

```

Which formula is used to derive this projectile code?

# Answer
The formula comes from the combination of one of the equations of linear acceleration (v=u+at), v =d/t and components of velocity.

The vertical velocity component = vel\*sin(ang). Using the equation of linear acceleration above with u=vel\*sin(ang), v=-vel\*sin(ang) and a=-g and rearranging for t we get the time for the projectile to hit the ground after being fired.

```
t = 2*vel*sin(ang)/g

```

Now using v=d/t (constant velocity formula) with the horizontal velocity component: v=vel\*cos(ang), d=dist and t is as above we get the following:

```
dist =2*vel*vel*sin(ang)*cos(ang)/g
vel = sqrt(dist /(sin(2*ang)/g)) using the trigonometric identity that 2*sinx*cosx=sin(2x)

```

Which is almost what you got... Not sure why we have a square root difference. But that's where the formula is coming from anyways.
> 3 votes

---
Tags: projectile-physics
---


# Question
Title: How do I make a daily challenge on a game with randomly generated levels?
I am currently making a game with randomly made levels, but I have an interest in making everyone play the same level in a daily challenge section, like Spelunky.

At first I thought about letting the clients decide the seed based on their date, but dates can be locally spoofed.

I have access to a parse.com free account, so I can execute code in the cloud and expect results back. So then I considered asking cloud code for a hash based on the current date, but this could be spoofed to play a different level while sending the server the score for THAT level instead of the daily one.

Then I thought of encrypting the date in the server and decrypting it on the client, but then this might be problematic if I used symmetrical encryption. So... maybe use assymetrical encryption?

Am I missing a simpler solution here? This feels like I'm overcomplicating myself, but I'm not sure. Is there a generally accepted solution for this kind of problem? I haven't found anything after googling for a good while.

# Answer
As long as the client can't be trusted, nothing will be secure short of a server-side solution. Following your example, even if you managed to transfer the seed securely, all the client has to do is to spoof the score being sent to the server.

If the client is secure, then strong symmetrical encryption should do the trick just fine. Asymmetrical is not necessary, as the server is assumed secure, so both passwords are safe.

If the client is not secure, then you're going to have to do cheat detection on the server. Hopefully you don't have to recreate the whole simulation to validate the score sent, and you can distill it to a few key areas that will be hard for a hacker to recreate if they played a different level. This will depend highly on your design. And note that if you're not using parse.com already, you can always have it serve as a middleman with the score server.

The good news is that you could add this cheat-detection step down the road if you find your client has been compromised. The key with cheat prevention is to put as much effort as necessary, but not more. If you expect rampant cheating, go all in, but if not, start with something simple, just send the key down from the server in plaintext, and see what happens. If that fails, then encrypt it. If that fails, then add server-side validation.
> 4 votes

# Answer
You could use a simpler approach using a hash and a validation algorithm.
Instead of encrypting and decrypting the date use the hash directly and apply a mechanism to make sure this hash is valid.
For instance the last 5 bits of the hash could be the sum of the bits of the rest of the hash. All hashes which don't oblige to this rule are generated by someone else. This way you can avoid brute force attacks to some extend.
Unless it is really needed though try not to complicate this.
Building the actual game should be your first priority.
Of course as Sergio said in his answer, if you can't trust the client nothing is safe in the long run.
> 1 votes

---
Tags: procedural-generation, random
---


title: Really simple count down timer

text:
# Question
Title: Really simple count down timer
I'm making a little 2D tank game that fires bullets depending on where you click (This has been done and works a treat).

I'm currently working on a timer class with a simple function that displays a little countdown depending on the inputted time. (This will be used for bullet fire delays).

`bool timer makeTimer(int waitTime)`

This is the start of the timer, it is a simple boolean function which returns "true" when the timer has reached 0.

I can make it decrement down until it reaches 0 easily, but the part I'm having issues with is making it countdown based on an actual time event, so once per second. I've tried lots of different things but I just can't get this darn part to work.

The variables I have to work with are;

```
waitTime // inputted timeDelay
sf::Clock // To show the elapsed time per frame
sf::seconds(1) // Not too sure if I need this

```

So, to wrap up. \- I'm trying to get it to countdown from the inputted time once per second.

# Answer
SFML2 allows arithemic operations on `sf::Time`, like substracting or comparing timestamps. It will be more reliable and consistent to compare elapsed time with desired delay, rether than counting down, especially integer of milliseconds(?).

Things like repeated shots are easier (imo) to implement, if you treat fire delays as locks, i.e. next bullet will not fire until enough time passed since previous shot.

```
sf::Clock game_clock;
sf::Time shot_delay = sf::seconds(0.25);
sf::Time last_fire_timestamp;
...

sf::Time now = game_clock.getElapsedTime();
if(want_fire_bullet())
{
    if((now - last_fire_timestamp) >= shot_delay)
    {
        last_fire_timestamp = now;
        fire();
    }
}

```
> 1 votes

# Answer
Subtract the elapsed time for the current frame from the timer's current value. When the timer value goes zero or negative, you know time's up.

Assuming **SFML 2.0**, you can do:

```
sf::Time elapsed = clock.restart();
timer.value -= elapsed.asMilliseconds();

```

...or `elapsed.asSeconds()`, or `.asMicroseconds()`, as you like; whatever units your timer uses.
> 0 votes

---
Tags: c++, sfml, timestep
---


# Question
Title: How to differentiate between instantiated objects in Unity?
I'm currently trying to solve a way to go about the following problem before I start writing any code (the old fashioned pen and paper way) but I'm not sure how I could achieve the following.

I'm going to have an object with a Collider attached to it in my scene. As my instantiated enemies pass through this Collider they will be added to an ArrayList which lets the object in question keep track of the enemies. The problem I can't figure out is how to determine which object is which.

I will have a script attached to my main camera which will be responsible for spawning the enemy units, I'll be using a while loop in sudo code it would look something like this.

```
public Transform; (Attach the prefab in the inspector)

Somefunction() {

int i = 0;
arraylist goes here;

while (i < 10) {
arraylist[i] = Newly instantiated object.

}
}

```

My object with the collider will then have something like the following:

```
OnTriggerEnter() {
get specific object somehow
add to arraylist
}

```

I can't use the tag function because all the objects will have the same tag, the only thing I assume will be different is the position of the object in the spawn array (ie: arraylist\[1\] arraylist\[2\] etc.)

If I created a public accessor method on the trigger object could I call this method to return a string name or something special that identifies the object uniquely compared to the rest of the objects in the scene or does Unity already do this somehow natively?

# Answer
> 2 votes
You could just add a script component that simply contains an int for an id with the start method containing some logic to initialize it to a unique value. Once you do that, you can use a hash table for storing and accessing the gameObjects with their ids.

# Answer
> 1 votes
First things first: do not use `ArrayList`. Use `List<T>`, for it will make your life simpler and nimbler.

How you keep track of these `GameObject`s depends on what you want to do with them. Hashtables and Dictionaries are a great way to associate objects with other data. (See the .Net documentation for the generic dictionary, nearby you'll also find `List<T>`'s docs).

But, if you want to get a reference to the `GameObject,` all `Component` subclasses (including `Collider`, `Transform` and any `MonoBehaviour`) all have a reference to the GameObject they're attached to by calling `theComponentIdentifier.gameobject`. This is probably what you want to store.

# Answer
> 0 votes
You could always change the name.

```
//make ten objects
for(i=1;i<=10;i++){
    var theOb = Instantiate(myPrefab,transform.position,transform.rotation);
    theOb.name = "ob"+i;  //its name will include an index number
    theOb.parent = transform; //it will be a child object
}

//modify the third object, finding it as a child
transform.Find("ob3").Translate(Vector3.right);

//modify the eighth object, finding it by a static GameObject method
GameObject.Find("ob8").transform.Rotate(Vector3.up);

```

# Answer
> 0 votes
(I'm having a hard time understanding your explanation of what you're trying to do. So I'm answering based on what I *think* you're trying to do, but my apologies if I misunderstood.)

I would use a Dictionary for this purpose. That data type is great for associating other data with specific objects. Also I would use List instead of ArrayList, so both the Dictionary and List would have types declared in \<\>. So like I would declare (c#):

```
public Dictionary<GameObject, List<GameObject>> objectMap;
void Start() {
  objectMap = new Dictionary<GameObject, List<GameObject>>();
}

```

then the collider script would look like:

```
void onTriggerEnter() {

  // in case there isn't a list for this object yet
  if (camera.objectMap[this.gameObject] == null) {
    camera.objectMap[this.gameObject] = new List<GameObject>();
  }

  // mapping objects to lists happens here
  camera.objectMap[this.gameObject].Add(hitObject);
}

```

In this way the Dictionary of objects maps different objects to different lists.

(Michael's answer also mentions Dictionaries, but isn't very specific about them)

---
Tags: unity, software-engineering, objects
---


# Question
Title: Algorithm for sensing mouse movements like a wiimote
I want to make a driving game where you can do tricks with your mouse when you hold down LMB. Ex. if you move it up in a straight line really fast (your cursor goes from the bottom to the top of the screen in, say, 0.1s), your bike will do a flip. If you do a quick circular movement, your bike will spin. Essentially, drawing a shape onto the screen = performing a move.

How would this be sensed? Currently, I can only think of having shapes defined by coordinates relative to some starting position (it would be some function taking in your mouse down coords), and within a certain time frame, every update loop will check to see if the current mouse coordinate pair is between the current preset one and the next preset one (and within a margin of error). To know which shape to use, you'd loop through the shape list, see whether or not the mouse coord is invalid for the current shape, and knock it off the possibilities if true.

Example circle path:

* X = Coordinate
* Red arrows = Expected mouse movement path
* Green = Margin of Error

Problems I can see with this algorithm right now:

* If I have a lot of moves, then there are a lot of shapes to loop through every frame before the deduction process kicks in
* It's not an optimal solution for doing consecutive moves in a short timespan, because the player would have to release LMB before pressing it down again for the system to sense that a new shape is starting
* Tiny circles vs big circles, how wide the margin of error would need to be to allow for both, and how that would affect calculations (clashing with other shapes that have similar valid spaces)
* What if you draw circles like flattened, diagonally skewed ovals, even when you're not trying to do it fast? It is indeed a circular motion, but maybe diagonally skewed ovals are for another move. Is it okay to just shun your artistic ability?
* How much time will it take before the system recognizes that you're doing a specific move? Must a full circle be completed before any bike spinning occurs?

What would be a better algorithm?

# Answer
> 1 votes
I once created a system like this as an experiment. The way I did it was to abstract the pixel-perfect path of the mouse away into a series of quantized directions of travel (rounded to 45° for my purposes). My primitive matching algorithm just tried to fit a pattern to the series when the user released the mouse button.

If I were to do it again I would add in these features to make it more robust:

* Understand that a curve could be sampled as both 45° and 90° turns
* Be able to start circles at any point
* Do early elimination of patterns by guessing when the user has started a gesture (so they don't have to use the mouse button)
* Sample only every few frames and spread pattern matching over the whole interval

Actually, your proposal could be viable if you took that last point into consideration. Although I barely dabble in either field, I'm sure some research into signal processing and machine learning could benefit the construction of such a system.

---
Tags: mouse, control, motion-control
---


# Question
Title: Retrieve the original prefab from a game object
How would one proceed to retrieve the original prefab used for instantiating an object?

In the editor these two functions work :

```
        Debug.Log(PrefabUtility.GetPrefabParent(gameObject));
        Debug.Log(PrefabUtility.GetPrefabObject(gameObject));

```

But I need something that works in the release version.

I have objects that can be transported between scenes and I need to save their data and original prefab to be able to instantiate them outside of the scene they have been originally instantiated.

---

ie:

* Game designers create new prefabs.
* Game designers create objects from prefabs and place them in scenes (50 to 150 scenes).
* Game is played and objects are moved across scenes.
* Game is saved and infos about objects which have moved are saved in the save streams (files or network).

This is where I got stuck. Currently, to palliate to the shortcomings, we're saving the name of the prefab in the prefab. But each time a prefab is moved, renamed or duplicated the string must be changed too, sometimes the objects created from the prefab keep the original name (game designer might have edited the prefabPath field).

Maybe there is a better way to achieve proper save games without having to access to the original prefab/name. But currently we keep the saves segmented on a per level basis (easier and safer to save/load to files and transfer the save games to/from servers)

# Answer
> 4 votes
**Simple Answer**

Use a class to load the original prefab from `Resources.Load(string prefabPath, typeof(GameObject));`

Store this returned prefab into a resource pool class by path key. For instance: `Dictionary<string, GameObject> prefabLookup;`

You can then grab the original prefab anytime you need it.

Use a helper method to automatically load at runtime.

```
public static GameObject GrabPrefab(string path)
{
     if(!prefabLookup.ContainsKey(path))
     {
          // Load prefab and add to dictionary...
     }

     return prefabLookup[path];
}

```

I would also suggest unloading un-used assets from memory on level change. This will keep you from hitting a memory limit.

# Answer
> -1 votes
For this specific problem, I suggest you create a global class in which you put those variables you need for other levels so you can always access them.

---
Tags: unity, objects, savegame, unityscript
---


# Question
Title: What does the term "channel" mean when used in regards to computer graphics?
I was studying terminology for computer graphics, and this statement came up that confused me.

> The image can have alpha channels for transparency.

I tried searching for the meaning of the term "alpha channel," but I got really confused by the definition which used another concept called a "channel." I'm not really sure what this means, so could someone be kind enough to please explain this term to me?

# Answer
Digital colors can be made up of three components: red, green, and blue. Combine these together, and you get final color, eg. yellow is 100% red, 100% green and 0% blue.

The fourth component is, as you mentioned, transparency. Together, these form the tuple `RGBA` (red, green, blue, alpha) which represent an image.

Now, instead of pixels, think about it another way: what if you split up the image into four layers? You could separate them like this:

* All the red pixels on one layer
* All the green pixels on one layer
* All the blue pixels on one layer
* A value indicating transparency on one layer

These layers are actually called "channels." Here's what they look like in a sample image:

In this image, you can see only the red pixels on the red channel; likewise for green and blue. That's all it means - a way of thinking about images as "channels" of separate colours which are combined together.
> 40 votes

# Answer
The term comes from the definition of "channel" that means a specific portion of a frequency spectrum. In this case, the red, green and blue components of a color are often referred to as "channels" (since red, green and blue light are portions of the visible light spectrum).

Since alpha is another component of color in computer graphics (although not one strictly related to visible light like that others), it's also called a channel.
> 7 votes

# Answer
Alpha channels were actually invented by George Lucas's company Industrial Light & Magic (actually Alvy Ray Smith did most of the work while working there, who was previously employed by Xerox PARC - who we can thank for almost everything in modern computing!).

Alpha channels, in addition to doing cool effects like transparent window, transparent gradients, and realistic shadows, can be used for sub-pixel operations. In fact, the original use was because computer graphics at the time sucked. In order to overlay a nicely anti-aliased image onto a different background (or the background of a live movie), you end up with blocky edges. That won't do for a movie, and trying to anti-alias the images with the backgrounds takes too much CPU time. So .. the edges of the image are made semi-transparent (the alpha channel). This allows the background to show through at varying densities - mixing the colors of the two images together to anti-alias it. This is used everywhere these days, for example, to draw icons with much smoother edges than the resolution would normally allow - and you don't need to recreate the icon for different backgrounds.

Alpha channels are easily done in hardware. Early movie production machines had a "genlock" bit (which was available on Amiga and some Atari machines as well), which was basically an output pin that switched from computer output to video output. The pin was driven by a "transparency" bit in the output (usually with "hicolor" graphics modes 5:5:5 for RGB and 1 bit for transparency = 16 bits/pixel), which allowed easy overlay of computer generated context over live video without digitizing the video. This was later modified to be an analog output with an 8-bit DAC - so instead of switching between computer and live video, it blended it - removing the nasty blocky edges that the 1-bit technique used. Analog anti-aliasing!

Modern video cards can store multiple layers of information in memory at once and use the alpha layer to mix multiple layers of alpha transparency in hardware. This makes your "sprites" and other objects that need to be anti-aliased look nice. Instead of mixing to a fixed background color, the anti-aliasing uses the alpha-channel to mix on the fly. Of course, you can do all sorts of things with the alpha channel, but I hope this gives you a start. For more history, try wikipedia.
> 5 votes

# Answer
None of the other examples explain why it's alpha, though. It's from the expression in Alpha Compositing:

where Ca and Cb are the two input colour values and Co is the output combined colour.

Varying the alpha between 0 and 1 varies the colour between front and back composited images.

(Image processing also has "gamma", but not "beta" as far as I know)
> 3 votes

# Answer
All images have 1 or more "channels" of information. For example, the familiar RGB image type has 3 channels of information: Red, Green, and Blue. That is, every pixel in the image has 3 numbers associated with it (if each number is 8 bits, then that's a 24 bit image).

Alpha can add a 4th channel of information (so a 4th number associated with each pixel, and a 32 bit image). This extra channel can be used for a variety of purposes, but the most common purpose is transparency.

Common file formats with alpha channels are PNG and TGA.
> 2 votes

# Answer
In many image format, A pixel is defined as a vector with 4 components. RGB and alpha. In the perspective of whole image, you can select only each component of the pixel, and this provides a series of values. If you want to process only one component, then you can select the comonent of all the pixels of the image, and this is usually called a *channel*. A collection of one component for all pixels. Then alpha channel means collection of alpha component. Similarily, collection of each RGB components can be called red channel, green channel, and blue channel.
> 2 votes

# Answer
A pixel is a collection of components. Traditionally these components are red, green and blue, with each of them taking 8 bits of data.

As it is often advantageous to have memory aligned certain ways, these where sometimes packed into 32 bits of space each. This leaves 8 bits of extra data at the end of each pixel. As this is neither red, nor green, or blue, it needs a name -- and alpha was a relatively meaningless name.

Now, when you have an array of pixels arranged into a rectangle, you get this:

```
   RGBARGBARGBARGBA
   RGBARGBARGBARGBA
   RGBARGBARGBARGBA
   RGBARGBARGBARGBA

```

sometimes you want to only talk about one of the colors above, say red:

```
   R***R***R***R***
   R***R***R***R***
   R***R***R***R***
   R***R***R***R***

```

this sub selection of only one element of each pixel component is called a "channel" in the image. As the pixels have 4 components, this image has 4 channels.

There are other image formats where there is no alpha channel:

```
   RGBRGBRGBRGB
   RGBRGBRGBRGB
   RGBRGBRGBRGB
   RGBRGBRGBRGB

```

and there are formats with different number of bits per pixel component (3,5,8,16,32), and some have non-uniform bits per pixel component.

The channel becomes the "virtual" array of only one pixel component. (I say virtual, because there is a stride between each element, while arrays traditionally do not have such stride)

The RGB portion is not fixed either -- you could have a greyscale image with or without an alpha channel, you can have a CMYK image (Cyan Magenta Yellow blacK, usually in a subtractive color space), you can have an image that has a whole myriad of different color channels created by a specular raytracer or a scientific instrument.

While I have treated pixels as if they are always contiguous, it is also possible to have the channels be split over multiple locations, like this:

```
    RRRRGGGGBBBBAAAA
    RRRRGGGGBBBBAAAA
    RRRRGGGGBBBBAAAA
    RRRRGGGGBBBBAAAA

```

or even

```
    RRRR
    RRRR
    RRRR
    RRRR
    GGGG
    GGGG
    GGGG
    GGGG
    BBBB
    BBBB
    BBBB
    BBBB
    AAAA
    AAAA
    AAAA
    AAAA

```

or have RGB packed and A stored in a separate buffer.

This is uncommon in live data in games, because modern graphics cards are often designed around RGBA pixels. RGB can be handled uniformly, and with A adjacent quick calculations can be done that allow compositing of a RGBA pixel on top of a pre-painted background.

The alpha channel is often used for transparency information. Annoyingly, the max value of alpha is sometimes treated as transparent, and sometimes as opaque, by different code bases. This again is less common nowadays. Alpha channel has also been used for z-buffer ordering (how far the pixel is from the viewer) to allow unordered drawing to a scene, and traditionally mip mapping was done by shoving the 2x 2x (or 4x fewer pixels) lower resolution image into the alpha channel of the higher resolution image, recursively.

Even in a system that uses RGBA pixels, the meaning of these pixels can disagree. Does R measure the how much red a human sees, or how many photons of red should be emitted? This is the difference between linear and non-linear color spaces, and it impacts the correct way to composite said pixels with a transparency channel.
> 2 votes

---
Tags: graphics, art, transparency, color, terminology
---