# Question
Title: Programatically placing musical notes on a stave
I'm trying to program a musical stave and have come against the problem of where to place a note, given its index.

The index of a note is defined from a model created from the table in the following: Piano Note Frequencies

For example, in the model, C4 has an index of 40 and D#5 an index of 55.

Here is an image of what the stave currently looks like:

The text in red shows the indices the stave has available to put notes (disregard the horizontal position). Only a few indices are shown, however they extend much further. For example, placing a note on the stave at index 0, it appears at A4 on the stave.

I'm having difficulty translating from an index in the note model, to an index on the musical stave.

At first, I've done a (knowingly) naive implementation. Index 0 in the stave corresponds to A4, or index 49 in the note model. Given an index from the model, calculate how many half steps away the index is and use this as the index in the stave. For example, C5 is index 52 and gives a stave index of 3. Looking at the above image, it's clear this is wrong for two reasons.

Firstly, we didn't account for a note and its sharp laying on the same index. Secondly, we didn't account that B4 and C5 have one half step between them, but are in different places on the stave.

I've been scratching my head over this for a while. What are the rules to follow for translating from a note index to a position on the stave?

EDIT: Each note in the note model knows whether it is sharp or not, its pitch (e.g. C, D, E, etc), and octave.

# Answer
Your indexing system for the staff cannot be used to describe all notes. The main reason is that you have 7 unique lines on the staff (A, B, C, D, E, F, G) but there are 12 unique notes (A, A#, B, C, C#, D, D#, E, F, F#, G, G#).

You need another flag to translate back and forth. My first thought would be a flag called IsSharpFlat that returns -1, 0, 1.
> 1 votes

---
Tags: algorithm, music, logic
---


# Question
Title: How to capture the screen in DirectX 9 to a raw bitmap in memory without using D3DXSaveSurfaceToFile
I know that in OpenGL I can do something like this

```
glReadBuffer( GL_FRONT );
glReadPixels( 0, 0, _width, _height, GL_RGB, GL_UNSIGNED_BYTE, _buffer );

```

And its pretty fast, I get the raw bitmap in \_buffer. When I try to do this in DirectX. Assuming that I have a D3DDevice object I can do something like this

```
if (SUCCEEDED(D3DDevice->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &pBackbuffer))) {
   HResult hr = D3DXSaveSurfaceToFileA(filename, D3DXIFF_BMP, pBackbuffer, NULL, NULL);

```

But D3DXSaveSurfaceToFile is pretty slow, and I don't need to write the capture to disk anyway, so I was wondering if there was a faster way to do this.

EDIT: I am targeting only DirectX applications. Actually DX9 apps. I am doing this through a hook to Present. (I am using Detours if that is relevant), and I am doing this for every frame. I don't need (or want) a particular bitmap format like BMP PNG JPEG etc, and a colorspace of RGB24 is OK. Getting it as YUV480p would be better but definitely not necessary. Thanks everyone for the very helpful answers

# Answer
The way I do this is as follows.

**IDirect3DDevice9::GetBackBuffer**: Get access to the IDirect3DSurface9 representing the back buffer, same as you've currently got. Don't forget to Release this surface when done as this call will increment the reference count!

**IDirect3DSurface::GetDesc**: Get the description of the back buffer surface, which will give you it's width, height and format.

**IDirect3DDevice9::CreateOffscreenPlainSurface**: Create a new surface object in D3DPOOL\_SCRATCH; you commonly want to use the same width, height and format (but you don't actually have to with this method). Again, Release when done. If you're doing this operation every frame (in which case you're better off looking at alternatives such as a shader-based approach to what you're trying to do) you could just create the offscreen plain surface once at startup and reuse it, instead of creating it every frame.

**D3DXLoadSurfaceFromSurface**: Copy from the back buffer surface to the offsceen plain surface. This will do a resize and format conversion automatically for you. Alternatively, if you don't want to or need to resize or change the format you could use **IDirect3DDevice9::GetRenderTargetData**, but if so then create the offscreen plain surface in D3DPOOL\_SYSTEMMEM instead.

**IDirect3DSurface9::LockRect**: Get access to the data in the offscreen plain surface and have your own evil way with it; UnlockRect when done.

This looks like a lot more code but you'll find that it's just as fast as glReadPixels, and can even be faster if you don't need to do a format conversion (which glReadPixels using GL\_RGB almost certainly does).

Edit to add: some (rought 'n' ready) helper functions I also have which may be useful for using this method for screenshots:

```
// assumes pitch is measured in 32-bit texels, not bytes; use locked_rect.Pitch >> 2
void CollapseRowPitch (unsigned *data, int width, int height, int pitch)
{
    if (width != pitch)
    {
        unsigned *out = data;

        // as a minor optimization we can skip the first row
        // since out and data point to the same this is OK
        out += width;
        data += pitch;

        for (int h = 1; h < height; h++)
        {
            for (int w = 0; w < width; w++)
                out[w] = data[w];

            out += width;
            data += pitch;
        }
    }
}

void Compress32To24 (byte *data, int width, int height)
{
    byte *out = data;

    for (int h = 0; h < height; h++)
    {
        for (int w = 0; w < width; w++, data += 4, out += 3)
        {
            out[0] = data[0];
            out[1] = data[1];
            out[2] = data[2];
        }
    }
}

// bpp is bits, not bytes
void WriteDataToTGA (char *name, void *data, int width, int height, int bpp)
{
    if ((bpp == 24 || bpp == 8) && name && data && width > 0 && height > 0)
    {
        FILE *f = fopen (name, "wb");

        if (f)
        {
            byte header[18];

            memset (header, 0, 18);

            header[2] = 2;
            header[12] = width & 255;
            header[13] = width >> 8;
            header[14] = height & 255;
            header[15] = height >> 8;
            header[16] = bpp;
            header[17] = 0x20;

            fwrite (header, 18, 1, f);
            fwrite (data, (width * height * bpp) >> 3, 1, f);

            fclose (f);
        }
    }
}

```
> 6 votes

# Answer
I believe you need to **LockRectangle** on the *pBackBuffer* and then read the pixels from **D3DLOCKED\_RECT.pBits** . This should be pretty fast. If you need to read only a few pixels, consider copying whole backbuffer to smaller buffer via something like DX11 CopySubresourceRegion (I'm sure there is alternative in DX9 as well), which is done on GPU and then stream this small buffer from GPU to CPU via **LockRectangle** \- you save the transfer of big backbuffer on bus.
> 1 votes

# Answer
You cannot capture screen with GetBackbuffer, this function only get a pointer of the back buffer, not the data.

The correct way I can think is as below

1. Create an off-screen surface by calling CreateOffscreenPlainSurface.
2. Call GetFrontBufferData to get the screen image to the off-screen surface
3. Call LockRect of the surface to retrieve the data in the surface, an off-screen surface was always lockable regardless of their pool types.
> 1 votes

# Answer
A bit late. But hope this helps to someone.

creating

```
        if (SUCCEEDED(hr = _device->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &backBuf)))
        {
            D3DSURFACE_DESC sd;
            backBuf->GetDesc(&sd);

            if (SUCCEEDED(hr = _device->CreateOffscreenPlainSurface(sd.Width, sd.Height, sd.Format, D3DPOOL_SYSTEMMEM, &_surface, NULL)))

```

capturing

```
    if (SUCCEEDED(hr = _device->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &backBuf)))
    {
        if (SUCCEEDED(hr = _device->GetRenderTargetData(backBuf, _surface)))
        {
            if (SUCCEEDED(hr = D3DXSaveSurfaceToFileInMemory(&buf, D3DXIFF_DIB, _surface, NULL, NULL)))
            {
                LPVOID imgBuf = buf->GetBufferPointer();
                DWORD length = buf->GetBufferSize();

```

In buf you will have raw image data. Don't forget to release everything.
> 1 votes

---
Tags: directx, directx9, screenshot, screen-recording
---


# Question
Title: Unity scene performance - better to use one scene and toggle what is active?
# Unity scene performance questions

In Unity, were one to have a scene that is basically identical in all but a few ways, would it be better to keep them as separate scenes, or to have them be one scene and have a script run during init to make all the modifications? Such as change the ground material from green to white to make it snowy, and such?

If you went the separate scene route, would that drastically bloat the project? would all things be stored twice?

# Answer
> 5 votes
Like many optimization questions, the answer here is "it depends."

Having separate scenes for each version probably won't increase your game size by much, since the **bulk of the storage usually goes to content both scenes can share** via `sharedassets#.assets` files in your built data (textures, meshes, sound & music tend to be the biggest hogs), so in many cases all that's really duplicated is the scene hierarchy. There are some caveats to this - in some cases using static batching will save a combined version of multiple meshes as part of the level file, for instance.

And when trying to combine scenes into one omni-scene, it's certainly possible to cram it full of so much alternate content that it has noticeable performance impact. As an extreme example, if every texture in the scene needed to be replaced with a snowy version, you might spend double the time you need loading the scene, pulling in twice the texture data (since Unity will typically load all referenced assets together with the scene), only to leave half of it unused.

Conversely, there are plenty of scenarios where the extra complexity of the combined scene would be trivial - maybe you're just swapping a few material & script parameters around. The best way to know for sure which case you're in is to profile it both ways and compare.

This also has to be weighed against the **development cost of maintaining multiple versions of the same scene**. If every time a level artist moves a tree, they need to save, load each alternate version of the scene, and make exactly the same adjustment in every one (or juggle multiple scenes at once), that starts to sap a lot of their time, and likely their will to keep iterating & polishing, as well as giving more opportunities for mistakes and bugs to creep in. So, a little inefficiency in the scene load, and some maintenance on the scene-alternate-switching tech, might ultimately be worth it if it helps you build & refine your game content faster.

---
Tags: unity, performance, scene
---


# Question
Title: Sprite quickly disappears after rendering
I'm currently making space invaders and I'm using the game loop pattern as described here. I have an entity class from which there is a spaceship derived class. The base entity class contains all of the general entity data such as the x/y position, speed, etc...

Currently, I have the X and Y positions initialized to (0,0) so the spaceship is rendered in the center of the screen. I tried initializing the y position to a different coordinate corresponding to a position, but for some reason, the spaceship just keep moving vertically as if the y position is just being accumulated at each frame. I think the problem is caused by the fact that in my render() method of the spaceship class, I'm translating the modelmatrix with the x and y position of the spaceship as that would explain why there isn't vertical movement when the coordinates are (0,0). I'm not sure exactly if this is the proper way to structure the render() method but I couldn't think of another way to change the object's position. Below is the relevant code:

**Spaceship class definition:**

```
class Spaceship : public Entity {
public:
    Spaceship(float xDirect, float yDirect,
        float xPosition, float yPosition, float speed, float rState, ShaderProgram* program, SheetSprite newSprite, bool movingLeft, bool movingRight):
        Entity(xDirect, yDirect, xPosition, yPosition, speed, rState, program, newSprite), movingLeft(movingLeft), movingRight(movingRight)
    {
        posY = 0.1;
    }

    virtual void Update(float elapsed) {
        // move stuff and check for collisions

        if (movingLeft) {
            posX -= elapsed* 0.001;
        }

        else if (movingRight) {
            posX += elapsed * 0.001;
        }
    }

    virtual void Render() {
        setOrthoProj();
        setObjMatrices();
        translateObj(posX, posY, 0.0);
        mySprite.Draw();
    }
    bool movingLeft;
    bool movingRight;
};

```

**Initialization Code in main**

```
Spaceship* spaceship = new Spaceship( 1.0f, 1.0f, -5.1f, 0.0f, 3.0f, 0.0f, program,mySprite, false, false);
    spaceship->Render();

```

**Game Loop movement code**

```
    const Uint8 *keys = SDL_GetKeyboardState(NULL);

    if (keys[SDL_SCANCODE_LEFT]) {
        spaceship->movingRight = false;
        spaceship->movingLeft = true;
        spaceship->Update(elapsed);

    }
    else if (keys[SDL_SCANCODE_RIGHT]) {
        spaceship->movingLeft = false;
        spaceship->movingRight = true;
        spaceship->Update(elapsed);

    }
    spaceship->Render();

```

For some reason, the first render() call outside of the loop isn't rendering the spaceship, only the one inside the loop works.

**Given the structure of the program, what could be causing the problem?**

### EDIT

**Translate method from Entity base class**

```
void translateObj(float x, float y, float z) {
        posX = x;
        posY = y;
        modelMatrix.Translate(posX, posY, 0.0);
    }

void setObjMatrices() {
        glUseProgram(program->programID);
        program->setModelMatrix(modelMatrix);
        program->setProjectionMatrix(projectionMatrix);
        program->setViewMatrix(viewMatrix);

    }

```

# Answer
You are on the right track.

Your problem is most likely here:

```
translateObj(posX, posY, 0.0);

```

You didn't post the code for that method but, from your description, you are translating the object **by**, and not **to** (posX, posY). When your objects move, they should **replace** the translation component of their world matrix.

**Edit per your edit:**

You want to modify the matrix as follows (sorry for DX style):

```
//Static method
modelMatrix = Matrix::CreateTranslation(posX, posY, 0.0f);

//or

//Simple enough to just store it
modelMatrix.Translation = Vector3(posX, posY, 0.0f);

```

Something like this:

```
virtual void Update(float elapsed)
{
    // move stuff and check for collisions
    if (movingLeft)
    {
        posX -= elapsed* 0.001;
        modelMatrixUpdated = true;
    }
    else if (movingRight)
    {
        posX += elapsed * 0.001;
        modelMatrixUpdated = true;
    }
}

virtual void Render()
{
    setOrthoProj();
    setObjMatrices();
    //translateObj(posX, posY, 0.0);
    mySprite.Draw();
}

//void translateObj(float x, float y, float z)
//{
    //posX = x;
    //posY = y;
    //modelMatrixUpdated = true;
//}

void setObjMatrices()
{
    glUseProgram(program->programID);
    if (modelMatrixUpdated)
    {
       //update or replace modelMatrix here
       modelMatrix.Translation = Vector3(posX, posY, 0.0f);
       modelMatrixUpdated = false;
    }
    program->setModelMatrix(modelMatrix);
    program->setProjectionMatrix(projectionMatrix);
    program->setViewMatrix(viewMatrix);
}

```
> 1 votes

---
Tags: opengl, c++, rendering, sdl, design-patterns
---


# Question
Title: Shading a 2D visibility mesh to act like a light?
I have a visibility mesh made by raycasting:

https://my.mixtape.moe/omjlgr.webm

Right now, I'm using a shader to color the mesh white and fall off with distance and radius (the texCoord in this case is the same as the current vertex position):

```
uniform vec2 lightPosition;
uniform vec4 lightColor;
uniform float lightRadius;

void main()
{
    float distance = gl_TexCoord[0].xy - lightPosition;

    float lightPower = 1 - length(distance) / lightRadius;

    gl_FragColor = lightColor * lightPower;
}

```

However, as you can see, this light is all white. What I want to happen, is to shade the sprites themselves fullbright. Right now, to apply an ambient light color, I set the color of every tile to the color.

So if I have an ambient color of (70, 70, 70), and a light of (255, 255, 255), I want the center of the light to have a fullbright sprite (as if you set the color if it to white), and the tiles at the very edge of the light and further to be the ambient color. To explain further, if my map is fullbright (e.g. ambient color pure white), white lights wouldn't be visible.

How would I change my shader / add another shader to accomplish this effect?

# Answer
One way to accomplish this is to use the shader to render something like a light map. You create a grayscale image which can then be used in other shaders as a mask. Moreover, this way you can enhance the light effect by applying some blur or other filters.
> 1 votes

# Answer
Why not just add `ambient` into your equation?

```
uniform vec3 ambient;
...
gl_FragColor = lightColor * lightPower + vec4(ambient, 1.0);

```
> 0 votes

---
Tags: lighting, raycasting
---


# Question
Title: Playing a simple camera animation with Animator
I haven't worked with the animation system in Unity before and am getting overwhelmed trying to figure out how to start playback of a simple animation. Yes, this is a "stupid question", but I've spent more than an hour researching this and can't find an answer on how to do something this simple:

I've created an animation called CameraZoom for the scene's camera. The CameraZoom animation is supposed to play when a specific event occurs, so I want to trigger it from script. I've created the animation on the camera, it has the Animator component attached to it, and by default the animation plays as soon as the scene starts. I can stop the animation from code, but when I try to start it, nothing happens. Here's my code:

```
private Animator myAnimation;
void Start () {
    myAnimation = gameObject.GetComponent<Animator>();
    myAnimation.Stop();
}
public void ZoomOut() {
    Debug.Log("Zoom out!");
    myAnimation.Play("CameraZoom");
}

```

This script successfully stops the animation when the scene starts, but when I call ZoomOut, the animation doesn't play.

Here are the states:

It may be I'm not understanding how to utilize the state machine and I'm trying to play the animation incorrectly. Tutorials I can find on the Animator are either too vague or discuss other features such as triggers and parameters that I don't know how to apply to such a simple task.

I know I could whip up a Coroutine to zoom the camera out in about 30 seconds, but I'm trying to learn how to utilize the Animator for basic keyframe animations.

# Answer
You don't need to stop the animation if you have an empty animator state as the starting point.

From there you have two options. You can create parameters that triggers the transition to your CameraZoom state, which you can activate by

```
getComponent<Animator>().SetTrigger("CameraZoomTrigger");

```

Or you can specifically order the animator to jump to a defined state. (docs)

```
getComponent<Animator>().CrossFade("CameraZoom", 0);

```

There's also the work in progress Playables API which lets you dynamically load an animation clip into an animator. You can look into that if you're feeling adventurous.
> 1 votes

---
Tags: unity
---


# Question
Title: Unity3D: How to convince the user of objects moving closer with layering?
I'm currently developing a Universe Simulator for Android. I had a question regarding layering. I have a list of 100k 3DPoints each represent a stars co-ordinates. I have decided to break the cameras frustum into a number of chunks.

Chunk\[0\]: This will be 3D space I will have any star inside here as this model.

Chunks\[1-N\]: The Chunk will be defined by 8 3DPoints which create that partition of the cameras frustum. These chunks will be rendered as 2D, any stars that appear will be represented as a single/multiple pixels.

How do I sell the illusion to the user that the star is smoothly growing bigger towards them? I hope to each an effect like this while keeping the workload to a minimal, I'm quite new to unity and I was wondering if anyone could point me towards the correct resources or has any insight! Cheers

# Answer
> 2 votes
Perspective projection will already make objects "twice as far" look "half as big". You need to one-up that scaling to make sure objects are dot-sized at the FARPLANE. You need two scale factors for each mesh. One of the factors, MinSize, will be shared by all of them and you can just experiment to find it. Place a mesh close to the farplane, then shrink it until it is "dot-sized". The other factor, MaxSize, is per-mesh, giving each mass their own dimensions.

A simplified example:

To be dot-sized at the FARPLANE, a MinSize of 0.01f looks good.

To be planet-sized at the NEARPLANE, a MaxSize of 50.0f looks good.

```
percentOfFrustumDepth = distanceFromCamera / FARPLANE;
//Using linear fall-off
//currentPlanetScale = lerp(MaxSize, MinSize, percentOfFrustumDepth);
currentPlanetScale = lerp(50.0f, 0.01f, percentOfFrustumDepth);

```

This makes the planet scale MaxSize (50.0f) at the NEARPLANE and MinSize (0.01f) at the FARPLANE. At 50% scene-depth, planet scale would be about 25.0005f.

You can adjust the fall-off any way you'd like, clamping it between X and Y, using different factors between DepthX and DepthY, etc., etc.

```
//Quadratic(?) fall-off
currentPlanetScale = lerp(MaxSize, MinSize, sqrt(percentOfFrustumDepth));

```

With this formula, at 50% scene-depth, the planet is about 1/4 of its' full size (71% between Max and Min). Around 25% scene-depth, the planet is half-sized.

```
//Don't lerp objects closer than 200-units
percentOfFrustumDepth = (distanceFromCamera - 200.0f) / (FARPLANE - 200.0f);
//(distanceFromCamera - 200.0f) might be negative so clamp
percentOfFrustumDepth = fmaxf(0.0f, percentOfFrustumDepth);

```

Experiment. To give a warp tunnel effect, you can also collapse the object's translations toward a single point, based on their scene-depth.

```
currentPlanetLocation = lerp(actualPlanetLocation, vanishingPoint, percentOfFrustumDepth);

```

With this formula, all incoming objects appear to originate from the same dot, spreading out to their actual positions as you get near. All out-going objects appear to collapse into the same dot, then vanish. To see what these two scaling and perspective effects might look like together, watch a few videos of ships warping in EVE Online.

A closeup of the "3D" partition:

# Answer
> 1 votes
Unity's rendering engine is not designed for interstellar scales, so you need to fake it.

Place the game objects which represent far-away stars just at the edge of the view frustum in the direction where the star is relative to the camera. Represent the stars as sprites and add a script to them which always turns them towards the camera ("billboarding") and adjusts their size according to the square-root of the distance.

---
Tags: unity, graphics, rendering
---


# Question
Title: Slaving OpenSceneGraph to an external time base?
I'm working on an OpenSceneGraph animation, and I want events in the animation to be synchronized to a time reference provided by my audio player (BASS or FMod). Yes, this is a demo :) . Which time do I set, and where? Sync is more important than frame rate or continuity - if the audio rewinds, I want the visuals to rewind, too. (To support GNU Rocket.)

I have looked at the forum posts and Google results, but haven't seen a clear answer for this use case.

* FrameStamps have a frame number, a calendar time, a simulation time, and a reference time. I think the simulation time is what I should change - is that so?
* Is specifying a new simulation time as a parameter to `frame()` or `advance()` the right way to specify the time? Will that work even if time moves backwards?

# Answer
> 1 votes
The answer can be found in the osgViewer::ViewerBase class:

```
/** Render a complete new frame.
  * Calls advance(), eventTraversal(), updateTraversal(), renderingTraversals(). */
virtual void frame(double simulationTime=USE_REFERENCE_TIME);

virtual void advance(double simulationTime=USE_REFERENCE_TIME) = 0;

```

So just pass the simulation time you want to viewer.frame(time).

---
Tags: animation, audio, timing, realtime, openscenegraph
---


# Question
Title: Unity Trail Renderer artifacts — flickering & disappearing
I have a projectile prefab that have 2 trail renderers attached to it. Whenever I instantiate another projectile, every trail renderer seems to flicker. This is similar to the question: Changes to one Unity trail renderer causes all of them to flicker

In addition to that, I have other rendering artifacts as well. Having too many trail renderers seems to cause some of them to not draw. Also, sometimes, they just seem to randomly choose not to draw.

As you can see, the left most projectile doesnt want to draw its trail.

Similarly, adding more projectiles, the front projectiles seems to lose all of its trails.

So thus, the 2 issues I am having is

* Flicking trail renderers when another is instantiated.
* Trails not rendering randomly.

Unity Version: 5.3.2f1

# Answer
This issue is fixed in Unity 5.3.3. The following is the bug tracker entry.

https://issuetracker.unity3d.com/issues/trailrenderer-flickers-and-does-not-render-at-all-times
> 1 votes

---
Tags: unity, trail-renderer
---


# Question
Title: Access buttons individually made by a for loop (old Unity GUI, Unity Editor script)
I've got a problem and I am struggling with this for a couple of days now.

I am making an Editor script and I want to access buttons individually when created by a for loop. There is a public class ButtonNode which stores some variables of the button like name and size.

```
public class ButtonNode
{
    public bool button;
    public string name = "O";
    public float sizeW = 25f;

    public void AlterButton()
    {
        name = "P";
    }
}

```

Then there is my Editor script in which I create the buttons. This is where I get stuck, how do I access these buttons individually? For example, I want to change the name of the button when that button is clicked. How do I do that? Because they are booleans (I don't really know why, this is the legacy GUI) I can't access the transform.name components etc).

```
public static ButtonNode[] bn = new ButtonNode[10];

void OnGUI()
{
    GUILayout.BeginHorizontal();

    for (int i = 0; i < bn.length; i++)
    {
        bn[i] = new ButtonNode();
        if (bn[i].button = GUILayout.Button(bn[i].name + i, GUILayout.Width(bn[i].sizeW)))
        {
            bn[i].AlterButton();
        }
    }

    GUILayout.EndHorizontal();
}

```

# Answer
> 0 votes
You are recreating your `ButtonNode` objects each time, the `OnGUI` function is being called. You will certainly want to create them at a single point in your application.

You can remove the initialization and set `bn = null`. You then check in `OnGUI` if `bn == null` and create the array and all buttons. The code should then look similar to this:

```
public static ButtonNode[] bn = null;

void OnGUI()
{
    GUILayout.BeginHorizontal();

    if (bn == null)
    {
        bn = new ButtonNode[10];
        for (int i = 0; i < bn.Length; ++i)
        {
            bn[i] = new ButtonNode();
        }
    }

    for (int i = 0; i < bn.length; i++)
    {
        // this line has to be removed, to avoid recreation of buttons
        // bn[i] = new ButtonNode();
        if (bn[i].button = GUILayout.Button(bn[i].name + i, GUILayout.Width(bn[i].sizeW)))
        {
            bn[i].AlterButton();
        }
    }

    GUILayout.EndHorizontal();
}

```

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


# Question
Title: Why do KD trees put the median split exactly on a point?
I've understood that KD tree split points using the median while cycling on each axis. I've also understood that at each node traversal, a nearest search must use a sphere to store to nearest neighbor (in case the query point is very close to the split median).

What I don't understand, is why median are always aligned with one point? Does that mean nodes are always storing one point? Does that mean each node can only have one point and 2 childs nodes ?

# Answer
Because that's how binary trees work, of which kd-trees are a special case.

In a binary tree, each node has

* exactly one value
* 0-1 child-nodes carrying a smaller value
* 0-1 child-nodes carrying a larger value

What sets kd-trees apart from normal binary trees is the way they decide what's "larger" and what's "smaller": The property which decides this cycles between tree levels.

The median of a node in a kd-tree is actually a coordinate of its value. You don't need an extra variable for this.
> 0 votes

---
Tags: algorithm, data-structure, tree, search, kd-tree
---


# Question
Title: How to calculate/detect the force of a collision? (Game-Maker Studio)
How can I use game-maker to detect the force in a collision between two mobile (not fixed) objects?

This is used for damage calculation and possibly compression calculation.

My problem is this: while net force can be calculated using mass and acceleration, the idea of damage is focused on the individual components of the force applied on an object. For instance, if a car is pushing another car against a wall, even though there are no acceleration, people will logically feel like some damage must be done to both cars because forces were conferred on them. I want to know if there is some underlying mechanism in game maker's physics system (I use the latest version) that actually calculate a reaction force from the wall on the car so I can use it to calculate damage.

# Answer
I found a solution to the particular problem that I am having:

I continue to use the physics system but instead of trying to dredge out the reaction forces acting on the object, I chose to create a "collision box" which I "attach" to all objects.

The box consists of multiple rectangles that surround a central geometry. The following code was used to give this rectangles, which I call "collision bars", a "springy" behavior:

```
if x!=X //X is the displacement of the collision bar from the central geometry
{
physics_apply_force(x,y,(x-X)^3,0)
}
//and the same is done for y

```

This means the collision bars are mobile around the central geometry but restores to a specific relative location.

If another object collide with the collision bar, there will be a displacement in the location of the collision bar, and the greater the "force of collision" the greater the force, and I can consequently use the collision bar's displacement from the central geometry to calculate the force applied on the object from a specific direction.

This may not be the most efficient or the most elegant method, but it works for the game that I am working on well enough.
> 1 votes

---
Tags: physics, game-maker
---


# Question
Title: How should I implement a timer in a strategy game?
I'm developing a real strategy game for Android and want to implement timers. Those timers will represent the time remaining until some building is finished.

Say that i have a building in construction that takes 45 minutes to be completed.

How can I communicate this timer information between my client (Android app) my server and my database? Should I communicate to the server every second in which state my timer is? Should I even do this on the server (i.e., should the timer run on the client)?

I'm inclined to assign this task to the server for security and integrity reasons, but i'm not sure on the way i can accomplish that.

# Answer
> I'm inclined to assign this task to the server for security and integrity reasons, but i'm not sure on the way i can accomplish that.

Yes, definitely; never trust clients. Clients sometimes "predict" what is *likely* to happen to help isolate the user's graphical experience from their network conditions, but any actions that could affect the outcome of the game should be validated by the server, which has final authority. That does not mean that the server has to manually "OK" each action. If the server detects cheating, the client is disconnected. If the server disagrees with the client's prediction, the client is killed. So, the fact that they have not been killed or disconnected by the server automatically tells clients they're good.

> How can I communicate this timer information between my client (Android app) my server and my database? Should I communicate to the server every second in which state my timer is? Should I even do this on the server (i.e., should the timer run on the client)?

For one, again, never trust clients to do anything critical. The clients can maintain their own "timers" but they are, again, purely for graphical fidelity.

I think you may be confused about the client and server roles. The server **is** "the timer". Clients can make educated guesses about what has *probably* happened, but nothing has actually happened on any client until it's **already** happened on the server. So, aside from the graphical reasons, there is no reason for clients to "timer" anything; the only "timer" actually required is the `Update()` loop on the server.

In that loop, the server will accumulate real time into discrete chunks of "what just happened", referred to as "ticks", and then dispatch those ticks to the clients for consumption. In many games, the client-side frame-rate, and the server-side tick-rate, are independent. Clients with higher frame-rates move through time in smaller chunks, but will still progress from tick to tick at the same rate as all other clients. Since the game occurs during the server-side ticks and not during the client-side frames, we can use the (constant) tick-rate to measure spans of time in ticks.

For example:

-30Hz tick-rate (each tick is 33.3mS)
-Player confirms build in tick 300
-Building takes 10 seconds to build

10 seconds / 0.03333333 seconds = 300 ticks

Since the server controls the creation and processing of ticks, and all clients move through ticks at the same rate, the "current tick" on any machine is a measurement from tick 0 (the beginning of the game) and can be used as an absolute timestamp to represent any past, present, or future event.

**Absolute:**
Rather than ask a timer: "Is it done yet?", "How bout now?", "Now?", etc., etc. The server can just calculate (once) that it will be finished in tick 600 (300 + 300). The server does not need any more information from the client; during tick 600, the client is notified of completion.

**Counting:**
Alternatively, you can tell the server (during tick 300) that a new building has 300 ticks worth of construction left to do. You can decrement that number down to 0 or start at 0 and increment up to 300. While construction is proceeding, the server either increments or decrements the building's counter. Depending on the method, the building is done when the counter is either (\<= 0) or (\>= 300).

Building progress may be paused by the player (client sends pause command) and by the server (player has insufficient resources for server to consume during this tick). While construction is paused, the server simply skips the increment/decrement. With multiple builders helping build the same building, the server adds/subtracts more than 1, each tick.

You may wish for the server to provide occasional progress reports to the client, just to help the clients maintain their own "timers" (for graphical purposes), but this does not have to be done **every** anything (frame/tick/second). This is just the client and server "re-synchronizing their watches" every now and again; maybe give updates at every 10% (which also automatically provides an update at 100%). When the server processes tick 600, the client is notified that the building is **actually** complete.

The client may predict the building becoming active and preemptively allow the player to issue commands to it. Even though the server hasn't confirmed the building yet, the timestamp on the commands issued by the client will be **after** building completion. So, by the time the server evaluates them, they are, indeed, valid.
> 5 votes

---
Tags: server, client-server, databases, timer, rts
---


# Question
Title: Unity/C# : How to execute a function after another function has finished its execution?
I've been trying to build a "event system" for a project that I'm working on . Here is how I'm doing it : I populate a list with reference to a gameObject and the functions that I need to execute from that gameObject . Then , when the "event" is triggered (in this case , when the player steps into a trigger collider) I just loop over the list and Invoke the functions inside it.

The problem with this is that every single function inside the list gets executed at the same time. This works fine in some cases but if I want to create a more cinematic event I need to have the ability to execute a function after the previous one has finished it's execution .Sadly I have no idea how to do that.

I've been reading a lot of the documentation of both Unity and C# about coroutines and delegates but I can't seem to wrap my head around all those things and find a way to do implement them on code .So I need your help with that :How can I achieve this?

TL;Dr version : I need your help in coming up with a way to execute a function after the previous function has ended it's execution .These functions would be stored in an array or list.

**Here is the code of the trigger of the event itself**

```
public class ActivateEvent : MonoBehaviour {

private bool activated;
public Signal[] actionList;
[HideInInspector]
public int actionEventAmount;

// Use this for initialization
void Start()
{
    activated = false;

}
void OnTriggerEnter2D(Collider2D other)
{
    if (other.gameObject.tag.Equals("Player") && !activated)
    {
        Activate();
    }
}

public void Activate()
{
    activated = true;
    for(int i=0;i<actionEventAmount;i++)
    {
        actionList[i].Invoke();
    }
}

```

}

**and here is the code for the Signal Class**

```
public class Signal
{
   public GameObject target;
   public string method;
   public string argType;

   public Signal()
   {

   }
   public Signal(System.Type argType)
   {
       this.argType = argType.FullName;
   }

 public void Invoke()
    {
        if (target != null && !string.IsNullOrEmpty(method))
            target.SendMessage(method, SendMessageOptions.RequireReceiver);
    }
    public void Invoke(object value)
    {
        if (argType != null)
        {
            if (target != null && !string.IsNullOrEmpty(method))
            {
                if (argType.Equals(value.GetType().FullName))
                    target.SendMessage(method, value, SendMessageOptions.RequireReceiver);
                else
                    Debug.LogError("Incorrect parameter type, expected [" + argType + "], got [" + value.GetType().FullName + "].");
            }
        }
        else
            Invoke();
    }
}

public class SignalAttribute : System.Attribute
{
    public string name;

    public SignalAttribute()
    {

    }
    public SignalAttribute(string name)
    {
        this.name = name;
    }
}

```

# Answer
> 1 votes
Here is a simple approach:

```
public class Manager
{
    private Worker[] workerQueue; //The array that holds the queue
    private int indexHolder;      //The integer that holds the index of most recent executed worker

    private void ExecuteNext()
    {
        workerQueue[++indexHolder].Execute(this); //Executes the next worker in queue.
    }

    public void OnExecutionFinished()
    {
        ExecuteNext();
    }
}

public class Worker
{
    private Manager _manager;

    public void Execute(Manager manager)
    {
        _manager = manager;

        Work();
    }

    private void Work()
    {
        //Do what you want to do here.

        //After your job is done, call this:
        NotifyExecutionFinished();
    }

    private void NotifyExecutionFinished()
    {
        _manager.OnExecutionFinished();
    }
}

```

---

**Edit:**

A better version which allows you to assign jobs to workers on creation:

```
using System;
using System.Collections.Generic;

public class Manager
{
    private List<Worker> workerQueue; //The list that holds the queue
    private int indexHolder;          //The integer that holds the index of most recent executed worker

    public void CreateWorker(Action job)
    {
        Worker newWorker = Worker(job);
        workerQueue.Add(newWorker);
    }

    public void StartExecution()
    {
        indexHolder = 0;
        workerQueue[0].Execute(this);
    }

    public void ClearQueue()
    {
        workerQueue.Clear();
    }

    private void ExecuteNext()
    {
        workerQueue[++indexHolder].Execute(this); //Executes the next worker in queue.
    }

    public void OnExecutionFinished()
    {
        ExecuteNext();
    }
}

public class Worker
{
    private Manager _manager;
    private Action _job;

    public Worker(Action job)
    {
        _job = job;
    }

    public void Execute(Manager manager)
    {
        _manager = manager;
        Work();
    }

    private void Work()
    {
        _job();                     //Do the job first.
        NotifyExecutionFinished();  //Then inform the manager.
    }

    private void NotifyExecutionFinished()
    {
        _manager.OnExecutionFinished();
    }
}

```

You can add workers like this:

```
    managerInstance.CreateWorker(() =>
    {
        //The job you want for this worker.
    });

```

---
Tags: unity, events, delegates
---


# Question
Title: Help with open and close UI Menu on background mouse click
I am trying to make a point and click game in unity 5.2.2.

My problem is that I need to have a UI menu to open, when the player clicks with the left mouse button on the background sprite, and it should close again, when he click on it again. I have created a script, and so far it works like that, but It also closes, when I click on the menu buttons itself, which means that I can't use the menu which opens. Please help me to how I can achive that.

The way the menu should work, is like in the game Game Dev Tycoon, where the player can open and close the menu, when clicking on the game background.

Here is my script, in its current form.

```
using UnityEngine;
using System.Collections;
/// <summary>
/// This is the main class, for the entire game. The purpose of this class, is to control any gameplay in the game.
/// </summary>
public class GameManagerScript : MonoBehaviour {

public GameObject gameUI;                                           //The actual Game UI

    public void Awake()
    {
        gameUI.SetActive(false);
    }

    // Game Manager Game Loop
    public void Update()
    {
        CheckForKeyInput();
    }

    void CheckForKeyInput()
    {
        //Mouse0 = First mouse button
        if (Input.GetKeyDown(KeyCode.Mouse0))
        {
            Debug.Log("Mouse0 button fired!");
            gameUI.SetActive(!gameUI.activeSelf);
        }
        //If escape, exit the game
        else if (Input.GetKeyDown(KeyCode.Escape))
        {
            Debug.Log("Application has been exited");
            Application.Quit();
        }
    }
}

```

# Answer
> 1 votes
You're probably looking for;

```
if(!EventSystem.current.IsPointerOverGameObject())
    ...

```

This method returns true when the mouse pointer is over a UI component. You're menu is simply being toggled when `Mouse0` is pressed. Include this inside your if statement to stop the menu being toggled when the user is over a UI element.

Hope this helped.

---
Tags: input, gui, unity, mouse, gameobject
---


# Question
Title: Example/Tutorial of passing structured data over network C++
This is very general question, about strategies how to pack same information about state of my game-world on server ( e.g. position/orientation of players, projectiles, etc. ) into data stream so that I can sent them over network and unpack them on the client side to draw on screen.

I know it's called serialization. But still I have many doubts.

1. My game already has some structure of objects. I do not want to re-design it ( too much ) in order to use some automatic serialization. I also do not want to make dependency on an other library (such as boost::serialize ) if not necessary
2. My classes/objects e.g.(class Airplane) contain some properties which should be passed over network to the client ( e.g. position and orientation ) but also some which should not ( e.g. some temporary variables relevant just for computations on server; pointers to nearest neighbor objects; array of Lift and Drag coefficient for set of angles-of-attack )
3. If I pack more objects into one message/packet I will probably need some protocol and parser to unpack the objects properly on the other side. The client should know of which *Class type* data are and to which *instance* it should be assigned.

Probably by trial and error I can figure it by myself, but it would take some time, and it would be helpful to have some example solution of similar problem to start with.

---

**background** \- I have some skill with physics and graphics programming (Java,C++,Frotran,GLSL,OpenCL...), but I know absolutely nothing about networking. I have done some games into which I would like multiplayer. Just simple games with only few players and moving objects (projectiles). For reference consider something like LIERO

# Answer
> 2 votes
There are things like Protocol Buffers, MessagePack, Capn Proto, Flatbuffers, etc. that can handle serialization for you, but I ended up doing something relatively simple. I wanted something that worked on my own data structures instead of switching to someone else's, and I didn't need most of the features they offered (backwards/forwards compatibility, optional fields, etc.). Backwards/forwards compatibility is very useful for serializing to disk or database, but for serializing to network, I didn't need it.

I did something structured like `operator << (ostream&, T&)`, `operator >> (ostream&, T)`, but for binary instead of the standard stream formatting. I don't modify the original data structures at all. Boost calls this “non-intrusive” serialization.

Let's say you have a `Point` type with `x`, `y`, `_temporary`, but you don't want `_temporary` to be serialized. With `operator <<` you could write it like this:

```
ostream& operator << (ostream& out, const Point& p)
{
    return out << p.x << p.y;
}

```

The main idea is that `<<` is already defined on numbers, so I'm defining the new operation `<<` on `Point` in terms of the existing operations on numbers.

I took that same idea but made it work for binary and json serialization.

If I have `serialize(int)`, `serialize(vector<T>)`, etc., then for a user defined type like `Point`, I only need to define a function:

```
serialize(const Point& p)
{
    serialize(p.x);
    serialize(p.y);
}

```

In that function I don't mention `_temporary` so it doesn't get serialized. If you then want to write out a `LineSegment` and it's made up of two `Points`, and you've already defined `serialize(Point)` you can define `serialize(LineSegment)` by calling serialize on the two points.

I also wanted to not have to write that once per type of operation (binary serialize, binary deserialize, json serialize, json deserialize, imgui gui output, etc.) so I abstracted a bit more, to something like this:

```
visit(Operation& op, const Point& p)
{
    visit(op, p.x);
    visit(op, p.y);
}

```

I also wanted to handle messages of varying types. Instead of writing out the type for every single struct, I use mapbox variant, and use that type *only* in places where the type can vary. To write out a variant type, I write out the variant index, then I write out the data. To read in a variant type, I read in the variant index, then construct a struct of the corresponding type, then read in the data. It became much simpler this way.

So all of this is a high level description but it might help to see the actual code with some tests. I'm not going to say my code is great, but here it is: link. Take a look at traverse.h to see how BinarySerialize works. There's a function to write out a signed int, an unsigned int, a string, and a vector. Then if you write out a `Point`, it writes out the `x` and the `y`, which end up recursively calling the functions to write out whatever type those fields are. For integers, I originally just wrote out the bytes, but switched to Google's zig-zag format because it's more compact, handles little/big endian, and handles 32bit/64bit. I haven't yet uploaded the mapbox variant serialization but if you need that let me know.

Other approaches that might be worth a look: boost fusion, this blog post, the cereal library, self-aware structs. For various reasons I ended up not using any of these and made my own :( but I'm happy that my code is rather short and simple, and can also "serialize" to a gui for in-game visualization or to std::cout for logging.

# Answer
> 1 votes
**1 & 2)** I would suggest the easiest approach without adding too much overhead would be to add seperate replication logic for networked objects. A Replicate and an OnReplicated method to each network enabled object (perhaps via an interface or abstract base class). The Replicate function would take an ostream object and use the operators to add the data needed (don't forget to encode std::string as spaces make the read from the istream after passing it from the network act poorly). Then you would add some kind of networkId for the object's instance so that when it is pushed across the wire, the server and other clients would know which object to grab a pointer to and call OnReplicated, passing in an istream object to read the data from. Here is some example code (where UUID is a struct, or value that is guaranteed unique):

```
class BaseNetworkReplicable
{
public:
    BaseNetworkReplicable();
    virtual ~BaseNetworkReplicable();
    virtual void Replicate(std::ostream& out) const;
    virtual void OnReplicated(std::istream& in);

private:
    UIID networkUIID;
};

```

And then the implementation (where MyUIIDGenerator is some kind of class that guarantees a unique value every time its MakeUIID method is called):

```
BaseNetworkReplicable::BaseNetworkReplicate()
{
    networkUIID = MyUIIDGenerator::MakeUIID();
}

BaseNetworkReplicable::~BaseNetworkReplicate()
{
}

void BaseNetworkReplicable::Replicate(std::ostream& out) const
{
    out << networkUIID;
}

void BaseNetworkReplicable::OnReplicated(std::istream& in)
{
    in >> networkUIID;
}

```

Finally, you would need to define a network replication protocol. Could be something as simple as this definition:

```
struct ReplicationPacket
{
    static const int ReplicationPacketTypeId;
    int networkUIID;
    int length;
    char* data; // or a stream
}

```

Then when you write it, you simple write the networkid, the length and the data to the wire. From the receiving end you ask a lookup table for a pointer to the BaseNetworkReplicable object with that networkUUID that matches the networkUUID sent in the ReplicationPacket.

By having a base class type of BaseNetworkReplicable, you don't need the extra logic of knowing the class type. This is essential for serialization, but since you are using virtual functions, it should auto-magically deserialize the replicated data for you.

**3)** I mentioned above that you really don't need to know the class type anymore if you use a seperate Replication pipeline. However, you mentioned packing multiple objects. You would just create a seperate ReplicationPacketCollection:

```
struct ReplicationPacketCollection
{
    const int replicationPacketCollectionTypeId;
    int packetCount;
    int totalPayloadLength; //sum of all ReplicationPacket lengths + ((3 * sizeof(int)) * number of packets) + (2 * sizeof(int))
    ReplicationPacket* collection;
}

```

I have covered a lot of the base objects needed to start up the framework for network replication but there is a lot more to cover. Such other considerations are:

* Who owns the object that controls the true state
* How to tell connected 'slave devices' that a new object was created on the 'master device' and need to add an entry for that network object in the replication lookup table
* Registering replicated objects
* the network code to write to and read from the network stream
* Handling pointers (I solved this by writing a NetworkUIID instead of a pointer and has some helper pointer serialization logic to fetch the correct pointer on the devices on the other side of the network.)

I hope this helps you get started!

---
Tags: c++, networking, multiplayer, sdl2
---


# Question
Title: Setup script variables before attaching to an object
I need to attach a script at runtime, but that script requires some public members to be set in order to be helpful. Is there a way for me to setup the public members of the script before attaching it to a GameObject at runtime?

# Answer
The ***Start()*** method and ***Update()*** method of the component will be called after the frame you add them.

So you can set all your public variables right after the line you add them.

The only thing you should be careful about is the ***Awake()*** method, which is called at the instant that you add the component.

Here is a brief summary of the execution order after you call ***AddComponent()***:

1. ***Awake()*** method of the component
2. The rest of the method that you added component from (the method that called ***AddComponent()***)
3. ***Start()*** method of the component
4. ***Update()*** method of the component

So, in the second step, you can safely setup component's variables that has nothing to do with Awake().
> 2 votes

---
Tags: unity
---


# Question
Title: How to access the players XBOX account from your Windows 10 game app?
We want to release a game that was previously an Android game for Windows 10 (Store / Desktop). Could you tell me how we can access the players XBOX account, see his friends and compare their scores? We also want to display their profile pictures. Sadly we don't even have an idea how the API we're looking for is called. We're confused by these "universal app" things. I saw something similar in the Minecraft app for Windows 10. Our Engine is the latest version of Unity, by the way. If informations are missing, please let me know.

All I have to know is where to find the API and it's name. A link to tutorials could be useful :)

Thanks!

# Answer
> **Do all games for Windows 10 need to go through ID@Xbox?**
>
> No. Only titles that want to feature Xbox Live are required to be part of ID@Xbox. Xbox Live lets you offer your players things like Gamertag identity, Achievements, Gamerscore, custom multiplayer features and more.

Join the ID@Xbox program.
> 1 votes

---
Tags: windows, xbox, xbox-live
---


title: Immovable object impact physics

text:
# Question
Title: Immovable object impact physics
I am trying to do some physics calculations from scratch, and as a result am creating a small bouncing ball example. However, I have some issues getting correct results from my impact physics when the ball bounces on the floor. I have attempted to follow the simple guide on Gamasutra (as referenced by my lecturer) that does impact physics between two balls. This is elastic collisions meaning the energy should be preserved (the ball should keep bouncing). I can cheat but I do want the proper physics calculations of the impact working as I need to use this for more complicated things later.

My current problem is that the ball bounces to a much higher position than it's starting point. I.e the ball starts at a specific position, with a velocity of 0,0,0 and is being effected by gravity. When it hits the floor however, the velocity calculated is much too high, so it bounces much higher (out of the screen) than the point at where it was dropped. It should, I believe, bounce back to the starting position. Here's a small gif showing what's happening.

Here's my current code. Could anyone point me in the right direction? Thanks!

```
// create sphere radius 3, color red
my_sphere = new Sphere(3, Vector(0.0,0.0,1.0) );
// set position
my_sphere->setDisplacement( Vector(0,50,0) );
// add gravity acceleration
my_sphere->addAcc( Vector(0.0, -9.82, 0.0) );

```

Physics foce calculation

```
// changes the objects velocity and position according to acceleration and time
void PhysicsObject::forceStep(float dt) {

    this->vel = this->vel + this->acc*dt;

    Vector s = this->vel*dt  + ( this->acc * (1/2.0f)  * pow(dt,2) );
    this->displacement = this->displacement + s;
}

```

Impact physics:

```
if ( my_sphere->floor_collision() ) {
        // floor properties
        Vector floor_vel = Vector(1,1,1);
        Vector floor_pos = Vector(0,0,0);
        // the floor is immovable e.g. mass=infinite
        float floor_mass = std::numeric_limits<float>::max();
        // Ball properties
        Vector ball_vel = my_sphere->getVel();
        Vector ball_pos = my_sphere->getDisplacement();
        float ball_mass = 1;
        Vector n = ball_pos - floor_pos;
        n = n.normalize();

        float a1 = ball_vel.dotProduct(n);
        float a2 = floor_vel.dotProduct(n);

        float optimizedP = (2.0 * (a1 - a2)) / (ball_mass + floor_mass);

        Vector new_ball_vel = v1-n*optimizedP * floor_mass;

        my_sphere->setVel( new_ball_vel );
}

```

# Answer
> @AzaraT What is v1? – zehelvion Feb 7 '15 at 20:05

> Ha! Good catch. That was indeed the issue. Bad variable naming from me, it was declared in another part of the program, but was supposed to be the old velocity of the ball (in the tutorial they called that v1). Thanks! – AzaraT Feb 7 '15 at 20:10
> 1 votes

---
Tags: c++, physics
---


# Question
Title: what is the best way to code an online multiplayer game?
so i want to create a simple game that runs over a network but I am having trouble deciding what needs to be done in terms of what the server needs to do and what the clients need to do. I understand I should use UDP sockets but I am unsure how to implement it within a game and have all the clients be in sync. Should the server side have like a master copy of the game where i basically runs the game and accepts moves, plays them in itself, and then sends the current state of the object to the other clients?

# Answer
In most of cases the relationship is simple:

> Client -\> Input to server
> Server -\> Calculate logic and physics, send object position and property data back to client
> Client -\> Render the scene using received data

I guess that this is what you where asking for!;)
> 4 votes

---
Tags: server, socket
---


title: Unity 5 Camera Functions Usage Error

text:
# Question
Title: Unity 5 Camera Functions Usage Error
How to use functions like ScreenToRayPoint() in Camera class?

I have used this code:

`Ray ray = camera.ScreenPointToRay(Input.mousePosition);`

and it says

> Component.camera is obsolete, instead using GetComponent()

Then I tried these:

`Camera cam = GetComponent<Camera>();`

`Ray ray = cam.ScreenToRayPoint(Input.mousePosition);`

and it says

> Camera doesn't contain a definition of ScreenPointToRay and no extension method 'ScreenPointToRay' accepting a first argument of type 'Camera' could be found.

# Answer
> 0 votes
Your code should work by the way. I think code you mentioned here is not exactly the same you used.

You did use `Camera.ScreenToRayPoint(Input.mousePosition);` instead of `cam.ScreenToRayPoint(Input.mousePosition);`

`cam.ScreenToRayPoint(Input.mousePosition);` should work without any doubt.

You can also use `Camera.main.ScreenPointToRay` from anywhere. But be sure that your Main Camera has tagged with `"MainCamera"`

# Answer
> 0 votes
I have a script named Camera, that's why I get the error(overrode UnityEngine.Camera), thanks for all the helping!

---
Tags: camera, unity
---


# Question
Title: Getting vector relative to other vector in rotating object
So I have a rotating object *a*. It is rotating at non-constant speed around it's `local x` axis. It is parented to object *b*. When the object *a* rotates, it's `local x` axis stays facing the same direction relatively to object *b*, but not the `local y` and `local z` axis.

In image the problem is explained a bit better. So I need to get a vector that is relative to the `local x` axis, but rotated by 90 degrees. And it should always match the *b* object's `local y` arrow's rotation around it's `local x` arrow. And I need to obtain a vector in global axis. I hope that you understand my problem.

So all I need is the math behind. Of course, if there is need for a dot product or cross product or something similar down there, please, don't start typing down all the math of that function:D

# Answer
So I found a solution. I can use a globalized vector for the *b* object's local `z` axis and cross it by the globalized vector of local wheel's `x` axis. Than normalize it. So in my game engine(Blender Game Engine) I can do it this way:

`direction = b.getAxisVect((0, 0, 1)).cross(a.getAxisVect((1, 0, 0)))`
> 0 votes

---
Tags: mathematics, rotation, vector, axis
---


# Question
Title: How to make my character double jump in unity3d using CharacterController?
I can now control my character in air, I used Unity's `CharacterController.Move` docs, but now I need to make my character double jump.

Here's the code.

```
public class PlayerMovement : MonoBehaviour
{

    // Moving fields
    float speed = 6;
    float jumpSpeed = 8;
    float gravity = 20;
    Vector3 moveDirection = Vector3.zero;
    CharacterController controller;
    bool isJumping;

    void Start()
    {
        controller = GetComponent<CharacterController>();
    }

    void Update()
    {
        if (controller.isGrounded)
        {
            moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
            moveDirection = transform.TransformDirection(moveDirection);
            moveDirection *= speed;
            if (Input.GetButton("Jump")) moveDirection.y = jumpSpeed;
        }
        else
        {
            moveDirection.x = Input.GetAxis("Horizontal") * speed;
            moveDirection.z = Input.GetAxis("Vertical") * speed;
        }
        moveDirection.y -= gravity * Time.deltaTime;
        controller.Move(moveDirection * Time.deltaTime);
    }
}

```

# Answer
> 4 votes
I tried your script and it seems like you're not checking if the "jump" button is pressed while in the air. The easiest way to fix this would be to add the line

```
if (Input.GetButton("Jump")) moveDirection.y = jumpSpeed;

```

to the else statement in your update function.

I would also recomend you to use `Input.GetButtonDown` insted of `Input.GetButton`.

`Input.GetButton` will trigger as long as you hold the `"Jump"` button down, making the player fly to infinity if you hold the button long enough.

`Input.GetButtonDown` on the other hand will only trigger once each time you press the `"Jump"` button, making the player jump accordingly to your jumpSpeed variable.

And if you only need double jumping and not "infinity jumping" you need some sort of counter to keep track on how many times you've double jumped.

A good coding custom is to avoid repetitions in the code. The movement in your if and else statements seems to be doing the same thing. So it's only needed once, outside of the if/else statement.

Here is the code i wrote to add the double jump functionality you asked for.

```
using UnityEngine;
using System.Collections;

public class PlayerMovement : MonoBehaviour {
    // Moving fields
    [SerializeField] // This will make the variable below appear in the inspector
    float speed = 6;
    [SerializeField]
    float jumpSpeed = 8;
    [SerializeField]
    float gravity = 20;
    Vector3 moveDirection = Vector3.zero;
    CharacterController controller;
    //bool isJumping; // "controller.isGrounded" can be used instead
    [SerializeField]
    int nrOfAlowedDJumps = 1; // New vairable
    int dJumpCounter = 0;     // New variable

    void Start()
    {
        controller = GetComponent<CharacterController>();
    }
    void Update()
    {
        moveDirection.x = Input.GetAxis("Horizontal") * speed;
        moveDirection.z = Input.GetAxis("Vertical") * speed;

        if (Input.GetButtonDown ("Jump")) {
            if (controller.isGrounded) {
                moveDirection.y = jumpSpeed;
                dJumpCounter = 0;
            }
            if (!controller.isGrounded && dJumpCounter < nrOfAlowedDJumps) {
                moveDirection.y = jumpSpeed;
                dJumpCounter++;
            }
        }
        moveDirection.y -= gravity * Time.deltaTime;
        controller.Move(moveDirection * Time.deltaTime);
    }
}

```

I hope this has answerd your question.

---
Tags: unity, movement
---


# Question
Title: Changes to one Unity trail renderer causes all of them to flicker
I'm using Unity. So I have a prefab, and this prefab has a trail renderer component attached to it.

However, for some of the game objects I want to stop the trailer renderer at certain points in time. But doing so seems to make all of the trail renderers blink; flash off and on. I've tried changing time, disabling the component, and using Clear() while hiding the trail renderer behind the background before needing to be used. All of these makes all trail renderers flicker on the frame the change happens.

I believe providing the code won't be helpful, it's just if(x) disable-action, if(y) enable\_action. What can I do?

# Answer
> 1 votes
This issue is fixed in Unity 5.3.3. The following is the bug tracker entry.

https://issuetracker.unity3d.com/issues/trailrenderer-flickers-and-does-not-render-at-all-times

---
Tags: unity, trail-renderer
---


# Question
Title: How does one generate mountains out of a Fourier transform?
I am watching this IGN video of No Man's Sky in which the founder/programmer of this game talks about how different is his game from other games. Here he talks about how mathematical equations instead of art is used to render graphic of planets and animals and even their behavior.

Then he says that instead of seeing mountains he sees only equation like Fourier transform. I have no knowledge about game development and its intricacies, but I'm curious how one might use a Fourier transform or similar mathematical operation to generate terrain without art?

# Answer
> 11 votes
One simple way is to use something like the midpoint displacement algorithm. It can be used to generate terrain, lightning, clouds, and other things as well. (It's a bit old, but easy to understand.)

It would also be possible using a Fourier Transform to add in various frequencies at various amplitudes to generate terrain.

Some systems, such as liquid flow, clouds, fire, and smoke can be modeled using Particle Systems.

In general, you can look up Procedural Generation for more information.

# Answer
> 1 votes
To provide a simple solution, in layman speak, all art through a computer is mathematics; in a sense.

When you load an image on your computer, the computer processes logic to determine what to display. This logic often difers, so the 'rules' are predefined in the format. Your computer will load a "bitmap" (.bmp) in a different way then it will load a "jpeg" (jpg). The differences are irrelevant without going into graphical design.

Ultimately, the computer understands numbers. You screen is made up of tiny dots, and a digital image simply tells the computer which dots to light up, when loaded. Delving further, it tells the computer how much red, green and blue to use on each dot, which in turn, defines our common perception of colour (Each pixel simply mixes the primary colours, and all colours are made up of our three primary colours; this concept reaches outside of computers and into real life.)

---

**At the end of the day, all you need to understand is that the computer interprets art as mathematics in every instance, in order to understand how it should display the image. You could load Van Gough through google images, but your computer will still process it in the same way**. We often call this the "interface". Within complex understanding of how the image converts, one has powerful ability over the image being displayed. This practice is so complex, that even in game developing, we often outsource a lot of this functionality to a separate system, such as Direct X.

It is not uncommon for a game to take control of this manipulation. It is easily an extremely complex subject, even for someone who is well versed in game developing. But technology has made the practice increasingly possible, so it is not surprising that someone has used it as a primary basis for their level generation.

I find a good model for "graphics-based game engine" is boxcar2D. It is a prototype that simply draws cars out of primitives, using flash, and slowly attempts to identify the best combination to create an efficient motor vehicle.

While I believe it would pose more questions than answers, for the average layman; I trust that it presents a much simpler variation of the concept of using computer graphics, as opposed to real "art" graphics.

Should you wish to delve further, I personally welcome anybody wishing to delve into game developing; However, you may find answers far quicker under the topic of "Computer Graphics".

---
Tags: procedural-generation, terrain
---


title: libgdx - Box2d debug draw not correct

text:
# Question
Title: libgdx - Box2d debug draw not correct
I have a problem where the bodies in my debug draw does not draw correctly, take a look:

As you can see, there is some space between the dynamic body and the ground. I have checked the contact listeners and they are indeed colliding, but with a space inbetween. The contact point is not drawn either, which gives the hint of some drawing error (?).

My PPM = 100. If I set it to 1, the problem disappears (dafuq), but that's not really feasable to have a 1 pixel/meter ratio. I have tried to play around with the cameras but without result. Here is a simplified snippet from my screen:

```
public class GameScreen implements Screen {

    private OrthographicCamera cam;
    private OrthographicCamera b2dcam;

    private World world;
    private Box2DDebugRenderer b2dr;

    private static final float PPM = 100;
    private static final int V_WIDTH = 160;
    private static final int V_HEIGHT = 90;

    public GameScreen() {
        cam = new OrthographicCamera();
        b2dcam = new OrthographicCamera();
        b2dr = new Box2DDebugRenderer();
        world = new World(new Vector2(0, -9.82f), true);

        /* ... create bodies etc ... */
    }

    public void render(float delta) {
        /* I actually use more complex fixed timestep - just simplified here */
        world.step(1/60f, 6, 2);

        // Render
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        // Align the b2dr renderer to the camera
        b2dr.render(world, cam.combined.cpy().scale(PPM, PPM, 1));
    }

    public void resize(int width, int height) {
        float aspectRatio = (float) width / (float) height;
        float aspectRatio2 = (float)height / (float)width;

        // This is to maintain the same aspect ratio, using virtual screen-size
        if(aspectRatio >= (float) V_WIDTH / (float) V_HEIGHT){
            cam.setToOrtho(false, V_HEIGHT * aspectRatio, V_HEIGHT);

        } else {
            cam.setToOrtho(false, V_WIDTH, V_WIDTH * aspectRatio2);
        }

        cam.update();
    }
}

```

# Answer
http://www.iforce2d.net/b2dtut/gotchas#smallgap

> To address this problem there is a tiny space around fixtures which is used as a buffer, in which two adjacent fixtures can agree that they are touching, but there is no overlap so no correction needs to be made - they can smile at each other and relax. This is another value in b2Settings, and while you can change it (b2\_linearSlop) you should really know what you are doing before you do.

Basically there is always going to be a distance between stuff, or else stuff would vibrate and jitter. To stabilize things it will come to rest without actually being totally in contact. I guess you could change your scale to make them small enough not to be visible.

Since this is a constant mm distance my guess is that it would be noticeable on smaller scales.
> 1 votes

---
Tags: libgdx, box2d, camera, matrix
---


# Question
Title: Unity Change Ball Direction after hitting paddle in a Pong game (like in dx-ball)
I'm struggling with how to get the ball to change the bounce based on where it hits on the paddle. Normally in a pong game, the angle changes, depending on how far from center the ball bounces, and which direction of the center it bounces. I managed to do something like that:

```
//rb = rigidbody, velOnPaddleHit = predefined float
float dist = transform.position.x - paddle.position.x;
dist = transform.position.x > paddle.position.x ? dist : -dist;
dist /= paddle.localScale.x/2;
dist *= velOnPaddleHit;
rb.addForce(dist, 0,0);

```

But it's just not working / it's weird. Can anyone help me?

Edit: Here's the video showing this kind of behaviour. When the ball hits the left side of the paddle, it goes left, the velocity doesn't matter

https://www.youtube.com/watch?v=fHX\_2DLDp1w

# Answer
Calculate the dot product of the ball's position, relative to the center of the paddle, and a fixed reference direction:

Both vectors must be normalized. While bouncing, invert the y-component of the ball's velocity and use the dot product to adjust the x-component.
> 1 votes

---
Tags: unity, quaternion
---


# Question
Title: What happens if I don't call glNormal for some vertices?
Let's say I have an object where some vertices will have the same normal and some won't. Are these two equivalent? Note I'm working with an old OpenGL version (2.3 I think).

**Option 1**

```
glNormal3f(0.0, 0.0, 1.0);
glVertex3f(-1.0, -1.0, 1.0);
glVertex3f( 1.0, -1.0, 1.0);
glVertex3f( 1.0,  1.0, 1.0);
glVertex3f(-1.0,  1.0, 1.0);

glNormal3f(0.1, 0.0, -1.0);
glVertex3f( 1.0, -1.0, -1.0);
glNormal3f(0.2, 0.0, -1.0);
glVertex3f(-1.0, -1.0, -1.0);
glNormal3f(0.3, 0.0, -1.0);
glVertex3f(-1.0,  1.0, -1.0);

```

**Option 2**

```
glNormal3f(0.0, 0.0, 1.0);
glVertex3f(-1.0, -1.0, 1.0);
glNormal3f(0.0, 0.0, 1.0);
glVertex3f( 1.0, -1.0, 1.0);
glNormal3f(0.0, 0.0, 1.0);
glVertex3f( 1.0,  1.0, 1.0);
glNormal3f(0.0, 0.0, 1.0);
glVertex3f(-1.0,  1.0, 1.0);

glNormal3f(0.1, 0.0, -1.0);
glVertex3f( 1.0, -1.0, -1.0);
glNormal3f(0.2, 0.0, -1.0);
glVertex3f(-1.0, -1.0, -1.0);
glNormal3f(0.3, 0.0, -1.0);
glVertex3f(-1.0,  1.0, -1.0);

```

# Answer
> What happens if I don't call glNormal for some vertices?

It will use the last `glNormal` value that you have set when you call `glVertex3f`.

You can view OpenGL as a state machine. Calling `glNormal` will change the state of the 'current normal', and that's all. As it can be read in MSDN documentation:

> The current color, normal, and texture coordinates are associated with the vertex when glVertex is called.

And about your question:

> Are these two equivalent?

You'll achieve the same effect, so effect-wise, yes, they are equivalent.

However, if this situation will occur often during the run-time, it would be wise to reduce the number of unnecessary calls to OpenGL to increase performance. Thus they're not equivalent efficiency-wise; you should use *Option 1* as much as possible.
> 3 votes

# Answer
`glNormal` just sets the *current* normal, just like `glColor` sets the current color, et cetera. When you call `glVertex`, the current normal, color, texture coordinates, and so on are associated with the specified vertex.

So you don't need to call `glNormal` for *every* vertex if you want your vertices to reuse whatever the current normal is.

(In other words, yes, those two options you posted are equivalent.)
> 2 votes

---
Tags: opengl
---


# Question
Title: How could I implement destruction of bases in Space Invaders type game?
What approaches could you use to implement the the gradual destructions of bases/shields in a top down shooter type game similar to Space Invaders?

The simplest approach could be to use a series of sprites that are replaced to show increasing deterioration after each missile hit.

A more advanced approach might be to randomize the deterioration pixel by pixel after each hit, but I'm not sure how to implement an approach like this. Does anyone have any suggestions for how to approach something like this?

# Answer
> 2 votes
A series of pre-defined sprites, per base, is a reasonable and simple approach.

A more dynamic approach that reflects the damage to each base on a per-pixel can be accomplished via a *mask*. The mask is a simple bit map corresponding to the base sprite. 0 for an invisible pixel, 1 for a visible one. Initially the mask would look like a blacked-out version of the base. For example, with crude ASCII art:

```
  mask         sprite
  ----          ----
00111100        ####
01111110       ######
11100111      ###  ###

```

When you render, you use both the mask and the real sprite and you skip drawing any pixels of the sprite where the mask is 0. In the old days we'd do this with bitwise magic prior to blitting the sprite; on modern platforms you'd probably accomplish this by multiplying the mask's color with the sprite's color.

Whenever a base takes a hit, you update the mask by:

* determine which horizontal column of the base was hit
* set the first non-zero bit in that column to 0 (starting from the top)

This will give you a per-pixel degradation of the base as it takes damage.

---
Tags: java, collision-detection, sprites, procedural-destruction
---


# Question
Title: Adversarial Search AI having problems with too many choices
I'm a game designer working with a set of coders trying to create a card game. Currently we're trying to implement a drawing mechanic in which you choose which card you draw, but the Adversarial Search AI can't keep up with that many choices and can only look two turns ahead without this new mechanic. I'm pretty set on finding a way to make this work, does anyone have and alternatives to fixing this problem?

I've tried reducing the space down to having only a few choices out of the deck, but the problems comes from the AI having to see what the player is going to draw. I'm pulling my hair over this problem, any thoughts?

# Answer
It seems you're using the Minimax algorithm, is that correct? If you already didn't, you should at least implement Alpha-Beta pruning in order to reduce the number of explored branches of your game tree. If it is not enough, the task at hand may be more suited to MCTS, which is used in Go due to the large branching factor, just like the one you describe.
> 2 votes

# Answer
You would need to create 3 states for your AI: Opening, Middle, Closing.

During the Opening State of your AI, it uses a lookup table of all possible moves that it's oppenent chooses. With an exact response to do against it. This may be anywhere between 1-4 moves total, but it helps with search times by reducing it to 1. Creating a look up table is tough, and requires lots of time, and simulations. These tables are used to compete in World Computer Games Championships in Chess, Hex, GO, Breakthrough, and more.

During the Middle State of your AI, it will use the main search algorithm. Monte Carlo Tree Search is a widely used algorithm for searching for strong moves to do. However, just a plane MCTS will not cut it for every case. To reduce the time for this search you would want to implement an Early Playout Termination (EPT) algorithm. This allows the MCTS to stop searching if a condition is met before the end of the search. Along with all of these algorithms you will also want to implement a visit count for each state/command/move, these visits are put on a high precedence for searching. A state/command/move with low precedence will be searched last and least often. Then ontop of that you can implement a common sequence of states/commands/moves, which stores a group of moves in one move.

For the Closing State of your AI, it will have a lookup table for finishing the player off. It will have any number of moves which when it is cable of doing it will do with no tree searching. Basically the same as the opening book, a quick check if there is a *win* found, then go for it.

During the Middle State of your AI, it could have alternate states where it needs to do certain things, and it will focus on those options during the tree searches. Things such as "Low Health", "Too many cards in hand", "Enemy has no cards". These states will have the AI specifically look for a certain paths in it's tree travesal by it's weight factor. These weight factors will weigh in on your Minimax searches, and ignoring certain paths like using a move point drinking a health potion (Already full health, ignore this path)
> 1 votes

---
Tags: game-design, ai, game-mechanics, python, card-game
---


title: flashpunk animation problems

text:
# Question
Title: flashpunk animation problems
i am having a problem with animations in my game using flashpunk

this is one of the animations that are causing problems in the game. The animation looks like that. The actual entity however with the animation on it looks like this
but without the tiled background

the code i am using is this

```
package
{

import net.flashpunk.Entity;
import net.flashpunk.graphics.Image;
import net.flashpunk.FP;
import net.flashpunk.graphics.Spritemap;

public class Fireball extends Entity
{
    public var angle:int = FP.angle(Player.playerX,Player.playerY,FP.world.mouseX, FP.world.mouseY);
    [Embed(source = 'Images/fire ball.png')] private const FIREBALLANIME:Class;
    protected var animatedSprite:Spritemap = new Spritemap(FIREBALLANIME,128,128);

    public function Fireball()
    {

    animatedSprite = new Spritemap(FIREBALLANIME, 16, 16);
    graphic = animatedSprite;
    animatedSprite.add("defaultfire", [0, 1, 2, 3], 24);
    x = Player.playerX;
    y = Player.playerY;
    animatedSprite.play("defaultfire");
    }
    override public function update():void
    {

    }

}

}

```

i turned the png's into an animation using texture packer. The ide i am using is FlashDevelop. I used pyxel edit to make the actual art.

# Answer
> 1 votes
I assume that with texture packer you mean TexturePacker, right?

The default settings in TexturePacker assume that you use a data file wich describes the positions of the sprites in the sheet. Why? Because this allows a whole bunch of nice tricks like removing transparency, packing different sized sprites and more.

Your code does not use such a data file - for this you have to change a bunch of the settings:

1. Layout \> Algorithm = Basic
2. Layout \> SortBy = Name
3. Layout \> ShowAdvanced \> Detect Identical Sprites = Off
4. Sprites \> Trim Mode = None

Also make sure that your sprites all have the same size and the animation is aligned within the sprite frames.

---
Tags: flashdevelop
---


# Question
Title: Can unity playerprefs fail to save, and if they do how can I check?
As the title says I would like to know if playerprefs can fail to save.

If they can, is there some way to check if it save properly / if it failed?

---

Example :

```
if (playerprefsFailed)
{
    Debug.Log("Failed to save playerprefs...");
}

```

---

I found `PlayerprefsException` in the Unity API, however I'm confused on how to use it.

I have also googled if they can fail, but couldn't find any results, however considering there is a exception for it, it can probably fail.

The `PlayerprefsException`is also only thrown on the web player however I would like to know if it can fail, and when, and also how to stop it on a normal pc build.

# Answer
> 4 votes
PlayerprefsException will be usually be thrown in web app where 1mb limit gets passed. Docs

To check if playerpref got saved use,

```
if(PlayerPrefs.HasKey("myFloat"){
PlayerPref.setFloat("myFloat",myFloatValue);
}else{
//First time initlisation of playerPref
}

if( !PlayerPrefs.HasKey("myFloat") || PlayerPref.getFloat("myFLoat") != myFloatValue){
 Debug.Log("Failed to save playerprefs...");
}

```

---
Tags: unity
---


# Question
Title: Blender to Unity, Specular Hardness/Smoothness Texture
In Unity there's a parameter for specularity (both modes) - Smoothness... I don't know what it corresponds to in Blender. You can bake two specularity maps: color and intensity, and at first I naively thought it to be intensity, but the result in Unity doesn't look quite right (beside the fact that it doesn't actually make sense). So I've decided that it's Hardness, but there's no baking option for Hardness in Blender, and I don't know what I'm supposed to do. I guess I could edit the alpha of the specular color texture down to prevent the object from looking like it's made from wet glass (although just the color is going to help there, I think), but maybe I'm missing something.

# Answer
> 1 votes
It doesn't really correspond to anything in Blender, unless you remake Unity's *Standard Shader* using Blender's Cycles.

The basic materials in Blender use relatively simply models, whereas Unity's Standard Shader is based on PBR and global illumination - where specular is much more complicated and interacts with a fresnel effect, in addition to receiving some light reflected by nearby surfaces. The Standard Shader material charts demonstrates what the different parameters mean. You may be able to get a better idea of how to accomplish what you're after by looking at those.

If after reviewing everything you're not actually interested in using full physically based rendering - which can be rather complex to bake for - you can simply switch the material to one of the Legacy Shaders in Unity.

See also:

---
Tags: textures, unity, blender
---


# Question
Title: Unity rigidbody exhibits a premature max speed
In effort to build a racing simulator, I have been working on a working model for the pistons in the engine, and have come to a bit of a stand still.

I have gone through extensive testing, through which we have "dumbed down" our prototype, in efforts to localise the actual problem.

We have a wheel, represented by a basic cylinder. I have added a second cylinder as a sort of knob, which allows us to run the system, and easily visualise its spin, using the following line;

Throughout various tests, a common observation is that the wheel does not appear to spin correctly. Using a collision plane to derive rotations per minute, we have determined that at a certain "thrust", the wheel reaches its maximum speed. Past a value of approximately 'thrust = 5,000', the wheel will not increase its speed. At present, this gives us a rotation of approximately 60 rotations per minute. Ideally, we want to be able to reach the breaking point of about 10,0000.

```
 rigidbody.AddTorque(transform.up * Time.deltaTime
                                  * rotatioonSpeed, ForceMode.Acceleration);

```

What causes the rigidbody to 'cap' its force? Everything is at default, as per various tutorials we have explored; As far as we have looked, various values might have an impact, but not to the point where speed hits a maximum on its own merit.

Incase it matters, a some extra information about the system:

* We are not yet using conventional Unity measurements. While to scale, the pistons are quite larger then normal, with the cylinder housing the piston holding a length of approximately 2 meters.
* Once "thrust" exceeds the maximum allowance to impact on speed, the value appears to weigh on breaking force, instead. Prior to reaching maximum speed, the user needs to "push" on the opposite direction, to reverse the rotation. It can take a second or two before the wheel slows down, and reverses its direction. The further past this maximum we go, the quicker the engine will immediately move in the reverse direction.
* There is nothing else imparted on our model for this behaviour to take place. We are literally dealing with a wheel with a joiner pin on the side.
* As stated, tutorials we have viewed tend to suggest that the values in the rigidbody should not effect the behaviour, this early. That said, here are our values:

```
Mass: 1
Drag: 0
Angular Drag: 0.05
Use Gravity: False
Is Kinematic: False
Interpolate: None
Collision Detection: Discrete
Constraints: FreezeRotationYZ

```

My best attempts to find a similar problem online ironically reaches a bunch of articles on users attempting to **enforce** a maximum speed. For best results within scope, we would hope to be able to reach infinite speeds, and separately work out whether the speed of our wheel would cause a major fault, in turn limiting the speed it would potentially reach in practice.

Personally, I suspect that the size of the object would make a difference, as unity perceives it. Another member on my team argues that because the rigidbody uses relative values, size should not make a difference. Unfortunately, this is as far as we can get in localising the problem.

# Answer
> 1 votes
It looks like it's limited by a single field on Rigidbody. Give this a try:

```
using UnityEngine;
public class RotateTest : MonoBehaviour
{
    private Rigidbody _rigidbody;

    // Change in acceleration
    public float DeltaAcceleration = 0.1f;

    // To display current angular velocity in editor
    public float Velocity;

    void Start ()
    {
        _rigidbody = GetComponent<Rigidbody>();
        _rigidbody.maxAngularVelocity = float.MaxValue; // <-- most important line
    }

    void Update ()
    {
        DeltaAcceleration += Time.deltaTime*0.1f; // increase acceleration over time
        _rigidbody.AddTorque(Vector3.up*DeltaAcceleration, ForceMode.Acceleration);
        Velocity = _rigidbody.angularVelocity.magnitude;
    }
}

```

---
Tags: physics, unity, rigidbody
---


title: Velocity Relative To A Vector

text:
# Question
Title: Velocity Relative To A Vector
So I have a velocity vector *`b`* in world space and I have a "pointing" vector *`a`* in world space. I need to know how to make the velocity vector to be relative to the "pointing" vector. Better explanation in image below:

So on the left you can see the vectors in world space, but on the right - vectors in *`a`* space. I need to get the vector *`b`* in the _`a`\_space from the worldspace.

# Answer
> 1 votes
So I solved this in kind of simple way. As I had the pointing vector(which in my specific case was `y`, but it doesn't matter that much) and I found out that I can actually get another vector out here. So I made a vector plane of `x` and `y` vectors. Than I did `x.cross(y)` and obtained `z` vector. Than I made those vectors 4D by setting `w` to be 0. After that I created a new matrix and plugged each of those vectors into the matrix - `x` into column 0, `y` into comun 1 and `z` into comlumn 2. In the result I had a transformation matrix which I could use as multiplier for the velocity vector and obtained velocity relative to the vector. Unfourtunately, I should say that vector to vector-space conversion requires 2 vectors. Fourtunately, I had 2:)

# Answer
> 1 votes
you can just convert the coodinates.

to do this, you have to use the normalized `â` as an base vector for the new coodinating system then use the 90º rotated `norm(a.y,-a.x)` as another base.

lets name they as `e1` and `e2`.

now you can express your vector `b` as an linear combination of `e1` and `e2` with the linear system of equations:

```
b = m*e1+n*e2

b.x = m*e1.x+n*e2.x
b.y = m*e1.y+n*e2.y

```

solve for `m` and `n` and the vector `(m,n)` is your `b` in `a` coodinates

# Answer
> 0 votes
The “velocity in **`a`** space” can be broken down in two vectors, one that is the same direction as **`a`**, and one that is perpendicular to **`a`**.

The first vector has direction **`u`** and size `su`, computed as follows:

```
u = normalize(a)
su = dot(u, b)

```

The perpendicular vector has direction **`v`** and size `sv`:

```
v = normalize(b - su * a)
sv = dot(v, b)

```

---
Tags: mathematics, vector, linear-algebra, direction, spaces
---


# Question
Title: Why does SDL render the background from the operating system to the window?
My code displays a fully transparent window that copies the background from the operating system.

This is the code I use for rendering:

```
void render()
{
    SDL_RenderClear(renderer);
    SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
    SDL_RenderDrawRect(renderer, &background);
    SDL_RenderPresent(renderer);
}

```

And this is the code I use to create my window:

```
window = SDL_CreateWindow("title", posX, posY, windowWidth, windowHeight, SDL_WINDOW_OPENGL);

```

# Answer
> 0 votes
The problem is that you are passing the `SDL_WINDOW_OPENGL` flag to your window in `SDL_CreateWindow`, but then you are using the `SDL_Renderer` for rendering. You need to remove the flag for `SDL_Renderer` to function properly.

---
Tags: c++, sdl2
---


# Question
Title: Creating a toggle button in unity3d Scene vs Scripting
I am making my first GUI in unity, and I am not sure if should create the toggle buttons in the game scene by creating new UI elements or by scripting.

Creating them in the game scene gives me more options but I have trouble to manipulate the input.

Because of this I am scripting them in the monodeveloper but it seems more difficult to work the visual side (I am using a texture but can't get rid of the little box (that shows f the button is clicked or not).

How do you make your toggle buttons and how do you develop your GUI?

Any help appreciated.

# Answer
> 0 votes
I am using the canvas UI in Unity 5. And to add a button to screen, I just create a UI Image under my canvas object in Hierarchy view. Change the sprite as required.

Now add "Event Trigger" as shown below.

Next "Add new event type". I use "PointerUp".

You get an empty list.

Click + to add a function which will be called on the event ("PointerUp" in our case)

In the third field insert the object which should have the script (you want to invoke) attached to it. In my example the object is called "LevelUIControls" and it has a script called "LevelControls" attached to it.

This should make it easy for you to manipulate input.

# Answer
> 0 votes
I prefer the scripting way to make the GUI, though it's probably because the only thing I like about making games is scripting.

---

**Slipting way :**

One way to do it is to use the GUI.Toggle function in Unity.

---

**Non Scripting Way :**

If you still want to use the new GUI, here's a good tutorial : Click me :)

# Answer
> -1 votes
I prefer UI Elements...

I mostly use UI Elements for static buttons and labels..

When I need dynamic stuff going on (an inventory for example) I just script-instantiate them (using object pools)

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


# Question
Title: Should particles check if they are in a region, or regions if particles are in them?
I have around 100 to 200 particles in my game. Then I have 5 to 20 regions (circle-shape) which should count the particles which enter them and add some force to them, so they change their direction.

My idea was now to keep a list of all particles and every region should check the whole list every frame, whether a particle is inside it. For this I calculate the distance between the particle and the central point of the region and check weather its \<= the radius of the region.

Is this the most efficient way to do it? Or should every particle have a list of all regions and check whether they are in one of it? Or a totally different approach?

I would like this application to be able to run also on older mobile devices like an iPhone 4S.

# Answer
You may want to have each region contain a list of particles which are in it. Then, when you move each particle, check if it is in a new region - add it to the new region's particle list, and remove it from it's current one (based on your checking above). That way you can just tell each region to apply the force to the particles in it's list (the work has already been done for you).

I like this method because it makes the code within the region easier. Useful in case you ever need/want to apply that force the particles more than once, as it will save performance by only having to do the checking once.
> 3 votes

---
Tags: collision-detection, mobile, efficiency
---


title: Adding an InputListener to a Group

text:
# Question
Title: Adding an InputListener to a Group
I'm trying to detect when a Group actor (my "slot") on my stage is clicked by add an InputerListener to the group. I've added the stage to my InputMultiplexer, but when I click on the actor, nothing happens.

Relevant code from the main Screen:

```
InputMultiplexer inputMultiplexer = new InputMultiplexer();
Stage stage = new Stage();
inputMultiplexer.addProcessor(stage);
Gdx.input.setInputProcessor(inputMultiplexer);

```

From the Group class:

```
Label amountLabel = new Label("", GameScreen.labelStyle);
Image itemImage = new Image();
Image slotImage = new Image(new TextureRegionDrawable(new TextureRegion(new Texture("Slot.png"))));
public SlotGroup() {
    this.addActor(amountLabel);
    this.addActor(itemImage);
    this.addActor(slotImage);

    this.addListener(new InputListener() {
        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
            System.out.println("Hello world");
            return true;
        }
    });
    this.setStage(Screen.stage);
}

```

# Answer
The issue may be that the Group distributes the touch events rather than accepting them itself:

From https://libgdx.badlogicgames.com/nightlies/docs/api/

> Touch events that hit more than one actor are distributed to topmost actors first.

Check whether adding the listener to a specific widget in the group will cause it to trigger instead. If so, then this is likely a design decision within the system.
> 1 votes

# Answer
The multiplexer is of no use if you just add the stage to it. You have to add "this" to the multiplexer as well, which would be your main screen. The multiplexer can take several and the order you add them in decides which gets to handle the input first.
> -1 votes

---
Tags: libgdx, scene2d
---