title: Calculations for a camera system

text:
# Question
Title: Calculations for a camera system
I am building an interactive application in Starling for which a camera system is required. Since there is no existing camera system in flash and the addons for starling do not meet our requirements, I am writing my own. Basically, it moves and scales all assets depending on the position of the camera.

However, I am having trouble with zooming towards a specific point on the screen. Every object has a pivotpoint in the topleft corner - so it scales relative to the topleft corner. For all kinds of reasons, I cannot change the pivotpoint of the objects.

To compensate for this, the camera needs to move towards the point we want to zoom towards on the x/y-plane, but I cannot figure out how much it should move. Are there any known formulas for this? How do I calculate how the camera should move?

EDIT: I can actually move the pivotpoint to the center of the assets if that makes it much easier.

EDIT: This method is used on each sprite to update its position:

```
var zPos:Number = Number(this.z - Game.cameraZ);
var scale:Number = Game.focalLength / (Game.focalLength + zPos);
var correctedScale:Number = scale * (1 / (Game.focalLength / (Game.focalLength + this.z)));
this.scaleX = this.scaleY = correctedScale;
this.x = Game.cameraX * scale + this.defaultX * scale;
this.y = Game.cameraY * scale + this.defaultY * scale;

```

# Answer
> 1 votes
# Expressing your camera using bounds

If I noticed correctly, you are currently expressing your camera as a **focuspoint** (= center of the camera) and a **zoom level** (how closely zoomed in you are). I'm also assuming your game is two-dimensional, with assets rendered in the XY-plane, and the camera looking along the Z-axis.

While parametrizing your camera like this could definitely work, you could also think of it differently. Instead of stating what *where your camera is looking at*, you could specify *what area you want to be onscreen*. In this case, you would parameterize your camera in terms of bound. On the X-axis, you have the **left bound** and the **right bound**. On the Y-axis, you have the **top bound** and the **bottom bound**. (Assuming the X-axis is your horizontal axis, pointing to the right, and the Y-axis is your vertical axis, pointing upward.)

Using this parameterization, you are always 100% what is being shown onscreen. Note that you can always translate back and forth between this representation and your original one (this requires the "scale" parameter to be split in a "xScale" and "yScale", as scaling is not necessarily uniform).

---

# World coordinates and Screen coordinates

Your question basically relates to moving from **world coordinates** to **screen coordinates**.

1. The **world coordinates** of an asset express its place in your game world. You could think of this as the position where you place the asset with your map editor. They remain unchanged if you move the camera around.
2. The **screen coordinates** of an asset express its location on your screen. You can think of this as follows: assume you jump into your game and take a photograph of the scene, through the lens of your camera. The place where your asset ends up on the photograph, are the screen coordinates of the asset. They are affected by the camera. If you move the camera to the left, your asset will move to the right in screen coordinates.

Lets assume your screen has a width of *screen\_w* (e.g. 800 pixels), and a height of *screen\_h* (e.g. 600 pixels). To translate a single point from world coordinates to screen coordinates, you'd do the following:

```
x_screen = screen_w * (x_world - cam_left_bound) / (cam_right_bound - cam_left_bound)
y_screen = screen_h * (y_world - cam_bottom_bound) / (cam_top_bound - cam_bottom_bound)

```

If you use a y-axis that points downward, this last line becomes:

```
y_screen = screen_h * (y_world - cam_top_bound) / (cam_bottom_bound - cam_top_bound)

```

For example, a point that is exactly at the left bound of your camera will have a screen x-coordinate of 0. A point exactly at the right bound of your camera will have a screen x-coordinate of *screen\_w*. Other points will evaluate to their correct position as well.

---

# Solution: Calculating the bounds of your assets

The above explains how to find where a single point would end up in screen coordinates. You can use this information to figure out where an asset goes as well.

Again, rather than thinking of an asset as a centerpoint on top of which a scalable sprite is drawn, you could think of it in terms of bounds. If you know the left, right, top and bottom bounds of your sprite (in screen coordinates), you know exactly where and how to draw it. In essence, you are just drawing a rectangle on your screen, and you are drawing the asset inside of this rectangle.

Thus, to figure out how to draw your asset in screen coordinates, do the following:

1. Use the left, right, top and bottom **bounds of your asset** in **world space** (these are 2 x-coordinates and 2 y-coordinates)
2. Transform these coordinates to **screen coordinates**
3. **Draw** your **asset on a rectangle** that uses those screen coordinate bounds

---

In summary, you might find your problem easier by thinking in terms of bounds, rather than a position and a scaling factor. Thinking of the "position finding problem" as a transformation between world space and screen space may also help you. In fact, transformations between different *coordinate systems* or *spaces* are ubiquitous in 2D and 3D rendering for games! The difference is that they use matrices rather than separate equations, as these are easier when combining multiple transformations (e.g. translations, rotations and scalings).

---
Tags: camera, flash
---


title: Question regarding irradiance

text:
# Question
Title: Question regarding irradiance
I know that the formula for irradiance at surface point *p* with normal *n* given a point light source at position *l* is:

```
H = I(cos x) / ||l - p||^2

```

Where:

x = angle between *n* and *l*-*p* I() = Intensity of light

But if I have an area light source defined by a polygon P, what is the formula for irradiance?

# Answer
As nikoliazekter explained, you'd have to calculate the **integral over the surface of polygon** P. To solve this integral, you'd probably use a numerical approximation. I don't think it is realistic to do this in a real-time application, due to the complexity of this calculation.

While solutions might exist for some specific shapes, they don't for polygons P of any arbitrary shape. If you still want to use area lights, I think you can do either of two things.

# Approach 1: Raytracing

You could opt for a **raytracing renderer** rather than a standard rasterizer. A raytracer works by "shooting" rays from the camera and checking where these rays end up. They might hit a diffuse surface, bounce of a reflective surface, hit a light source or something else. You might shoot several rays per pixel, to obtain multiple samples to determine the pixel's color.

A raytracer is a lot **more flexible** than a standard rasterizer, but this comes at the cost of complexity. This option might **not be suitable for real-time** applications.

**Pathtracing** is a specific type of raytracing where the full path of a ray is calculated, instead of only calculating direct light bounces (ie. bounces directed towards light sources) when the rays from the camera hit a surface. This technique is a **global lighting** solution. When calculating the color of a pixel, the entire scene is considered as a whole, as light rays can bounce between objects. Thus, effects such as shadow casting, color bleeding etc will be simulated.

---

# Approach 2: Approximate the area light with point lights

Alternatively, you could **approximate** your area light **with multiple standard point lights**. While your render will not be physically correct, it is possible to closely approximate the area light. This way, you can make use of standard rasterization.

Rasterization is **less flexible** than raytracing, but it is much faster. This makes it **suitable for real-time rendering**.

Rasterization (in its basic form, using a simple illumination model such as Phong illumination) is a **local lighting** solution. When a polygon is being rasterized into fragments, only the fragment itself is considered. The entire rest of the scene is considered non-existant at that point. You are just calculating angles relative to the normal, camera and light sources, ignoring shadow casting, reflecting of light rays etc.

---

In summary, area lights are a lot more difficult to calculate than point lights, using a standard rasterizer. If your use-case is non-time-critical (e.g. an offline renderer for videos), you could look into raytracing as a rendering technique. If your use-case is time-critical (e.g. a video game), you might be more interested in approximating your area light using multiple point lights.

I'm not an expert at lighting equations, so I can't provide you with the exact mathematical solution unfortunately. I may have also butchered some of the lighting and rendering related terminology.
> 2 votes

---
Tags: lighting, graphics-programming
---


# Question
Title: How, if possible, do you add loop cuts to models in real time?
I am working on a prototype for a very low poly game. I can't figure out a way for a player to cut or break objects in real time without predefined fractures. For example, if a player cuts a tree, it will separate at the cut point rather than at a predetermine fracture. So how can you create a vertex loop and separate the halves in real time?

# Answer
> 1 votes
*EDIT: if you still really want to cut that model in half realtime without any predefined fractures, you might want to look into clip planes. They don't actually generate two separate meshes but you might be able to achieve the effect you want with them.*

I found a similar question on another gamedev site - and as I figured, there's no easy solution. To quote one of the replies:

> In the case of a wooden beam, it may be relatively straightforward because you already know the cross sectional shape. In the general case, it's doable on well formed meshes but kind of a pain. Essentially you'll have to calculate where the vertices should be and create a new mesh.

So, what I was thinking was - why not create more than one predefined fracture - and pick the closest one to where the player cuts? And if the visuals aren't *that* detailed you may even be able to move some of the model pieces around a bit so that a cut point is closer to where the player actually cut. Here's an image explaining my idea: (please don't mind the icky-looking microsoft paint graphics. xD)

I'm not sure if this method would suit your needs but it might be more effective and/or easier than modifying model mesh data on the fly. Especially because there's not much in the way of support for that kind of stuff, or at least as far as I can tell. Anyway - good luck - hope this helps.

---
Tags: game-mechanics, models, realtime
---


# Question
Title: How do I use rigidbody2d.AddForce to apply a force in the direction the object is facing?
I'm trying to create a thruster on a spaceship. It should add this thrust in the direction the thruster is facing, but I am at a loss on how to get that direction and send it to AddForce. Am I even heading in the right direction with this script?

```
public float maxThrust;
FixedUpdate()
{
 float moveVertical = Input.GetAxis("Vertical") * maxThrust;
 Vector3 heading = rigidbody2D.transform.eulerAngles;
 Vector2 thrust = new Vector2(heading.normalized.x, heading.normalized.z);
 rigidbody2D.AddForce(thrust * moveVertical);
}

```

Maybe I'm not understanding something with EulerAngles or Vectors, but it sure seems like this would be a straightforward thing to do.

# Answer
The rigidbody2D's transform has **up**, **right**, and **forward** properties that'll tell you what's up, right, or forward for the object, respectively. In 2D, only two of those will actually be useful to you, and I imagine those would be **up** and **right**.

So, if you want to apply the force in the object's **up** direction, do away with `Vector3 heading = ...;` and calculate thrust something like this instead:

`var thrust = transform.up;`

Hope that helps :)
> 2 votes

---
Tags: unity, unityscript
---


# Question
Title: Easy SpriteKit question on creating a function
The following code is what I'm working on to animate characters in a SK scene class. I can run the code without building, no problem, but I can't build it and run it; I get one error message: **Binary operator '+=' cannot be applied to operands of type '\[(SKTexture)\]' and '\[SKTexture!}'.** The code is below:

```
func initStoryBegin() {
    let CaitAtlas = SKTextureAtlas(named: "cait")
    let DrewAtlas = SKTextureAtlas(named: "drew")

    CwalkAnimation = self.animateSheet(CaitAtlas, walkAnimation: CwalkAnimation, formattedword: "cait%01d")

}
// ***This is where I am having trouble. In the walkAnimation += line.
func animateSheet(nameAtlas: SKTextureAtlas!, walkAnimation: [(SKTexture)], formattedword: String) -> [SKTexture] {
    for index in 1...nameAtlas.textureNames.count {
        let imgName = String(format: formattedword, index)
        walkAnimation += [nameAtlas.textureNamed(imgName)]
        println(walkAnimation)
        return walkAnimation
    }
}

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    let charNode = self.childNodeWithName("charNode")

    if (charNode != nil) {
        let animation = SKAction.animateWithTextures(CwalkAnimation, timePerFrame: 0.2)

    charNode?.runAction(animation)

    }
}

```

I can't figure out why the code works when I run it, but it doesn't work when I try to build and run? Any help would be greatly appreciated.

# Answer
Your walkAnimation array needs to be defined as inout in order to be mutated. Arrays in Swift are treated as Structs, which cannot be altered when passed by value, which is the default behavior. Using "inout walkAnimation: \[(SKTexture)\]" allows the array to be passed by reference, thus allowing a change such as your append.
> 1 votes

---
Tags: game-design, spritekit, xcode
---


title: How to draw an ellipse with DirectX 9?

text:
# Question
Title: How to draw an ellipse with DirectX 9?
I can draw the outline of an ellipse but I want to draw a filled in ellipse, but I can't seem to get the code to work. Any help would be great! I am using DirectX 9 and D3DX.

# Answer
There are multiple approaches:

1. Cut-out texture

Create a fully transparent texture. Fill the texture with the ellipse shape on the CPU. Render the texture with alpha blend. You only need one texture per ratio of radii, so chances are you can generate some offline.

2. Geometry

Create a tessellated sphere, pass radii to vertex shader, deform shpere into ellipsoid in the vertex shader. Project it orthographically onto the screen.

3. Pixel Shader

Render a rectangle, pass the radii through to the pixel shader and use trigonometric functions to determine for each pixel whether it's inside the ellipse - or even better it's signed distance to the ellipse's edge. Then fill accordingly. If you compute the signed distance you can even fade it nicely toward the edges to achieve effects like bevel and emboss.
> 1 votes

---
Tags: c++, directx, graphics, directx9
---


# Question
Title: Trying to get reference to Button in Javascript Unity3d
I've this simple script in Unity3d:

```
#pragma strict

public var topLeft : UnityEngine.UI.Button;
public var topCenter : UnityEngine.UI.Button;
public var topRight : UnityEngine.UI.Button;
public var midLeft : UnityEngine.UI.Button;
public var midCenter : UnityEngine.UI.Button;
public var midpRight : UnityEngine.UI.Button;
public var bottomLeft : UnityEngine.UI.Button;
public var bottomCenter : UnityEngine.UI.Button;
public var bottomRight : UnityEngine.UI.Button;

private var x = "X";
private var o = "O";

function Start () {

    var board = [[topLeft, topCenter, topRight], [midLeft, midCenter, midpRight], [bottomLeft, bottomCenter, bottomRight]];
    for (var i = 0; i < board.length; ++i) {
        var row = board[i];
        for (var j = 0; j < row.length; j++) {
            var button = row[j];
            button.onClick.AddListener(function() { onTileClicked(button); });
        }
    }
}

function onTileClicked(tile : UnityEngine.UI.Button) {
    Debug.Log("Click click!");
}

```

Here is how I reference the buttons:

Why are all the buttons in 'board' variable null even if I referenced them through the GUI (the red rectangle in the image)?

# Answer
Turns out it was a bug in Unity.. All I had to do was restart the IDE.. Bad start from Unity.
> 1 votes

---
Tags: unity, unityscript
---


title: Pausing the game inside the game loop

text:
# Question
Title: Pausing the game inside the game loop
Inside the game loop, the game is paused by pressing P, meaning that the game loop does not run anymore. Problem is that after this loop is halted, P cannot be pressed again to resume the loop, since it was inside the loop itself. How to make it so that when P is pressed again it makes the loop work again?

# Answer
> 21 votes
Don't actually stop the game loop when pausing the game. Instead, you have to add bool variable, that is changed to true/false depending if game is paused. If game is paused, you only have to stop updating the game, but you can still keep rendering the current frame including getting updates from input.

```
if(gameIsPaused == false)
{
    // run updates
}
checkInput();
render();

```

# Answer
> 1 votes
Make it so that pressing P switches to another loop that handles the game state "Paused" and allows to transition back to the original game loop by pressing P again.

You can actually put this all into the game loop itself and introduce a state variable, if you want and instead of turning off the loop, the state variable toggles between the execution of the respective state-specific code within the loop.

---
Tags: game-loop
---


# Question
Title: In a 2D top-down game, how can I create projectiles that have a height?
A 2D game called Deer Hunter has projectiles like this:

Are the projectiles 2D or 3D models? How could I implement something similar?

# Answer
I've made projectiles like this in a game and they are most likely 2D for all purposes besides selecting the correct sprite. Then a third Height variable is maintained and some simplified physics is applied. This variable might even be "time in air". So they are likely represented in 2D (x,y) and animated using a third tertiary variable
> 5 votes

# Answer
3D models for something that uses minimalist art is completely overkill. The arrows' effects are most likely produced by 2D art and some math.

First, the arrows are given a rotation based on the angle that the player makes with the mouse, upon release of the left mouse button.
Then, based upon how long the mouse button was held, the arrows are given a flight time.
Finally, upon reaching the end of their flight time, the arrows will be animated to angle toward the ground and have their height reduced by a small amount.

Once again, this is, or at least should be, done with 2D art that is rotated based upon the angle being shot at.
> 0 votes

# Answer
By speculation - this is what it looks like to me.

* The arrows seem to, as others say, have an extra variable to determine their height. It looks like an X and Y velocity of the dart might be determined by the direction and power of the power bar, with a predetermined height. I'm not sure if the darts are shot at an upward angle. If not then the flight time for every dart would be constant.
* I would expect there would also be a height velocity variable that would be set to the power of the power bar / some constant, or 0 if the darts are shot straight with no upward angle. It looks to me as if the dart might be some sort of rotated bitmap - but it could also likely be an extremely simple texture with its pixels calculated per frame based on angle. I'm not sure *exactly* how they did it - but I'd figure not with models. There's only so many pixels to work with anyway, so an approximation will look very similar to a pixelated model. So why do it with models?
* It looks like the X position of the arrow is unaffected by its height. I'd say that the Y position is simply set to its calculated Y position (technically Z position in a 3D world) minus its height value. The angle of the actual dart appears to be determined by the change in the dart's X position and the change in the dart's Y (and height) position, while the shadow is simply a brown (or black semi-transparent) dart that follows the same path as the "3D" dart except without any height.

I'd say that this game (and the darts) should be and probably is made in 2D because:

* Calculating and pixelating 3D models for such a simple game would be a waste of processing power, let alone being overkill.
* The techniques here look very much like 2D game techniques. Besides, pixel games are *usually* 2D anyway.
* Look at the way the dart sort of "blips" through the tree. I don't think that would be acceptable if the models were 3D.
* The game itself has no perspective. If the darts were 3D models then I would assume they'd be in a 3D world. So then why is there no perspective at all, really?

Anyway, this is all mostly speculation - but hey, you asked us to look at a gif and tell you how we think it was done, so I guess speculation is okay. :P

Although, despite this being speculation, I think it's actually how the game *should* be done if it was not already done this way. Although there's plenty of other answers here and I'd say any of them would probably work well. Eh, I hope this answer helps you some way. :)
> 0 votes

---
Tags: 2d, 3d, graphics-programming, projectile-physics
---


# Question
Title: Why does my Outlined Diffuse 3 shader seem "detached" at a distance?
I'm using the *Outlined Diffuse 3* shader from Unity and I'm having a problem with it: the outline looks great when the camera is near the object, but at a distance, it looks detached.

From nearby (looks good):

From afar (looks bad; see the shelf and books):

How can I fix this graphical anomaly?

# Answer
> 2 votes
I guess you refers to this shader. That's not an "anomaly", it's how this shader is supposed to work(not a great result imho).

So let's have a quick look to the relevant code:

```
float3 norm   = mul ((float3x3)UNITY_MATRIX_IT_MV, v.normal);

```

This first line transforms the normal from object space to view space.

```
float2 offset = TransformViewToProjection(norm.xy);

```

The second line projects the xy normal components from view space. Basically you'll end up with a vector describing "how much" the normal point to right and up direction relatively to the screen.

```
o.pos.xy += offset * o.pos.z * _Outline;

```

This is the "guilty line" :) . The projected vertex position is **offset** by the projected normal calculated before by an amount proportional to `_Outline`(the size of the outline you specify by inspector) and the distance from the camera (`o.pos.z`).

The idea behind is that if you don't multiply by the distance, the outline will become thinner depending on how fare you are from the camera. So basically it should guarantee that the outline should stay on the same (clip space) distance independently from camera distance. (Just comment the multiplication by o.pos.z and you will see).

So basically in the second picture what seems a larger outline, is an outline of the same width when projected (de facto larger if you consider the width relative to the world size of the object).

Note that the "outline" is simply the same model draw with front face culling:

```
Name "OUTLINE"
Cull Front

```

---

Side note

There are several way of drawing outlines. The way you are using produce several problems other than the outline width, for example:

* crack on hard edges (see the space in the bottom left corner of the shelf)
* missing outlines (see the outline is not visible on the right side of the book)

There are several better techniques, both for the vertex shader or as post process effect (es. sobel filter for edge detection). Which technique you can use is highly dependent on the final look desired, and maybe depends on your asset characteristic too.

---
Tags: unity, shaders, graphics, graphic-effects
---


title: Cross platform C++ UDP socket library

text:
# Question
Title: Cross platform C++ UDP socket library
Can somebody recommend a free C++ open source library which I will use to build a networked game using UDP. Must be available for Windows/Linux/Mac. As lightweight as possible please.

# Answer
> 1 votes
There are some libraries which may do even more than what you need, not very light weight but completely reliable I think you can even use the *Net* portion of the library instead using them as a whole:

you can also take a look at this question.

# Answer
> 2 votes
You could try http://enet.bespin.org/.

# Answer
> 0 votes
I highly recommend RakNet; it's relatively lightweight and implements a virtual connection over UDP for you (you don't have to manually send acks). I've had great success in using it across multiple projects.

---
Tags: c++, networking
---


# Question
Title: Model texturing not seamless at certain zooms? (C# XNA)
I found a very odd glitch with my game this morning. XNA doesn't render certain textured models properly, while other models are completely unaffected. And it's not even like my models are made incorrectly - even one of my spheres doesn't render properly at certain zoom levels. Agh, it's hard to explain, here's a picture:

The arrow on the left is in blender. The right two pictures are from within my game. At first, I thought that this was some sort of bleeding / collision issue of the arrow and the space-y background. But when I removed the background, the issue was still there.

So what are all those weird pink dots and seams? This is what my texture looks like:

Oddly enough, all of the other models in my game render correctly, except for the space sphere you see behind the arrow. (It only looks incorrect at other zoom levels, although no pink dots, just more black seams)

So I tried to find a similarity between the two malfunctioning objects, the arrow and the sphere. It occurred to me that they were the only objects whose textures did not cover the entire model, but instead were tiled. So like the UV unwrapping was not totally contained in the texture... here's a picture of what the UV looks like in blender:

Based off of this, I concluded that somehow XNA is not tiling the texture properly when it maps it to the objects. Since blender renders the model correctly and XNA doesn't, I'm assuming the problem is with XNA. (although correct me if I'm wrong)

So finally, my question is: I'm totally lost - does anybody know how to fix this?

Thanks!

EDIT: As requested in comments, here is my drawing code. It's nothing special, just your basic model draw code.

```
class OrderedDrawModel
{
    Model M;
    Matrix Transform;
    float Transparency;
    Vector3 Ambience;
    public float Distance;
    float Reflect;
    public OrderedDrawModel(Model M, float Transparency, Vector3 Ambience, Matrix Transform, float Distance, float Reflectivity)
    {
        this.M = M;
        this.Transparency = Transparency;
        this.Ambience = Ambience;
        this.Distance = Distance;
        this.Transform = Transform;
        Reflect = Reflectivity;
    }
    public void Draw(GraphicsDeviceManager graphics, Camera_Edit C)
    {
        Matrix[] T = new Matrix[M.Bones.Count];
        M.CopyAbsoluteBoneTransformsTo(T);
        foreach (ModelMesh mesh in M.Meshes)
        {
            foreach (BasicEffect basicEffect in mesh.Effects)
            {
                basicEffect.World = T[mesh.ParentBone.Index] * Transform;
                basicEffect.View = C.view;
                basicEffect.Projection = C.projection;
                basicEffect.LightingEnabled = true;

                basicEffect.AmbientLightColor = Ambience;
                basicEffect.DirectionalLight0.DiffuseColor = Color.White.ToVector3();
                basicEffect.DirectionalLight0.Direction = Vector3.Normalize(new Vector3(-3, -3, 1));
                basicEffect.DirectionalLight0.SpecularColor = new Vector3(Reflect, Reflect, Reflect);

                graphics.GraphicsDevice.BlendState = BlendState.AlphaBlend;
                basicEffect.Alpha = Transparency;
            }
            mesh.Draw();
        }
    }
}

```

I create the object with this line:

```
DrawModel(Arrow, 1.0f, Matrix.CreateScale(5f), new Vector3(0, 0, 0), 0.4f);
        //Model  alpha transform_matrix        ambience            specular

```

Which adds it to a list of back-to-front ordered models that get drawn by calling their draw method.

# Answer
> 1 votes
Try making your texture `512x512` that could be the issue since your texture is `400x400`. XNA error logs state that the texture should be resized to a power of two.

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


title: Handling input with callback functions

text:
# Question
Title: Handling input with callback functions
I'm not sure if I understand callback functions completely - they are functions that another function calls? This seems like a powerful tool, especially w/r/t handling input. I've written up this quick and dirty example using callbacks(or at least my understanding of them), but I feel as though I am doing too much.

1st, I would gather input from the OS.

2nd, I would pass that input into some sort of Context to handle input.

3rd, I would use the current active Contexts to shoot off these callback functions, based off of the input.

Something like this,

```
//Gathers keyboard input
struct InputData {

    std::map<SDLKey, bool> held_keys;
    std::map<SDLKey, bool> pressed_keys;
    std::map<SDLKey, bool> released_keys;
};

//Takes a shared_ptr in the constructor so it always knows what the current InputData is

class Context {

public:
    //Constructors/Destructors
    ...

    //Maps a function to a SDLKey
    void set_held_key_to_function(SDLKey key, std::function func)
    {
        held_key_action[key] = func;
    }

    void set_pressed_key_to_function(SDLKey key, std::function func)
    {
        pressed_key_action[key] = func;
    }

    void set_released_key_to_function(SDLKey key, std::function func)
    {
        released_key_action[key] = func;
    }

    //Fires off actions of pressed keys
    void PressKey(SDLKey key)
    {
        if(input_->pressed_keys[key] == true) {
            pressed_key_action[key]();
        }
    }

    //Fires off actions of held keys
    void HeldKey(SDLKey key)
    {
        if(input_->held_keys[key] == true) {
            held_key_action[key]();
        }
    }

    //Fires off actions of released keys
    void ReleasedKey(SDLKey key)
    {
        if(input_->released_keys[key] == true) {
            released_key_action[key]();
        }
    }

private:
    std::shared_ptr<InputData> input_;

    std::map<SDLKey, std::function> held_key_action;
    std::map<SDLKey, std::function> pressed_key_action;
    std::map<SDLKey, std::function> released_key_action;
};

```

Is this a viable way to handle user input, especially considering that the input in a Pause Menu would be vastly different than the input in the actual Gameplay part? Or am I vastly over-complicating the entire process of handling input? Am I even understanding callbacks correctly?

# Answer
In the broadest sense, yes a callback is nothing more than a function call.

But rather than trying to over-engineer an input system by using function pointers, I would consider approaching input from two angles, and allowing both to be available.

## Observer

There are times where it makes sense for part of your code to react to state transitions in a generic semi-coupled way. Listeners are a great way to do this with little effort in C/C++.

```
 class KeyboardListener {
 public:
   void OnKeyEvent(const KeyEvent& evt) {}
 };

```

Any object that now wants to be informed about keyboard events can simply be derived from this listener contract and your input system simply needs to allow a way to register these dependencies.

```
 class Input {
 public:
   void AddListener(KeyboardListener* pListener) {
    /* add pointer to a list */
   }
 };

```

Whenever a keyboard press/release occurs, your input system can then create a `KeyEvent`, populate it with information and then iterate the listeners and dispatch it.

## Polling

There are often other times where it can be just as easy and perhaps cleaner to poll for the current state rather than trying to react to it using a listener.

For example, in a `PlayerController`, it may make more sense to simply do something like this in it's update method rather than trying to implement it as a listener.

```
 void PlayerController::Update(float deltaTime) {
   if(Input.IsKeyDown(KeyCode::KC_SPACE) && !isJumping && isGrounded) {
     isJumping = true;
     Jump(deltaTime);
   }
 }

```

When you combine this together, you can start to create elaborate high-level systems. For example, an action/keybind system may act as an observer to the input system. As input occurs, the action system updates the state of game action commands based on bindings between keys and actions. Any other piece of code can query the current state of a game action command and react accordingly.

```
void PlayerController::Update(float deltaTime) {
  if(Actions.IsActionToggled(JumpAction::NAME)) {
    mJump->Execute(this);
  }
}

```

This allows you to separate the actual key combinations from the actions and even allow actions to be triggered based on a series of key presses rather than just logical press/release state. And instead of polling, you could react with listeners.

```
void PlayerController::OnAction(const Action& action) {
 switch(action.GetType()) {
   case JumpAction::TYPE:
     Jump();
     break;
 };
}

```

Hope this gives you an idea of how simply this can be handled without having to dive into function pointers :p.
> 2 votes

---
Tags: c++, input, callbacks
---


# Question
Title: How does Unity call "update()" in the scripts?
I understand that you can expose your C++ code to a scripting language such as ChaiScript. From this you can call code that you've made in C++. In Unity, however, they have functions in the script, such as `Update()` that get called. In other words, how do I call script functions from C++?

# Answer
Scripting languages often expose a set of API functions that allow you to inspect and determine attributes about a loaded script, in your case what functions are defined. This varies by scripting language naturally and will also depend on your native language to scripting language bindings.

In Lua for example, I can load a script and then check whether a particular function is declared. I've often done this for `Update()` and other methods so that if defined, I create a mapping that will then be invoked during the game simulation for those scripts that have overloaded that callback.

In the case of Unity, their `MonoBehavior` is a contract they've defined and they simply look to see whether you've overwritten specific functions from the contract and if so, then the callback is invoked at the appropriate times during game simulation.
> 1 votes

# Answer
Unity uses its own messaging system to call methods like Update. You can use it as well with for example Component.SendMessage.

I think that the underlying implementation of the message system uses some form of reflection to determine what methods a class has and call the appropriate ones.

(This post's answer explains it better)
> 0 votes

# Answer
`C++` and `C#` can interact quite easily. (In the practice C++ issues relative to name mangling often force to have an intermediate `C` layer)

There are several resources you can have a look such as Mono P/Invoke docs and unity docs on native plugins.

Calling a `C#` function from `C++` code is simply as using a function pointer (a `C#` delegate can be marshalled to be used this way).

---

For what concern how `Unity` handles callbacks it's another question. I don't know the exact underlying implementation but most `MonoBehaviours` hooks like `Update` aren't virtual|abstract method, nor implement any interface.

Why? Not sure, I often asked my self why (honestly I prefer a more explicit approach like implementing an interface like ISerializationCallbackReceiver).

On how the binding between function pointer and C# method happens, it's probably creating a delegate instance. The problem is really different between SendMessage and `Update`.

I guess Unity is forced to use Reflection for SendMessage, because the method name is know only at runtime. Use it carefully because reflection is really expensive.

For the others Update, Start, etc.. the problem is simpler because method name, signature and target object are know. So the expensive binding process can be used only once in initialization. Here's a nice article.
> 0 votes

---
Tags: unity, c++, scripting
---


# Question
Title: How to use Cocos2dJS to connect to a Socket.IO server?
How can I connect to a `nodejs socket.io` server from a `cocos2djs` game? I've google all the way to no avail. I tried this but it does not work:

```
socket = io.connect('http://192.168.254.102:7714');
if ( socket === undefined ) {
    cc.log("Could not connect to socket.io");
} else {
    socket.on('connect', function() {
        socket.emit('join', {username: 'Android Application'})
    });
}

```

I read in the docs that there's a module called `SocketIO` for doing that, but there's not enough info on how to use it. Thanks in advance.

# Answer
try opening a new thread like in this video tut and use that for your connections. https://www.youtube.com/watch?v=6G\_W54zuadg

there may be some useful info in this video hope it helps
> -1 votes

---
Tags: javascript, cocos2d, node.js, websocket
---


title: Sharing Tiled Maps

text:
# Question
Title: Sharing Tiled Maps
Where can share my existing Tiled maps, as well as download and use other people's existing maps?

# Answer
Haven't come across anything like that yet. But you could check GitHub for games that use Tiled. Then you can download their Tiled files and images. Here's one such repository: https://github.com/bjorn/tiled/tree/master/examples

Additionally, you can also do Google searches by filetype and look for .tmx files. You might have to do a lot of searching through all those results. But you might find some good stuff along the way. Type this into Google's search box: `filetype:tmx tileset`

None of the methods listed above allow you to share your own work, however.
> 3 votes

---
Tags: 2d, tilemap, tiled
---


# Question
Title: Body lost a velocity component when hitting a wall
I am creating a Breakout game using Box2D (of LibGdx if anyone interest). Everything works well until when the ball hits the wall when moving with a very small angle. Please look at the image for details:

I tried to set the wall friction to 0 and restitution to 1, as well as the ball's friction and restitution, but it still move along the wall (I have no World Gravity). This also happens to the vertical wall if the angle is small enough, it will lose X velocity.

How can I move the ball the way I expected? If there is no friction, what caused the problem?

**EDIT**: In case of LibGdx only, this is a fix:

```
World.setVelocityThreshold(float threshold);

```

I set it to 0.1f, and it helped. If you encounter problem, maybe 0 can help, but it is unrecommended..

# Answer
# What's happening

First of all, note that this behavior is not specific to oblique collisions. Below is an example of two balls colliding head on with a wall. All fixtures have `m_restitution = 1.0`, and `m_friction = 0.0`. The ball on the left is traveling with `v = 0,1` and the ball on the right has `v = 0,1.01`.

I found three similar questions asked on the box2d forums a while back, which suggest lowering a value in b2Settings.h, `b2_velocityThreshold`.

It didn't take me long to find the code block where `b2_velocityThreshold` is referenced. It turned out to be line 211 of the file b2ContactSolver.cpp, and inside the function `b2ContactSolver::initializeVelocityConstraints`:1

It is here that the velocity bias factor is set based on whether or not the relative velocity exceeds `b2_velocityThreshold`. That velocity bias factor is then referenced in the iterated function `b2ContactSolver::SolveVelocityConstraints`. When the bias velocity is not set (defaults to zero), the initial accumulated impulse is becomes just enough to counteract the initial momentum of the ball, and it sticks to the wall.

I have tried to understand why the `b2_velocityThreshold` exits in the first place (many web searches) and haven't come up with a definitive answer. The best I can do is quote Erin Catto (author of box2d) who posted in one of the above threads:

> If you set the \[`b2_velocityThreshold`\] to zero, non-zero restitution will cause your bodies to bounce forever.

So I'm extrapolating that this behaviour is implemented for the sake of games with bouncing balls, where balls with restitution `0<e<1` would otherwise never stop bouncing (even though the bounce heights would eventually become *very* small). This would waste tons of cpu time creating/deleting the contact between the two bodies, and in addition the bouncing body would never sleep.

# Recommended Solutions

**Solution 1**
The recommendation from the above forum threads is to reduce the parameter in b2Settings.h:

> `#define b2_velocityThreshold 1.0f`
>
> A velocity threshold for elastic collisions. Any collision with a relative linear velocity below this threshold will be treated as inelastic.

Unfortunately, this parameter is a `#define` constant and is therefore not editable unless box2d is re-compiled. I'm assuming that you don't wan to re-compile libgdx to do this.

**Solution 2**
Zee was on the right track with his answer, but it needs a little more detail. A good approach to doing this is using collision callbacks as you suggest. You sound like you know what you're doing with this one, so I won't go into detail here.

**Solution 3**
This one's a bit of a trick, and I'm only recommending this because you say you're working on a breakout clone, which only has a couple of moving parts.

You should leave almost everything as is, but increase your ball speed by a factor of `s` where `s>1`. If `s` is high enough, then very oblique collisions will still have a significant relative velocity and will therefore trigger the velocity bias-setting else branch in the referenced code, and your ball will almost always bounce. The problem is that now your game is impossible because the ball is so fast and the player cannot keep up. To compensate for this, just multiply your time-step by a factor of `1/s` before calling `b2World::Step`. That way box2d will technically be operating in slow motion, but since your ball has been sped up by the same amount, everything will look normal.

Here are 2 more gifs. The left one shows a ball with `v=1,1` and time step size `ts = dt`. The second is with `v=2,2` (magnitude doubled), and time step size `ts = 0.5*dt`. Voila:

I hope this helps!

1 This is the only place I could find where that threshold parameter is referenced. (i.e. it has the same effect for all contact types, regardless of the shapes involved in the collision)
> 4 votes

# Answer
I am not familiar with libgdx, so I apologize if this might be a bit out of place; but don't you need a script for the wall class? Right now it seems the wall is simply acting like it should react and do nothing to affect the ball's movement, so the ball will continue going in the same direction on the black arrow.

Make it such as that if the wall is hit, it will multiply by -1 the ball's Y axis vector component. And if it hits any of the right / left walls, multiply by -1 the X axis component.
> 1 votes

---
Tags: libgdx, box2d, body
---


# Question
Title: Does vector transformation order matter?
Theoretical question - imagine a car object. There are two (or more) 'forces' acting on this car, these forces will affect where the car will steer. But the forces are calculated using car's location in relation to the world, car's steering on the other hand relies on a vector within car's local space. Therefore these forces need to be translated to the car's own space before they can be applied on the car's steering.

Now the question is - should the vectors that represent these forces be summed first and the resulting force then translated to the car's domain? Or should both forces first be translated and then summed, within car's domain? Or does it not matter?

# Answer
> 10 votes
Because of the linearity (aka distributive property) of vector addition and matrix multiplication, it doesn't matter! Yay!

```
Transform(Sum(v_i)) = Transform(v_0 + v_1 + ... + v_n)
                    = Transform(v_0) + Transform(v_1) + ... + Transform(v_n)
                    = Sum(Transform(v_i))

```

EDIT: However, transformations are not *commutative*, so these are not equal:

```
Transform_A(Transform_B(v_i)) != Transform_B(Transform_A(v_i))

```

---
Tags: vector, transformation
---


# Question
Title: Updating game objects already placed in scene
I have about 20 game objects placed in certain positions in my scene. I then realized i need to attach two additional game objects to each one of these as children.

Is there a simple way of doing this? I really don't want to remove them all update the prefab and then place them back.

Is there a way that i can add the two children to the prefab and all 20-something objects in the scene will also be updated?

# Answer
> 8 votes
When modifying a prefab in the scene, you can save the changes to be reflected on all instances of the prefab by clicking the Apply button in the Inspector tab - children, component values, everything on and under the prefab will get saved and applied to all.

So, add your child objects to one instance of the prefab in the scene, select the top-level of the prefab (or any object in its hierarchy that is coloured blue), and click the Apply button under the Inspector tab. All instances of the prefab will then be updated with the change.

Note that this will immediately modify the prefab file in your Project folder, so if you're doing a significant change that you're unsure of, it might pay to back up your project folder first, just to be safe.

# Answer
> 4 votes
If you've already saved your GameObjects as a prefab, you can add the GameObjects to one instance of your prefab. When you click on the instance of the prefab, an 'apply' option should show up in the inspector. If you click that it will overwrite the prefab with the properties on that particular instance and then apply that to all the instances of that prefab.

If you hadn't already saved your GameObject as a prefab then you probably just have to do it all the hard way.

---
Tags: unity
---


title: Shader - Convert vector into scalar

text:
# Question
Title: Shader - Convert vector into scalar
I am trying to convert a half3 as a simple half but I am facing an issue. As for an example half3(1, 0, 0) give me white but half3(0, 1, 0) gives me black.

How can I convert properly a half3 to a simple black and white half value

Thank you.

# Answer
There are a variety of formulae for converting colour to black and white. Furthermore, the programmer might mean something else when converting a vector into a scalar (length would be a common example). The shader compiler keeps things as simple as possible, just taking the first value in the vector, in your example.

Experiment with different ways to get a black and white that looks good in your situation. Some examples might be:

`scalar = max(vector.r, max(vector.g, vector.b));`

OR

`scalar = (vector.r + vector.g + vector.b) * 0.333;`

OR

`scalar = length(vector) / 1.73205080757; // sqrt(3), which is the length of vector(1,1,1)`

OR go for one of the formulae in that Wikipedia article I linked that emulates black and white film.
> 2 votes

---
Tags: opengl, shaders, directx, glsl, hlsl
---


title: Problems Animating Texture in OpenGL

text:
# Question
Title: Problems Animating Texture in OpenGL
I'm trying to animate a texture to scroll a static screen for a television, however I'm having some issues.

Just translating within the texture matrix animates all textures in the scene which is obviously a problem. However when trying to push and pop the matrix the texture matrix seems to keep getting reset. So rather than a scrolling texture, the texture just stays at the same translation.

Here's the code snippet.

```
glMatrixMode(GL_TEXTURE);

glPushMatrix();

glTranslatef(0, 0.03 * dt, 0);

glBindTexture(GL_TEXTURE_2D, staticTexture);

RepeatTexture();

glBegin(GL_QUADS);
glTexCoord2f(0, 0);
glNormal3f(0, 0, 1);
glVertex3f(0.49, 0.205, 0.461);
glTexCoord2f(0, 1);
glNormal3f(0, 0, 1);
glVertex3f(0.49, 1.204, 0.461);
glTexCoord2f(1, 1);
glNormal3f(0, 0, 1);
glVertex3f(-.80, 1.204, 0.461);
glTexCoord2f(1, 0);
glNormal3f(0, 0, 1);
glVertex3f(-.80, 0.205, 0.461);
glEnd();

glPopMatrix();

glMatrixMode(GL_MODELVIEW);

```

# Answer
> 1 votes
Your problem is that you're doing this:

```
glPushMatrix();
glTranslatef(0, 0.03 * dt, 0);
// (...)
glPopMatrix();

```

The offset created by the glTranslatef() command only exists between the glPushMatrix and the glPopMatrix; it doesn't retain its values from previous frames; the offset goes away forever as soon as the matrix is popped. So assuming that dt remains constant at a value of 1/30 (for 30fps), every single frame you draw effectively uses the same single `0.03 * 0.033` offset from the texture coordinates specified on the mesh. Which is why it doesn't appear to scroll.

In order to make it scroll, you want to make the texture be offset by a *different* amount on each frame. One easy way to do this would be to do `glTranslate(0, 0.03 * absolute_time, 0);`, where 'absolute\_time' is the number of seconds since the game started to run. Or any other continuously-upward-moving counter. That way, the translation will continue to increase as the game runs, instead of holding still.

# Answer
> 1 votes
There's an easy solution - *don't* translate with a matrix.

Since you're using immediate mode, it's an incredibly easy matter to simply offset the texture coords however much you'd like.

EG, `glTexCoord2f(1, 0.03 * dt);`

This will, of course, not be so easily done when you learn about the OpenGL Core Profile, which is highly recommended to be used. But until then, there's a very easy solution right there.

# Answer
> 0 votes
have you tried to assign a separate var for each texture?

also what is RepeatTexture(); calling?

i think that may be the source of your problems

---
Tags: opengl, textures, animation, matrix
---


# Question
Title: Trouble drawing repeating and scrolling screen elements from a 2d array for an endless runner in swift
I've been trying draw level segments for an iOS endless runner using 2d elements that repeat forever. I have a class that generates a random 2d array, then scene elements are drawn and animated to move left based on the 2d array. I also have a random number of ground tiles that generate in between each segment. The problem is when I attempt to have this action repeated forever. Everything I've tried has failed. My question is, what is the most efficient way to achieve this without any spaces in between segments? My goal is to generate the new segment when the end gets close to the viewing area, whereas to not take up unnecissary memory. Here is my code that generates only one segment:

func generateSegment() {

```
let wholeBlock = SKTexture(imageNamed: "wholeblock")
let halfBlock = SKTexture(imageNamed: "halfblock")
let ySegment = self.frame.height / 9
let randomSpacer = Int(arc4random_uniform(12) + 5)
let startPoint = (ySegment * CGFloat(randomSpacer))
let tempBlock = SKSpriteNode(texture: wholeBlock)
let sizeDifference = ySegment / tempBlock.frame.height
var moveBlock = SKAction.moveByX(-tempBlock.frame.width, y: 0, duration: NSTimeInterval(0.4))
var moveBlockForever = SKAction.repeatActionForever(moveBlock)

// get random 2D Array
var segmentMatrix: [[Int]] = GetLevelSegment().atRandom() as! [[Int]]

//draw random number of ground spaces between segments
for var x = 0; x < randomSpacer; x++ {
    var groundSprite = SKSpriteNode(texture: wholeBlock)
    groundSprite.setScale(sizeDifference)
    groundSprite.zPosition = 98
    groundSprite.anchorPoint = CGPointMake(0,0)
    groundSprite.position = CGPointMake((CGFloat(x) * groundSprite.frame.size.width), 0)
    groundSprite.runAction(moveBlockForever)
    gameLayer.addChild(groundSprite)
}

//set segment start point

//draw a 32 x 9 segment
for var i = 0; i < 9; i++ {
    for var j = 0; j < 32; j++ {
        if segmentMatrix[i][j] == 1 {
            var sprite = SKSpriteNode(texture:wholeBlock)
            sprite.setScale(sizeDifference)
            sprite.zPosition = 98
            sprite.anchorPoint = CGPointMake(0, 0)
            var xPosOne = CGFloat(j) * sprite.frame.size.height
            var xPosTwo = xPosOne + startPoint
            var segFromTop = CGFloat(i + 1) * sprite.frame.size.height
            var yPos = CGFloat(self.frame.height - segFromTop)
            sprite.position = CGPointMake(xPosTwo, yPos)
            sprite.runAction(moveBlockForever)
            gameLayer.addChild(sprite)
        }
        if segmentMatrix[i][j] == 2 {
            var sprite = SKSpriteNode(texture:halfBlock)
            sprite.setScale(sizeDifference)
            sprite.zPosition = 98
            sprite.anchorPoint = CGPointMake(0, 0)
            var xPosOne = CGFloat(j) * sprite.frame.size.height
            var xPosTwo = xPosOne + startPoint
            var segFromTop = CGFloat(i + 1) * sprite.frame.size.height
            var yPos = CGFloat(self.frame.height - segFromTop)
            sprite.position = CGPointMake(xPosTwo, yPos)
            sprite.runAction(moveBlockForever)
            gameLayer.addChild(sprite)
        }
    }
}

```

}

# Answer
Use a queue structure to represent the on-screen terrain; this approximates an infinite "ring-buffer".

Psuedo-code:

```
float maxCount = 20; //enough "terrainBlocks"(Sprites?) to fill the screen
//I only call this a "queue" because we add/remove from opposite ends
float Array<TerrainBlock> queue;
void fillQueue()
{
  while (queue.count < maxCount)
  {
     queue.apend(new TerrainBlock()); //Add "empty" blocks to the right
  }
}
void Init() //or ctor/loadContent/etc..
{
  fillQueue();
  foreach(TerrainBlock terrainBlock in queue)
    terrainBlock.LoadNewValues(); //Initialize the new blocks
}
void Update()
{
  foreach(TerrainBlock terrainBlock in queue)
    terrainBlock.Update(); //Update/animate the blocks
  while (queue[0].Location.X < 0) //If queue[0] is, now, off-screen...
  {
    TerrainBlock deadBlock = queue[0]; //get the one we're killing
    queue.removeAtIndex(0); //remove it from the left
    deadBlock.LoadNewValues(); //Reset the values for this "new" TerrainBlock, from disk
    queue.append(deadBlock); //add it right back to the right
  } //continue until queue[0] is the left-most on-screen block...
}

```
> 0 votes

---
Tags: ios, spritekit
---


# Question
Title: Making a night scene without being dark on the monitor
What would be a good way to make a 3D scene look "like" a dark night, without being so dark on the monitor that it's hard to see stuff (especially when playing in a brightly lit room).

I've been experimenting with making the light bluish in nature, and having a fairly dark ambient component with a brighter diffuse component, but I find the result either a bit lack-luster or still too dark, depending on the exact parameters.

Are there any good examples to study?

# Answer
This is one case where it's useful to steal ideas from Hollywood, who have been doing this for decades.

> Typical hollywood night scene, also related question from Movies.SE

The picture above was filmed during the night time, but it's not actually a dark picture. Notice how the actors' faces are very well lit, although the sky is pitch black and the road is very bright (which you wouldn't normally expect). Studying similar shots will give you some clues to how you can fake a night scene while still allowing your viewers/players to actually see.

**Tint things blue/purple**

This one's easy to guess; since sunlight is usually yellow, the spectral opposite of that happens to be bluish/purplish. That is, take neutral white light, remove yellow, and you end up with a blue/purple colour.

**Desaturate colours**

Since our night vision uses rods which can't see colour, reducing saturation emulates this effect.

**Increase contrast**

Increasing contrast has the effect of making bright things brighter and dark things darker. This simulates reality where, in dark conditions, bright things like artificial lights look much brighter in comparison, whereas we lose the ability to see dark details.

**Darken skies**

And also darken things that are typically bright during the day but dark during the night. This actually goes a long way towards the illusion and seems less "artificial" than tricks like making your scene blue. In the old days, with black/white cameras, they took advantage of this by filming during the day with a red filter over the lens, which conveniently darkens the blue sky but little else.

> *Hey look it's night time.* \- Bret Victor - Inventing on Principle

The corollary of that is to brighten things that are dark during the day but bright at night. Think artificial light sources like flashlights, campfires, computer screens. Exaggerate their brightness.

**Add light sources from "unnatural" angles**

If you don't have the luxury of actual light sources (like full moon, or streetlights) in your night scene, you still need to add some light so viewers/players can see, but make them cast light in funny angles so they aren't associated with the sun and break the illusion. Daylight typically comes from above at a slight angle, and this trope extends everywhere, even in UI where "3D" buttons are typically brighter at the top and left edges, and drop shadows extend down and right. For night time, reverse those angles. Have lights illuminating from *below*, or *behind* your subjects. Behind is particularly neat as it shows silhouettes but leaves features undefined, mimicking the ominous dark.

> Some night scene; note the light angles and the well-outlined hat and afro

A lot of these tricks come from a filmmaking technique known as "Day for night", which is where a low-budget film will shoot night scenes during the day but use a number of filming tricks and editing to make it look like night. The relevant tricks I've already mentioned above but you can read on here: http://www.videomaker.com/article/10368-shooting-day-for-night
> 68 votes

---
Tags: lighting, graphics-design
---


# Question
Title: Turn the front wheels of a car according to the car's bezier path
I have a 3D car which follows a predefined 3D Bezier path. I want the car's front wheels' rotation to match the car's changing direction.

I had the idea to match the wheel's orientation to the **derivative of the path's direction** (3D vector), aka the 2nd degree derivative of the Bezier path.

For some reason, this barely works. At some point it seems to work fine, while at others the wheel spins like hell. I noted that the 2nd degree derivative changes even when the Bezier path is a **straight line**: AFAIK in this case it should be **0**.

So, **my 1st question** is if my idea to match the wheel's rotation to the 2nd degree is the way to go. If yes, **my 2nd question** is what on earth is going wrong?

Here is my Bezier 3D curve code:

```
package fanlib.math {

import flash.geom.Vector3D;

public class BezierCubic3D
{
    public const anchor1:Vector3D = new Vector3D();
    public const anchor2:Vector3D = new Vector3D();
    public const control1:Vector3D = new Vector3D();
    public const control2:Vector3D = new Vector3D();
    /**
     * Gets values from both 'getPointAt' and 'getDirectionAt'
     */
    public const result:Vector3D = new Vector3D();
    private const previous:Vector3D = new Vector3D(); // temporary (optimization)

    // normalization aka arc-parameterization
    public var arcLengths:Vector.<Number> = new Vector.<Number>;
    public var steps:Number = 100;

    private var _length:Number;

    public function BezierCubic3D()
    {
    }

    /**
     * To get a point between anchor1 and anchor2, pass value [0...1]
     * @param t
     */
    public function getPointAt(t:Number):Vector3D {
        const t2:Number = t*t;
        const t3:Number = t*t2;
        const threeT:Number = 3*t;
        const threeT2:Number = 3*t2;
        result.x = getPointAxisAt(anchor1.x, anchor2.x, control1.x, control2.x, t3, threeT, threeT2);
        result.y = getPointAxisAt(anchor1.y, anchor2.y, control1.y, control2.y, t3, threeT, threeT2);
        result.z = getPointAxisAt(anchor1.z, anchor2.z, control1.z, control2.z, t3, threeT, threeT2);
        return result;
    }
    public function getPointAxisAt(a1:Number,a2:Number,c1:Number,c2:Number, t3:Number, threeT:Number, threeT2:Number):Number {
        return  t3      * (a2+3*(c1-c2)-a1) +
                threeT2 * (a1-2*c1+c2) +
                threeT  * (c1-a1) +
                a1;
    }

    /**
     * @param t
     * @return Un-normalized Vector3D!
     */
    public function getDirectionAt(t:Number):Vector3D {
        const threeT2:Number = 3 * t * t;
        const sixT:Number = 6 * t;
        result.x = getDirAxisAt(anchor1.x, anchor2.x, control1.x, control2.x, threeT2, sixT);
        result.y = getDirAxisAt(anchor1.y, anchor2.y, control1.y, control2.y, threeT2, sixT);
        result.z = getDirAxisAt(anchor1.z, anchor2.z, control1.z, control2.z, threeT2, sixT);
        return result;
    }
    public function getDirAxisAt(a1:Number,a2:Number,c1:Number,c2:Number, threeT2:Number, sixT:Number):Number {
        return  threeT2 * (a2+3*(c1-c2)-a1) +
                sixT    * (a1-2*c1+c2) +
                3       * (c1-a1);
    }

    public function getDirectionDerivativeAt(t:Number):Vector3D {
        const sixT:Number = 6 * t;
        result.x = getDirDerAxisAt(anchor1.x, anchor2.x, control1.x, control2.x, sixT);
        result.y = getDirDerAxisAt(anchor1.y, anchor2.y, control1.y, control2.y, sixT);
        result.z = getDirDerAxisAt(anchor1.z, anchor2.z, control1.z, control2.z, sixT);
        return result;
    }
    public function getDirDerAxisAt(a1:Number,a2:Number,c1:Number,c2:Number, sixT:Number):Number {
        return  sixT    * (a2+3*(c1-c2)-a1) +
                6       * (a1-2*c1+c2);
    }

    /**
     * Call this after any change to defining points and before accessing normalized points of curve.
     */
    public function recalc():void {
        arcLengths.length = steps + 1;
        arcLengths[0] = 0;
        const step:Number = 1 / steps;

        previous.copyFrom(getPointAt(0));
        _length = 0;
        for (var i:int = 1; i <= steps; ++i) {
            _length += Vector3D.distance(getPointAt(i * step), previous);
            arcLengths[i] = _length;
            previous.copyFrom(result);
        }
    }

    /**
     * 'recalc' must have already been called if any changes were made to any of the defining points
     * @param u
     * @return u normalized/converted to t
     */
    public function normalizeT(u:Number):Number {
        var targetLength:Number = u * arcLengths[steps];
        var low:int = 0,
            high:int = steps,
            index:int; // TODO : have a look-up table of starting low/high indices for each step!
        while (low < high) {
            index = low + ((high - low) >>> 1);
            if (arcLengths[index] < targetLength) {
                low = index + 1;
            } else {
                high = index;
            }
        }
        if (this.arcLengths[index] > targetLength) {
            --index;
        }
        var lengthBefore:Number = arcLengths[index];
        if (lengthBefore === targetLength) {
            return index / steps;
        } else {
            return (index + (targetLength - lengthBefore) / (arcLengths[index + 1] - lengthBefore)) / steps;
        }
    }

    public function getNormalizedPointAt(u:Number):Vector3D {
        return getPointAt(normalizeT(u));
    }

    /**
     * "Normalized" goes for t, not the return Vector3D!!!
     * @param u
     * @return Un-normalized Vector3D!
     */
    public function getNormalizedDirectionAt(u:Number):Vector3D {
        return getDirectionAt(normalizeT(u));
    }

    public function getNormalizedDirectionDerivativeAt(u:Number):Vector3D {
        return getDirectionDerivativeAt(normalizeT(u));
    }

    public function get length():Number
    {
        return _length;
    }

}
}

```

And here is the code that applies the 2nd degree derivative orientation to the car's wheels:

```
            const dirDer:Vector3D = bezier.getDirectionDerivativeAt(time);
            dirDer.negate(); // negate vector's values; for some reason, this gives better results
            for each (wheel in dirWheels) {
                wheel.setRotation(0,0,0); // must nullify before below line
                const localDirDer:Vector3D = wheel.globalToLocalVector(dirDer); // convert dirDer vector to wheel's local axis; wheel translation does NOT affect conversion
                wheel.setOrientation(localDirDer); // orients the object in a specific direction; Up-vector's default value = (0,1,0)
            }

```

I even tried (to no avail):

```
            for each (wheel in dirWheels) {
                const localDirDer:Vector3D = wheel.parent.globalToLocalVector(dirDer); // convert dirDer vector to wheel's local axis; wheel translation does NOT affect conversion
                wheel.setOrientation(localDirDer); // orients the object in a specific direction; Up-vector's default value = (0,1,0)
            }

```

One clear example that something is wrong: even when the car is on a straight line, the wheel originally is non-rotated (as it should), but after the car passes the center point of the line, the wheel rotates 180 degrees!

# Answer
I haven't digested all of your code. Consider the effect of using the center of the rear axle as the vehicle's origin and have that point ride the actual Bezier. As such, the car's forward direction is coincident with the tangent. Both of these relate to the path of a real car. The front wheels just need to always point directly toward their next-frame-location (t+0.0001).

If the Bezier is too "tight", the back wheels "break lose" from the pavement and the same effect occurs at the center of the front axle, instead of the back.

**Edit:** Added control points/lines in red, as well as, first- and second-order derivatives for t=0.5. The car/wheel locations for t=0.5 are in blue.

When interpolating the car's location between magenta and cyan, also lerp the wheel rotation between magenta and cyan. The positive difference in 't' between magenta and cyan is arbitrary, since it will be updated every frame.

**Edit2:** I use an AutoCAD addon called AutoTurn to design driveways that can accommodate fire-truck and/or semi-truck turn radii; it makes similar paths to the one shown below, in yellow. It is an extremely specific path based on the vehicle's lock-angle, wheel-base, etc., etc. It is not even remotely parametric.

Interpolating using the direction between (normalizedT) and (normalizedT + 0.0001) should look great.
> 1 votes

---
Tags: 3d, rotation, car, orientation, beziers
---


# Question
Title: main camera not covering whole screen in unity3d
I have been using unity and i got a problem where my main camera is covering only the first half of the floor i made. camera position is left and the floor is rotated ,i m posting an image please help . I have shown a player white coloured and an enemy pink coloured .player is not shown as you can see.

# Answer
> 1 votes
I suggest you to look at camera's clipping planes. Play with near and far and see what changes. Near plane tells camera where to start rendering the scene and far plane tells where to stop rendering. Maybe your near plane is too far and parts of your level which are closer to your camera are not rendered. You could get more info from the camera docs

---
Tags: unity
---


title: Depth Stencil Buffer

text:
# Question
Title: Depth Stencil Buffer
In OpenGL, what is the difference between GL\_DEPTH\_COMPONENT and GL\_DEPTH\_STENCIL? I have looked around and have been unable to find a clear explanation.

Information on their usage with GLSL would also be appreciated (mainly DEPTH\_STENCIL).

Thanks for any help.

# Answer
> 3 votes
It is typical to use a 32-bit depth-buffer:

```
GL_DEPTH_COMPONENT32F //internal format
GL_DEPTH_COMPONENT    //depth only
GL_FLOAT              //float(32-bit depth)

```

If you also wish to utilize the stencil buffer, it is typical to dedicate 8 of those 32-bits to the stencil:

```
GL_DEPTH24_STENCIL8   //internal format
GL_DEPTH_STENCIL      //depth + stencil
GL_UNSIGNED_INT_24_8  //ushort(24-bit depth) + uchar(stencil)

```

If you require 32-bit precision for depth, but also require the stencil:

```
GL_DEPTH32F_STENCIL8               //internal format
GL_DEPTH_STENCIL                   //depth + stencil
GL_FLOAT_32_UNSIGNED_INT_24_8_REV  //float(32-bit depth) + ushort(spare) + uchar(stencil)

```

Refer to the last chart under "Description".

Stencil diagram:

---
Tags: opengl, graphics-programming
---


# Question
Title: How to mirror flip animation curves in Unity?
I have a animation that moves my camera from **left to right**. Now I'd like to copy it with 'mirror' transformation so I can use it to move from **right to left**.

Is it possible to do it using script or purely in editor?

# Answer
> 1 votes
When importing the animation there is a 'mirror animation' checkbox under the Animations Tab in the Inspector for that asset.

If you check that box and rename the animation to "myanimation\_mirror" or whatever then you should have 2 mirrored animations.

# Answer
> 0 votes
2 Options I'm aware of.

1. Play the same animation but set it to -1 speed. It will play in reverse.

or

2. In the OS, copy the `.anim` file and rename it. Then, open the new animation in Unity and physically swap the keyframes.

---
Tags: unity, animation, camera
---


# Question
Title: unity3d - Instantiate and fire bullet realtive to player rotation in 3D
This is a top-down view but in 3D coordinates, I would like to instantiate and fire a bullet from the player's gun. This script is on a spawner object at the end of the barrel. Also tried putting the script on the player itself but also didn't work.

```
GameObject projectile =  Instantiate (bullet, transform.position, transform.rotation) as GameObject;

 projectile.GetComponent().AddForce(transform.forward * speed);

```

The problem is the bullets doesn't behave as intended, instead they don't appear relative to the player rotation and they just go in a very different direction. Shouldn't "Transform.Forward" mean forward in the Z position regarding the object's transform ?

# Answer
> 0 votes
Maybe you spawn it too close/inside other colliders. Try spawning it at some distance.

---
Tags: unity, rotation
---


title: I cant get my interface to work

text:
# Question
Title: I cant get my interface to work
This is my first time using interfaces so I imagine I'm doing something dumb. I have an interface called ILoadable inside ILoadable.cs;

```
using UnityEngine;
using System.Collections;

public interface ILoadable {
    void AssetLoader();
}

```

I also have a couple scripts that implements the interface, here's the small one;

```
using UnityEngine;
using System.Collections;

public class InputRebinder : MonoBehaviour, ILoadable {

    string upKey;

    public void AssetLoader(){
        upKey = ",";
    }
}

```

Then I have a script that I want to call all the instances of AssetLoader throughout my game.

```
using UnityEngine;
using System.Collections;

public class InterfaceControl : MonoBehaviour {
    ILoadable loader;
    // Use this for initialization
    void Awake () {
        AssetInterface();
    }

    // Update is called once per frame
    void Update () {

    }
    void AssetInterface(){

        loader.AssetLoader();
    }
}

```

I want all my assets to load up when the game starts. Assets in this case being links to gameobjects, so I'm essentially running a bunch of gameobject.find~ and I want to be able to summon those at will. Instead of working as advertised I'm getting this error;

```
NullReferenceException: Object reference not set to an instance of an object
InterfaceControl.AssetInterface () (at Assets/Resources/Scripts/Interfaces/InterfaceControl.cs:18)
InterfaceControl.Awake () (at Assets/Resources/Scripts/Interfaces/InterfaceControl.cs:9)

```

Which I know means I need to have an instance of loader in my interfacecontrol script. I think I could probably put in

loader = new InputRebinder(); But I don't want to just call input rebinder I want to call any script that has the ILoadable interface.

'for reference, I was following the instructions on dotnetperls.com in the interfaces section.

# Answer
> 0 votes
http://answers.unity3d.com/questions/46283/way-to-get-all-object-with-a-certain-componentscri.html

Here's what you're looking for. You want to find all components of this type in the scene. Since Unity 5 you should be able to find interface in the generic versions of Find\* or Get\* methods.

You should probably only do this in Awake, Start or some other method that does not run every frame since finding these can be pretty slow.

---
Tags: c#, interface
---


# Question
Title: Animation works, but Unity doesn't realize it
I have an animation which plays once, and it played once just fine. I want to Invoke a method as soon as the animation finishes. I have been researching and experimenting for over an hour now, but without the result I want. I try to get the animation from the Animator, but Unity says my animation is not attached. The thing is, I don't care if it's attached...I just want to know how long it is, not actually do anything with it. How can I achieve this? Here is the code which results in the error:

CODE:

```
using UnityEngine;
using System.Collections;

[RequireComponent(typeof(PolygonCollider2D))]
[RequireComponent(typeof(Animator))]
public class Construction : MonoBehaviour
{
    // Use this for initialization
    void Start()
    {
        Invoke("EnableObstacleState", GetComponent<Animator>().animation.clip.length);
    }

    private void EnableObstacleState()
    {
        GetComponent<PolygonCollider2D>().enabled = true;
    }
}

```

ERROR:

```
MissingComponentException: There is no 'Animation' attached to the "Barricade(Clone)" game object, but a script is trying to access it.
You probably need to add a Animation to the game object "Barricade(Clone)". Or your script needs to check if the component is attached before using it.
Construction.Start () (at Assets/Scripts/Construction.cs:11)

```

# Answer
Let's unpack this, as it looks like you might be confusing Animator & Animation

```
GetComponent<Animator>().animation.clip.length

```

**GetComponent\<Animator\>()** returns an Animator component attached to the same game object as this script instance, if one exists.

**.animation** tries to access a member called "animation" of that Animator object. Animator itself doesn't define such a member. So instead, .animation tries to access an Animation component attached to the same game object as the Animator.

(This makes the initial GetComponent\<Animator\>() call redundant, which is why I said it looks like there's some confusion here)

If there is no Animation component attached (and the \[RequireComponent\] attributes at the top don't guarantee there will be), then you can't get any information about it. It's kind of like asking "how long is the longest river that never existed?" - there's no meaningful way the engine can answer this for you.

What you might be looking for instead is:

GetComponent\<Animator\>().**GetCurrentAnimatorClipInfo**(layerIndex)

to get information about the current animation clip playing on a particular layer
> 1 votes

# Answer
Check the barricade prefab to make sure the animation is set to the animation you are trying to invoke.
> 0 votes

---
Tags: unity, animation
---


title: OpenGL ES 2.0 2D-Image displaying

text:
# Question
Title: OpenGL ES 2.0 2D-Image displaying
I have followed the official OpenGL ES tutorial to create a working OpenGL-environment. I have been able to do anything I wanted to except for displaying 2D-images. To do so I worked through this tutorial and came up with the following:

Here is my Sprite class:

```
public class Sprite
{
//Reference to Activity Context
private final Context mActivityContext;

//Added for Textures
private final FloatBuffer mCubeTextureCoordinates;
private int mTextureUniformHandle;
private int mTextureCoordinateHandle;
private final int mTextureCoordinateDataSize = 2;
private int mTextureDataHandle;

private final String vertexShaderCode =
    "attribute vec2 a_TexCoordinate;" +
            "varying vec2 v_TexCoordinate;" +
            "uniform mat4 uMVPMatrix;" +
            "attribute vec4 vPosition;" +
            "void main() {" +
            "  gl_Position = vPosition * uMVPMatrix;" +
            "v_TexCoordinate = a_TexCoordinate" +
            "}";

private final String fragmentShaderCode =
    "precision mediump float;" +
            "uniform vec4 vColor;" +
            "uniform sampler2D u_Texture;" +
            "varying vec2 v_TexCoordinate;" +
            "void main() {" +
            "gl_FragColor = (vColor * texture2D(u_Texture, v_TexCoordinate));" +
            "}";

private final int shaderProgram;
private final FloatBuffer vertexBuffer;
private final ShortBuffer drawListBuffer;
private int mPositionHandle;
private int mColorHandle;
private int mMVPMatrixHandle;

// number of coordinates per vertex in this array
static final int COORDS_PER_VERTEX = 2;
static float spriteCoords[] = { -0.5f,  0.5f,   // top left
    -0.5f, -0.5f,   // bottom left
    0.5f, -0.5f,   // bottom right
    0.5f,  0.5f }; //top right

private short drawOrder[] = { 0, 1, 2, 0, 2, 3 }; //Order to draw vertices
private final int vertexStride = COORDS_PER_VERTEX * 4; //Bytes per vertex

// Set color with red, green, blue and alpha (opacity) values
float color[] = { 0.63671875f, 0.76953125f, 0.22265625f, 1.0f };

public Sprite(final Context activityContext)
{
    mActivityContext = activityContext;

    //Initialize Vertex Byte Buffer for Shape Coordinates / # of coordinate values * 4 bytes per float
    ByteBuffer bb = ByteBuffer.allocateDirect(spriteCoords.length * 4);
    //Use the Device's Native Byte Order
    bb.order(ByteOrder.nativeOrder());
    //Create a floating point buffer from the ByteBuffer
    vertexBuffer = bb.asFloatBuffer();
    //Add the coordinates to the FloatBuffer
    vertexBuffer.put(spriteCoords);
    //Set the Buffer to Read the first coordinate
    vertexBuffer.position(0);

    // S, T (or X, Y)
    // Texture coordinate data.
    // Because images have a Y axis pointing downward (values increase as you move down the image) while
// OpenGL has a Y axis pointing upward, we adjust for that here by flipping the Y axis.
// What's more is that the texture coordinates are the same for every face.
final float[] cubeTextureCoordinateData =
        {
            -0.5f,  0.5f,
            -0.5f, -0.5f,
            0.5f, -0.5f,
            0.5f,  0.5f
        };

mCubeTextureCoordinates = ByteBuffer.allocateDirect(cubeTextureCoordinateData.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();
mCubeTextureCoordinates.put(cubeTextureCoordinateData).position(0);

//Initialize byte buffer for the draw list
ByteBuffer dlb = ByteBuffer.allocateDirect(spriteCoords.length * 2);
dlb.order(ByteOrder.nativeOrder());
drawListBuffer = dlb.asShortBuffer();
drawListBuffer.put(drawOrder);
drawListBuffer.position(0);

int vertexShader = MyGLRenderer.loadShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode);
int fragmentShader = MyGLRenderer.loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode);

shaderProgram = GLES20.glCreateProgram();
GLES20.glAttachShader(shaderProgram, vertexShader);
GLES20.glAttachShader(shaderProgram, fragmentShader);

//Texture Code
GLES20.glBindAttribLocation(shaderProgram, 0, "a_TexCoordinate");

GLES20.glLinkProgram(shaderProgram);

//Load the texture
mTextureDataHandle = loadTexture(mActivityContext, R.drawable.ic_launcher);
}

public void draw(float[] mvpMatrix)
{
//Add program to OpenGL ES Environment
GLES20.glUseProgram(shaderProgram);

//Get handle to vertex shader's vPosition member
mPositionHandle = GLES20.glGetAttribLocation(shaderProgram, "vPosition");

//Enable a handle to the triangle vertices
GLES20.glEnableVertexAttribArray(mPositionHandle);

//Prepare the triangle coordinate data
GLES20.glVertexAttribPointer(mPositionHandle, COORDS_PER_VERTEX, GLES20.GL_FLOAT, false, vertexStride, vertexBuffer);

//Get Handle to Fragment Shader's vColor member
mColorHandle = GLES20.glGetUniformLocation(shaderProgram, "vColor");

//Set the Color for drawing the triangle
GLES20.glUniform4fv(mColorHandle, 1, color, 0);

//Set Texture Handles and bind Texture
mTextureUniformHandle = GLES20.glGetUniformLocation(shaderProgram, "u_Texture");
mTextureCoordinateHandle = GLES20.glGetAttribLocation(shaderProgram, "a_TexCoordinate");

//Set the active texture unit to texture unit 0.
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);

//Bind the texture to this unit.
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mTextureDataHandle);

//Tell the texture uniform sampler to use this texture in the shader by binding to texture unit 0.
GLES20.glUniform1i(mTextureUniformHandle, 0);

//Pass in the texture coordinate information
mCubeTextureCoordinates.position(0);
GLES20.glVertexAttribPointer(mTextureCoordinateHandle, mTextureCoordinateDataSize, GLES20.GL_FLOAT, false, 0, mCubeTextureCoordinates);
GLES20.glEnableVertexAttribArray(mTextureCoordinateHandle);

//Get Handle to Shape's Transformation Matrix
mMVPMatrixHandle = GLES20.glGetUniformLocation(shaderProgram, "uMVPMatrix");

//Apply the projection and view transformation
GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mvpMatrix, 0);

//Draw the triangle
GLES20.glDrawElements(GLES20.GL_TRIANGLES, drawOrder.length, GLES20.GL_UNSIGNED_SHORT, drawListBuffer);

//Disable Vertex Array
GLES20.glDisableVertexAttribArray(mPositionHandle);
}

public static int loadTexture(final Context context, final int resourceId)
{
final int[] textureHandle = new int[1];

GLES20.glGenTextures(1, textureHandle, 0);

if (textureHandle[0] != 0)
{
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inScaled = false;   // No pre-scaling

    // Read in the resource
    final Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resourceId, options);

    // Bind to the texture in OpenGL
    GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureHandle[0]);

    // Set filtering
    GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST);
    GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_NEAREST);

    // Load the bitmap into the bound texture.
    GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);

    // Recycle the bitmap, since its data has been loaded into OpenGL.
    bitmap.recycle();
}

if (textureHandle[0] == 0)
{
    throw new RuntimeException("Error loading texture.");
}

return textureHandle[0];
}
}

```

Here is MyGLRenderer.java:

```
public class MyGLRenderer implements GLSurfaceView.Renderer {

private static final String TAG = "MyGLRenderer";
private Context context;

private Sprite sprite;

// mMVPMatrix is an abbreviation for "Model View Projection Matrix"
private final float[] mMVPMatrix = new float[16];
private final float[] mProjectionMatrix = new float[16];
private final float[] mViewMatrix = new float[16];

public MyGLRenderer(Context ctx) {
    this.context = ctx;
}

@Override
public void onSurfaceCreated(GL10 unused, EGLConfig config) {

    // Set the background frame color
    GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

   sprite = new Sprite(context);
}

@Override
public void onDrawFrame(GL10 unused) {
    sprite.draw(mMVPMatrix);
}

@Override
public void onSurfaceChanged(GL10 unused, int width, int height) {
    // Adjust the viewport based on geometry changes,
    // such as screen rotation
    GLES20.glViewport(0, 0, width, height);

    float ratio = (float) width / height;

    // this projection matrix is applied to object coordinates
    // in the onDrawFrame() method
    Matrix.frustumM(mProjectionMatrix, 0, -ratio, ratio, -1, 1, 2, 7);

}

public static int loadShader(int type, String shaderCode){

    // create a vertex shader type (GLES20.GL_VERTEX_SHADER)
    // or a fragment shader type (GLES20.GL_FRAGMENT_SHADER)
    int shader = GLES20.glCreateShader(type);

    // add the source code to the shader and compile it
    GLES20.glShaderSource(shader, shaderCode);
    GLES20.glCompileShader(shader);

    return shader;
}

public static void checkGlError(String glOperation) {
    int error;
    while ((error = GLES20.glGetError()) != GLES20.GL_NO_ERROR) {
        Log.e(TAG, glOperation + ": glError " + error);
        throw new RuntimeException(glOperation + ": glError " + error);
    }
}

//NEW
public static int loadTexture(final Context context, final int resourceId)
{
    final int[] textureHandle = new int[1];

    GLES20.glGenTextures(1, textureHandle, 0);

    if (textureHandle[0] != 0)
    {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inScaled = false;   // No pre-scaling

    // Read in the resource
    final Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resourceId, options);

    // Bind to the texture in OpenGL
    GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureHandle[0]);

    // Set filtering
    GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST);
    GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_NEAREST);

    // Load the bitmap into the bound texture.
    GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);

    // Recycle the bitmap, since its data has been loaded into OpenGL.
    bitmap.recycle();
}

if (textureHandle[0] == 0)
{
    throw new RuntimeException("Error loading texture.");
}

return textureHandle[0];
}

```

The problem that I have is that the app crashes with a

```
java.lang.RuntimeException: glGetUniformLocation: glError 1282

```

before it even opens. Thanks for any help in advance!

EDIT: I don't know if this helps but when I start my app in an AVD I get following error:

```
../../sdk/emulator/opengl//host/libs/Translator/GLES_V2//GLESv2Imp.cpp:glGetAttribLocation:857 error 0x502
../../sdk/emulator/opengl//host/libs/Translator/GLES_V2//GLESv2Imp.cpp:glGetUniformLocation:1442 error 0x502
../../sdk/emulator/opengl//host/libs/Translator/GLES_V2//GLESv2Imp.cpp:glGetUniformLocation:1442 error 0x502
../../sdk/emulator/opengl//host/libs/Translator/GLES_V2//GLESv2Imp.cpp:glGetAttribLocation:857 error 0x502
../../sdk/emulator/opengl//host/libs/Translator/GLES_V2//GLESv2Imp.cpp:glGetUniformLocation:1442 error 0x502

```

# Answer
Lacking an OpenGL compiler I forgot a semicolon. So this

```
"v_TexCoordinate = a_TexCoordinate" +

```

should be this:

```
"v_TexCoordinate = a_TexCoordinate;" +

```
> 0 votes

---
Tags: opengl, java, android, opengl-es, opengl-es2
---


# Question
Title: Unity Make sprite visible only to shaders
I have made a shader for my UI buttons, the sprites should be black and white, so they can be used as a mask when blending. They should allow for the image behind them to pass through the whiter pixels and be blocked by the darker ones.

I want to use this effect for my menu, have a black background and a colored one (like a gradient or a pattern), let the colored one pass only through the buttons and the black one everywhere else.

My shader does just that, but with one problem. I can't hide the colored background from the camera. If I change it's layer it is useless (I guess because it is the child of a canvas), and if I use a regular sprite (non UI) it is just ignored by the camera and the buttons don't pick up the color.

How can I achieve this effect, having the sprite be invisible to the camera but visible to the shaders of the buttons.

# Answer
Although it may not be what you are looking for, I generated this to show how to use the stencil buffer to achieve what you want:

The "black-shader" could just `return (0,0,0,1);` but could also sample from a texture (animated gradient, etc.)
> 1 votes

---
Tags: unity, gui, blending
---


title: Box platform collision

text:
# Question
Title: Box platform collision
I'm working on a platform game and my collision code is to picky. I can't exactly do aabb(?) because the map is represented as metatiles. (23-24 16x16 tiles make up a 300ish pixel resolution.) My game thus far simply takes the player's x/y coords and divides them by 16 to check the current tile the player is in. Thus far the only thing I have managed is a very picky collision by simply checking the divided values against weather the tile in the map is solid or not and setting a bool to the player being blocked in that direction. It works, but not solid as the x and y velocity of the player changes so much the hit point of the collision does as well. For example going left at a small speed seems pixel perfect yet full speed results in the collision taking place 5 pixels before the actual collision.

Can anyone point me in the right direction on this?

# Answer
> 0 votes
Here is what I usually use.

I have not checked it, but I hope it does not contain any mistakes.

Yes, it's a bit complex, but it gives very nice platformer physics.

```
int x = /*...*/, y = /*...*/; // Player coords.
int xv = 0, yv = 0; // Player horisontal and vertical speed.

/// Returns true if left key is being held.
bool LeftKeyHold() {/*...*/}
/// Returns true if right key is being held.
bool RightKeyHold() {/*...*/}
/// Returns true if jump key is was pressed at previous tick.
bool JumpKeyPressed() {/*...*/}

/// This func tests if point at specific coords can be passed through.
bool IsSolidAt(int xpos, int ypos) {/*...*/}
// Just divide xpos and ypos by tile size and check if tile at this position
// is solid. If so, return true, else false. Don't forget to check if these
// coordinates are in correct range, and if they are not, return false.
// (Or true if you want solid map border.)

/// This func tests if player would be inside a wall at specific location
bool IsPosSolidForPlayer(int xpos, int ypos)
{
    return IsSolidAt(xpos - 5, ypos - 5) ||
           IsSolidAt(xpos + 5, ypos - 5) ||
           IsSolidAt(xpos + 5, ypos + 5) ||
           IsSolidAt(xpos - 5, ypos + 5);
    // These are "collision points" of a character. They are relative to
    // player's center.
    // Usually they are just corner points of a character. In this case
    // character is 11x11 pixels.
    // If character is larger than tile, you MUST add more points, look at
    // image below.
    // Distance between two nearest points MUST be smaller than tile size.
    // If it is larger, add more points. Toooo many points is bad because
    // it can become slow.

    //     Character exapmples
    //              |
    //     +--------+-----+
    //     |              |
    //     V              |          'o's are collision points.
    //                    |
    // o'''o'''o          V
    // :       :
    // o   x   o        o'''o    #####
    // :       :        : x :    ##### <-- Tile
    // o...o...o        o...o    #####
    //
    //     ^              ^
    //     |              |
    //     |              +-- No extra points needed if character is small.
    //     +-- Notice the extra points at sides' centers. You would need
    //         more if character is bigger.
}

/* ... */

while (true) // Main loop.
{
    /*...*/

    yv += 1;
    // Use another number if you want different gravity acceleration.
    // Remove completely if you don't need gravity.
    // Also modify xv if you want horisontal gravity too.
    // I assume you have fixed FPS. If not, you must add 'tick delta'
    // multiplied by some number instead of fixed number.

    // Code below controls horisontal movement, remove if not needed.
    const int movementvel = 5; // Maximum movement velocity, pixels per tick.
    int hc = (RightKeyHold() - LeftKeyHold()) * 1; // Replace 1 with desired
                  // player acceleration or leave it as 1 if you don't care.
    if (!hc)
    {
        // Speed at which player loses it's velocity if he is not
        // controlled. You can replace 1 with any number or leave it as 1
        // if you don't care.
        xv -= ((xv > 0) - (xv < 0)) * 1;
    }
    else
    {
        xv += hc;
        if (xv > movementvel) xv = movementvel;
        else if (xv < -movementvel) xv = -movementvel;
    }

    // Code below controls jumps, remove if not needed.
    if (JumpKeyPressed() && IsPosSolidForPlayer(x, y+1))
        yv = -10; // Replace -10 with desired jump power. It should be negative.

    // Code below moves player depending on his velocity. Collision is
    // pixel-perfect, character can't stuck inside a wall with it.
    const int maxvel = 10; // Maximum velocity, pixels per tick.
    if (xv)
    {
        int v = xv;
        if (v > 0)
        {
            if (v > maxvel) v = maxvel;
            while (v--)
            {
                if (!IsPosSolidForPlayer(x+1, y))
                    x += 1;
                else
                {
                    xv = 0;
                    break;
                }
            }
            if (v && IsPosSolidForPlayer(x+1, y)) xv = 0;
        }
        else
        {
            if (v < -maxvel) v = -maxvel;
            while (v++)
            {
                if (!IsPosSolidForPlayer(x-1, y))
                    x -= 1;
                else
                {
                    xv = 0;
                    break;
                }
            }
            if (v && IsPosSolidForPlayer(x-1, y)) xv = 0;
        }
    }
    if (yv)
    {
        int v = yv;
        if (v > 0)
        {
            if (v > maxvel) v = maxvel;
            while (v--)
            {
                if (!IsPosSolidForPlayer(x, y+1))
                    y += 1;
                else
                {
                    yv = 0;
                    break;
                }
            }
            if (v && IsPosSolidForPlayer(x, y+1)) yv = 0;
        }
        else
        {
            if (v < -maxvel) v = -maxvel;
            while (v++)
            {
                if (!IsPosSolidForPlayer(x, y-1))
                    y -= 1;
                else
                {
                    yv = 0;
                    break;
                }
            }
            if (v && IsPosSolidForPlayer(x, y-1)) yv = 0;
        }
    }

    /*...*/
}

```

---
Tags: sdl
---


# Question
Title: How can I ensure my game complies with all asset/source licenses when preparing it for distribution?
I put together a 3D space scene demo, but I bought some models from turbosquid and using the jmonkey engine I must comply with BSD licence (jmonkeyengine) and also package the models, but I don't think that the 3D artist who created the 3D models agrees, could you tell me if there is a solution to "lock" or "encrypt" the assets that I bought from turbosquid or other ways to handle content and assets with a different licence than the source code / libraries?

In practice I've purchased a 3D model from turbosquid and I don't think that I can just include it with a BSD-licenced open source 3D scene.

# Answer
This really depends on the exact terms of all the licenses involved. If you do not understand any portion of your licensing agreements or how they would interact (if you have multiple), you should consult a lawyer. In fact, you should probably consult a lawyer even if you *think* you understand everything.

I am *not* a lawyer, and this *not* legal advice.

However, you do need to comply with the terms of the license you were granted for the use of the art assets, whatever that was. If you are not allowed to distribute the art assets, "locking" or "encrypting" the assets is probably not an option (because you are still distributing them) unless the license you were granted permits redistribution in that case.

If the license under which you are able to distribute your assets conflicts in some fashion with the license under which you must distribute your game binaries, you have a problem. You will need to work something out with one or more of the respective license holders or purchase new assets. And next time, you should conduct a complete investigation into the licensing issues before purchasing.
> 3 votes

# Answer
The 3-clause BSD license used by the jMonkeyEngine is a so-called *permissive* open source license. It allows you to take the BSD-licensed code, combine it with other code and assets, even change the BSD code when you want to, and release the resulting product under any license terms you want. The only condition you need to fulfill in order to comply with the BSD license is that the resulting work includes the copyright message and license terms of the BSD project you incorporated into your code. These license terms apply **only** to the BSD-licensed component of your project, not to anything else.

It is not uncommon for proprietary games to use libraries under permissive open source licenses like BSD or MIT. Many AAA games do this, and fulfill the license conditions simply by listing the used libraries and their license texts in the credits roll. Take Starcraft 2, for example.

Combining the 3d assets you obtained under other license conditions with BSD code does not affect the license terms of the assets in any way. In this regard the BSD license is different from viral share-alike open source licenses like, for example, the GNU GPL which requires that anything it gets combined with is also licensed under the terms of the GNU GPL.

By the way: When you have more in-depth questions about using open source licensed code in game development, you might want check out Open Source Stackexchange.
> 3 votes

---
Tags: assets, licensing
---