title: XNA/MonoGame RenderTargets not working

text:
# Question
Title: XNA/MonoGame RenderTargets not working
I'm having a problem with drawing 2 RenderTargets to the screen.

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Content;

namespace Please
{
    class Class1
    {
        RenderTarget2D rt;
        Texture2D temp;
        Vector2 v;
        public Class1(Vector2 v,GraphicsDevice g)
        {
            this.v = v;
            rt=new RenderTarget2D(g,800,600);
        }

        public void Draw(SpriteBatch sb,GraphicsDevice gd,ContentManager cm)
        {
            gd.SetRenderTarget(rt);
            sb.Begin();
            sb.Draw(cm.Load<Texture2D>("Untitled.png"),v,Color.White);
            sb.End();
            gd.SetRenderTarget(null);

            temp = (Texture2D)rt;

            sb.Begin();
            sb.Draw(temp, Vector2.Zero, Color.White);
            sb.End();
        }
    }
}

```

Here's my draw function in the actual "game"

```
protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.CornflowerBlue);
    base.Draw(gameTime);
    one.Draw(spriteBatch, graphics.GraphicsDevice, Content);
    two.Draw(spriteBatch, graphics.GraphicsDevice, Content);
}

```

one and two have positions (100,200) and (300,200) respectively, so, they should be drawn 100 pixels apart, however, only two is being drawn with the rest of the screen black

# Answer
> 2 votes
Clear both rt's to Transparent before drawing the texture to them.

Since you will be explicitly clearing them to Transparent\[Black\], you should specify:

```
 new RenderTarget2D(..., RenderTargetUsage.PreserveContents);

```

to prevent XNA from clearing rt's rendertarget (to **not** Transparent\[Black\]) when you set the current rendertarget to NULL.

When you draw them with AlphaBlending enabled (the default), the **not** Transparent\[Black\] overwrites the backbuffer, as though you were using Opaque.

**Also:**
You should not Load\<\> the texture more than once and it should be during or after game.LoadContent(). You are currently re-re-re-re-re-loading it every time you render it.

---
Tags: xna, c#, monogame
---


title: SDL draw dynamic select box

text:
# Question
Title: SDL draw dynamic select box
This might seem obvious to many, but I'm stuck and I cannot find any tutorial which helped me, so it would be great to find the answer here.

I tried to make a rectangle like you have in RTS games, so to speak a dynamic select box, but it does not work correctly. It would also be enough is someone lists up bullet points which each step for creating a box like this.

(Don't wonder I'm really new to c++)

Mouse.h :

```
#ifndef MOUSE_H_
#define MOUSE_H_

class Mouse {

public:
    bool leftButtonDown = false;
    bool mouseMoves = false;

    struct MouseCoords {
        int x = -1;
        int y = -1;
    };

    MouseCoords start_coords;
    MouseCoords move_coords;
    Mouse(){}

    void setState(Uint32 eventType, SDL_Event event){

        if ( eventType == SDL_MOUSEBUTTONDOWN) {
            this->leftButtonDown = true;
            SDL_GetMouseState( &this->start_coords.x, &this->start_coords.y );
        }

        if ( eventType == SDL_MOUSEBUTTONUP ) {
            this->leftButtonDown = false;
        }

        if ( eventType == SDL_MOUSEMOTION ) {
            this->mouseMoves = true;
            this->move_coords.x = event.motion.x;
            this->move_coords.y = event.motion.y;
        } else {
            this->mouseMoves = false;
        }
    }

    /**
     * Provides coordinates when mousebutton down
     */
    MouseCoords getCoordinates(){
        return move_coords;
    }

    /**
     * Refresh the coordinates. MUST be called after Mouse::clearCoordinates();
     */
    void clearCoordinates(){
        this->move_coords.x = -1;
        this->move_coords.y = -1;

    }

    /**
     * Creates selector rect, call this in the render loop
     */
     void createSelectBox(SDL_Renderer *renderer){
         if(this->leftButtonDown) {
            Block rect(
                       this->start_coords.x,
                       this->move_coords.y,
                       this->start_coords.y -this->move_coords.y ,
                       this->move_coords.x - this->start_coords.x
                       );
             rect.draw( renderer );
             this->clearCoordinates();
         }
     }
};

#endif

```

Block.h

```
#ifndef BLOCK_H_
#define BLOCK_H_
/**
 * Standard Class which can be used to build a player, enemy, or something similar
 */

class Block{
    SDL_Rect rect;
public:
    Block(int x=10, int y=10, int w=10, int h=10, int filled=true){
        rect.x = x;
        rect.y = y;
        rect.w = w;
        rect.h = h;
    }

    /**
     * draw with the given rendererer
     */
    void draw(SDL_Renderer *renderer){
        SDL_SetRenderDrawColor( renderer , 200 , 155 , 255 , 255);
        SDL_RenderDrawRect( renderer, &rect );
        SDL_RenderPresent( renderer );
    }

    bool framed(){
        return 0;
    }

};
#endif

```

Then in my main.cpp

```
SDL_Window *window;
SDL_Renderer *renderer;
Mouse mouse;
Block rect;

void renderWindow(){
    window = SDL_CreateWindow("commanding rects", 100, 100, 700, 600, 0);
    renderer = SDL_CreateRenderer(window, -1, 0);
}

void renderGame(Mouse mouse){
    SDL_RenderSetLogicalSize( renderer, 400, 300 );
    SDL_SetRenderDrawColor( renderer, 0, 0, 0, 0);
    SDL_RenderClear( renderer );
    SDL_RenderPresent( renderer );
    mouse.createSelectBox( renderer );

}

void gameLoop(){
    bool game_run = true;
    while (game_run) {
        SDL_Event event;
        while( SDL_PollEvent(&event)){
            if ( event.type == SDL_QUIT ) {
                game_run = false;
            }
            mouse.setState(event.type, event);
        }
        renderGame(mouse);
        SDL_Delay( 15 );
    }

}

int main(){
    renderWindow();
    gameLoop();
    return 0;
}

```

# Answer
I finally found out what I was doing wrong.

I was retrieving the wrong start points for drawing the rectangle. When triggering the mousedown I had to get `event.button.x` instead of `GetMouseState`

Here is the updated Mouse.h

```
#ifndef MOUSE_H_
#define MOUSE_H_

class Mouse {

public:
    bool leftButtonDown = false;
    bool mouseMoves = false;

    struct MouseCoords {
        int x = -1;
        int y = -1;
    };

    MouseCoords start_coords;
    MouseCoords move_coords;
    Mouse(){}

    void setState(Uint32 eventType, SDL_Event event){

        if ( eventType == SDL_MOUSEBUTTONDOWN) {
            this->leftButtonDown = true;
            this->start_coords.x = event.button.x;
            this->start_coords.y = event.button.y;
        }

        if ( eventType == SDL_MOUSEBUTTONUP ) {
            this->leftButtonDown = false;
        }

        if ( eventType == SDL_MOUSEMOTION ) {
            this->move_coords.x = event.motion.x;
            this->move_coords.y = event.motion.y;
        }
    }

    /**
     * Provides coordinates when mousebutton down
     */
    MouseCoords getCoordinates(){
        return move_coords;
    }

    /**
     * Creates selector rect, call this in the render loop
     */
     void createSelectBox(SDL_Renderer *renderer){

        if(this->leftButtonDown) {

            float width = this->move_coords.x - this->start_coords.x;
            float height = this->start_coords.y - this->move_coords.y;
            float x = this->start_coords.x ;
            float y = this->move_coords.y;

            Block rect(x, y,width, height);
            rect.draw( renderer );

        }

     }
};

#endif

```
> 0 votes

# Answer
You have to do this:

In ever loop:

First: SDL\_RenderClear()

SDL\_RenderDraw \<-- ALL YOUR RENDED HERE, LIKE TEXTURE AND OTHERs.

And with: SDL\_RenderPresent()
> 0 votes

---
Tags: c++, sdl, selection
---


# Question
Title: Is creating a blend state like this possible?
I'm wanting to create a custom blend state that is similar to XNA's BlendState.Additive, but slightly different. I'm wanting something like the 'custom' output below:

Is something like this possible? I'd even appreciate an answer that could help point me in the right direction. Blend states are a little bit baffling to me at the moment.

For an explanation of why I need this: I'm trying to add emissive maps to our game's rendering. I think most shading that uses emissive maps handle that in the lighting shader. Unfortunately, the emissive maps aren't available to our lighting shader, so I'm just trying to draw them over the top of what's already been rendered. Using BlendState.Additive almost works, but doesn't handle situations where emissive textures are overlapping.

Thanks in advance.

# Answer
# How blend states/ blend modes work

A blend state defines how newly rendered fragments should combine with existing pixel data. They define how to mix two values:

1. The **Source Color** \- the color you are trying to render. In your case, this is a grayscale value ranging from white (in the center of the disc) to black (at the border of the disc).
2. The **Destination Color** \- the color that already exists in the exact position where you want to draw. In your example, this is a color ranging from blue to white.

The additive blend mode you experimented with says: calculate the new color value by adding all individual channels. For example, the new blue value becomes *source\_blue + dest\_blue*.

I found this page regarding blend states in XNA: https://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.blendfunction.aspx

Unfortunately, I don't think any of these will produce the effect you are looking for. I'm not sure if it's even possible to describe the effect you want as a blend function. Here are three alternative solutions you could try:

---

# Solution 1: Make your texture blue/white coloured

This *will only work* if your use-case only requires you to draw *on the blue background* you've shown in your example. If so, you could use a **disc texture** that goes from **blue (edges) to white (center)** and use the standard 100% source pixel blending. Be sure to render from left to right obviously.

---

# Solution 2: Pre-render to an intermediate texture

This is probably the cleanest method, that will work for any type of background. Rather than rendering to the screen instantly, render to an **intermediate texture** first.

1. **Initialize** the intermediate texture to be filled with a **black color**. Then draw your **spheres from left to right** with 100% source pixel blending. This will produce a texture that looks like the bottom image in your example, but with a black background rather than a blue one.
2. Next, **render** the intermediate texture **to the screen** using an **additive blend mode**. This will produce additive blending, while preserving the disc shapes as shown in your example. It will work with any background as well.

---

# Solution 3: Z-buffering method to achieve your effect

There is also a trick you could use to achieve the effect you describe. **Z-buffering** is a technique used in 3D rendering, that makes sure only the front most fragments are rendered/visible for each pixel. This works by writing the depth (= distance to the camera) of a fragment as it is drawn. Whenever a new fragment is drawn, the renderer checks whether a closer fragment was rendered before, by checking the depth buffer. You can achieve the described effect by:

1. Enable depth testing/ z-buffering
2. Draw your circles from right to left, with increasing depth

This will only work if your draw your texture on actual circular polygons, not if you draw on quads.

---

In summary, I do not believe it is possible to achieve the described effect by using an XNA blend mode. Out of the proposed solutions, think the second approach using an intermediate texture will produce the cleanest result. It is the most robust method as well, working on any background. The Z-buffering method will allow you to render to the screen instantly (not requiring an intermediate texture), but is more involved and only works for simple shapes such as circles and rectangles (as you need to construct polygonal meshes for the shapes to render on).
> 6 votes

---
Tags: xna, 2d
---


title: 3D game with Pre-rendered background

text:
# Question
Title: 3D game with Pre-rendered background
So a friend of mine and myself are starting to create our first game together. We descided on doing a 2.5D kind of game, so a static camera that moves with the player but cannot rotate.

I got the collisions object from my friend which in unity looks like this:

Now I'd like to create an overlay with a JPG image which is going to cover the entire viewport and is going to "be" the map itself. I want to use this JPG as a kind of background image and then hide the collisions so the player will walk into the collisions and stop there but can't actually see them. In stead, he will see the image with buildings on it.

How can I do this correctly? I've gotten as far as creating a second camera which will show me the image and then trying to create an Image (Create gameobject -\> UI -\> Image).

But I cannot find any way to continue on this.

Is this a good way to do this whole 2.5D kind of thing?

We want lightweight maps in our game and thought this was a good idea to go about this.

**Edit**

My friend and me are trying to create an isometric game like this. The reason behind this is that the amount of work for the map is going to be massively reduced if we can do it like this since he can then just work in photoshop, in which he's super good.

This was he does not have to bother with the 3d design in detail and can make the collision blocks much faster.

So does anyone know how to get this to work? Maybe someone has a partial guide on this because I cannot seem to find anyone doing it like this but I imagine that ie Commandos is made like this.

It would be much appreciated!

# Answer
First off, there are a lot of games that did this back in the PS1 era (eg. FF8) so this is definitely a done thing.

Basically, you need to render multiple times, and thus may want multiple cameras. First make the low-res collision geometry visible but the overlay and your characters are invisible, then render normally, then make the collision geometry invisible and the overlay image and your characters visible, then render again with the image buffer overwriting but NOT affecting the depth buffer. That way the character will be correctly occluded by the invisible collision objects.

Or maybe it's the other way around with the multiple renders, I haven't done this in a while. It's one or the other anyway.

EDIT: This requires that the collision geometry is more or less shaped like objects in the background image, so that they'll be correctly occluded. From your screenshot that isn't the case, so you'll need to fix that (eg. the collision mesh for the church has the pointy roof).
> 2 votes

# Answer
I'm sure someone else will address the technical aspects of exactly what you have in mind, but have you considered other approaches that are similar but not quite as extreme?

Your models look like they have a lot of fine details, and a lot of those could be baked to normal/displacement maps. That would leave you with simple geometry, but the type of "overlay" effect you're looking for, where the geometry appears much more detailed than it actually is.

Additionally, it removes the complexity of carefully synchronizing a static image with your 3D scene. You'll also be able to take advantage of Unity 5's new lighting system.

What you're describing is more feasible when you're using a tile-based system and each entity is pre-rendered and stored as an object on a tiled map, often itself covered in pre-rendered textures. Storing the entire map in a pre-rendered state in-memory isn't likely to be very efficient, and will probably be extremely limiting down the road.
> 1 votes

# Answer
# Z-buffering in a non-prerendered scene

I will use the term **pre-rendered background** for what you describe as a 2.5D scene, as I assume this is what you are looking for. Ideally, you would want your character to be able to walk around the environment, as if it were not rendered as a flat image. Your character should be able to move behind and in front of objects as he moves away from or towards the camera. The way "drawing only the front-most objects" works is by using a **Z-buffer** or **depth buffer**. When rendering a fragment, the depth of the fragment is written to this buffer. When a new fragment is drawn on the same onscreen position, the depth buffer is consulted to see whether this previous fragment was in front of the new one. If so, the new fragment is not drawn.

---

# Solution 1: Z-buffering for pre-rendered backgrounds

Ideally, you would want to exploit this mechanism for your pre-rendered backgrounds as well. Technically, you would do this by rendering two passes of your background: the actual **color data** and a **depth map**.

1. The **color pass** would be a simple color image. It should obviously be rendered with a camera identical to the one used in your game.
2. The **depth map** is a grayscale image that represents the distance of pixels to the camera. White pixels are very close to the camera's near plane, whereas black pixels are very far away from the camera (close to the far plane). Again, this map should be rendered with a camera identical to the one used in your game. Pay special attention to the near and far plane settings here! (You can do a Google search for *Depth Map* to see an example of these maps)

What you want to do in the draw phase of your game loop, is **render the background first**. This means, you'd write the **color image to the screen**. Additionally, you want to copy the **depth map to the depth buffer**, so that it is filled with the same depth data, as if it were truly rendered as 3D geometry. Note that after these steps, the screen and depth buffer will be in exactly the same state, as if you has truly drawn the state in 3D. You however can render as much detail as you want, as the color and depth data are pre-rendered, thus they don't have any real-time constraints. After that you can simply **draw all of your objects on top**. Objects that appear behind segments of your pre-rendered background will be occluded correctly if depth buffering is enabled.

Now, this is where you might run into a problem. I'm not very familiar with Unity myself, but I do not know if it is possible to write to the depth buffer directly. If it is not, you could try the following.

---

# Solution 2: Splitting of your pre-rendered background into depth planes

If direct write access to the z-buffer is impossible, you'll need to fill it with the correct depth data "the right way" (i.e. by rendering polygons). A solution would be to **split your backgrounds** up into **multiple layers of different depths**. Within a single layer all objects in your pre-rendered background will be considered to be at the same depth plane. For example, if you need to render a scene with a floor, a sky and two church buildings, you would use separate layers for:

1. The *ground + sky*: the backmost layer, as the player is always in front of these
2. The *backmost church*: an inbetween layer, so that the player can walk both behind and in front of it
3. The *frontmost church*: a more nearby layer, so that the player can walk inbetween both churches, as well as in front of the front-most one

Note that this is an **approximation**! For example, a wall that is not perfectly parallel with the camera should have a gradually increasing depth value as it comes closer to the camera. You will need to be clever in designing your backgrounds, and assigning a single depth value to every layer. This is how it is done in some older PS1 games however, so you should be able to use the same clever tricks.

To actually **render** your pre-rendered background, you will render all layers separately on full-screen quads. In your shader, make sure to **discard fragments** (using the discard keyword in GLSL, or something similar) if they are **fully transparant**. For example, in the depth plane of the frontmost church, you only want to render the church. The area around it should be fully transparant (think of it as a cut-out, or a PNG with a transparant background). By using the discard keyword, you make sure no data is written to the depth buffer. What you will end up with, after rendering all depth planes, is:

1. The color data of the pre-predered background background drawn onscreen
2. Your depth buffer filled with multiple depth planes

As in the first solution, you can now **draw your objects on top of this setup**. Fragments of objects that should appear behind background depth planes will be occluded correctly thanks to automated depth testing with the z-buffer!

---

To summarize, you will want to make use of the depth buffer (= z-buffer) to achieve your effect. If Unity allows you to write data to the depth buffer directly, pre-rendered depth maps are the way to go. They will provide pixel-perfect depth data, which will make your scene indistinguishable from a true 3D rendered scene. If you can't write data to the buffer directly, the classic approach using depth planes is the way to go. Segment your background into multiple planes, assign depths to them, and render them before drawing anything else.
> 1 votes

---
Tags: unity, 2.5d, overlay
---


title: Texture rotation inside a quad

text:
# Question
Title: Texture rotation inside a quad
How can I rotate a texture inside a quad without rotating the quad? Here's the code but I'm rotating the whole quad here.

```
glBindTexture(GL_TEXTURE_2D, texName5);
glMatrixMode(GL_TEXTURE);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);

    glPushMatrix();
            glTranslatef(12.8, 10, 10);
            glRotatef(rotateAd, 1, 0, 0);
            glBegin(GL_QUADS);
                    glNormal3f(1, 0, 0);
                    glTexCoord2f(0.0, 0.0); glVertex3f(0, -3,  -3);
                    glTexCoord2f(0.0, 1.0); glVertex3f(0, -3,  3);
                    glTexCoord2f(1.0, 0.0); glVertex3f(0, 3, 3);
                    glTexCoord2f(1.0, 1.0); glVertex3f(0, 3, -3);
            glEnd();
    glPopMatrix();

```

Thanks.

# Answer
> 11 votes
# Solution 1: Rotate your UVs in your vertex shader

The **vertex shader** is where per-vertex attributes can be modified before rendering. These values are then linearly interpolated to generate values for all fragments of your polygons. As a rotation of your your UVs is a linear transformation, you only need to recalculate the values in the vertices, and linear interpolation will take care of all intermediate fragment values. (Note that in case of a non-linear transform such as u\_new = sin( u\_old ), you'd have to calculate the new UVs for every fragment individually. In this case, the transformation belongs in your **fragment shader**.)

The **UVs** are a **2D coordinate pair** with values ranging from 0 to 1: \[0, 1\] x \[0, 1\]. (These values can sometimes be outside of the 0,1 range, in this case clamping, wrapping or repeating of the texture occurs, depending on how you specified your OpenGL texture hints)

In your vertex shader, you could **rotate your UVs** prior to the texture sampling to obtain a rotation. I'll assume you want to rotate the texture around its center coordinate (0.5, 0.5) (if the rotation origin varies from texture to texture, you could pass it as a 2f uniform). To enable animation, I'd suggest passing the angle as a 1f uniform.

You can calculate the new UVs using a **concatenation of three transforms**. You can't just do a single transform (a rotation) because this would rotate the texture around the (0, 0) point. Instead you want to use (0.5 ; 0.5) as your origin of rotation. The image by Jon at the bottom of this answer illustrates this. You can use these transformations:

1. **Translate** the UVs to the origin using **T\[-0.5, -0.5\]**. This means: *UVs = UVs + vec2(-0.5f, -0.5f);*
2. **Rotate** your UVs by the angle specified in the uniform using **R\[uniformAngle\]**. This can be done by multiplying with a 2x2 rotation matrix. This means: \*UVs = mat2(cos(uniformAngle), sin(uniformAngle), -sin(uniformAngle), cos(uniformAngle)) * UVs;\*
3. **Translate** the UVs back to the center of the texture using **T\[0.5, 0.5\]**. This means: *UVs = UVs + vec2(0.5f, 0.5f);*

By sampling your texture using these new UVs, a rotation will have been applied. You can increase your angle uniform over time to apply an animation to the rotation.

---

# Solution 2: Rotate your UVs on the CPU

If the **angle** of rotation **remains constant** throughout your program, it might be better to rotate the UVs on the **CPU**. This means you rotate them before rendering (thus while filling up your buffer objects). The procedure is exactly the same. You could use the GLM library to perform the matrix and vector operations for you. The procedure is the same as described above.

---

In summary, you will want to rotate your UVs to have the effect of a rotation on your texture. You can do this in two places. If the rotation changes over time, it is best to perform the calculation on your GPU, in the vertex shader. If the angle is constant, you can do the calculation on the CPU while filling up your vertex buffer, to prevent performing the same calculation every frame.

---
Tags: opengl, textures
---


title: OpenGL Vertex Array Object(VAO)

text:
# Question
Title: OpenGL Vertex Array Object(VAO)
I have drawn a triangle and a square using open gl and everything was fine.

I have then tried to draw the same triangle and square, while implementing VAO's and now I only get a white triangle - that is not the triangle I am attempting to draw. As far as I can see I am binding everything correctly in the onLoad method.

The square doesnt draw at all. Only the triangle which is not right.

If anyone could point out what I am missing or point me to somewhere I can understand this problem and fix (tutorial or other documentation) I would be very grateful.

Here is the code

```
    using Labs.Utility;
    using OpenTK;
    using OpenTK.Graphics;
    using OpenTK.Graphics.OpenGL;
    using System;

    namespace Labs.Lab2
    {
      class Lab2_1Window : GameWindow
      {
    private int[] mVertexArrayObjectIDs = new int[2];

    private int[] mTriangleVertexBufferObjectIDArray = new int[2];
    private int[] mSquareVertexBufferObjectIDArray = new int[2];
    private ShaderUtility mShader;

    public Lab2_1Window()
        : base(
            800, // Width
            600, // Height
            GraphicsMode.Default,
            "Lab 2_1 Linking to Shaders and VAOs",
            GameWindowFlags.Default,
            DisplayDevice.Default,
            3, // major
            3, // minor
            GraphicsContextFlags.ForwardCompatible
            )
    {
    }

    protected override void OnLoad(EventArgs e)
    {
        GL.ClearColor(Color4.CadetBlue);

        GL.Enable(EnableCap.DepthTest);

        #region Shader Loading Code

        mShader = new ShaderUtility(@"Lab2/Shaders/vLab21.vert", @"Lab2/Shaders/fSimple.frag");

        #endregion

        int vColourLocation = GL.GetAttribLocation(mShader.ShaderProgramID, "vColour");
        int vPositionLocation = GL.GetAttribLocation(mShader.ShaderProgramID, "vPosition");

        //square
        float[] sVertices = new float[]  { -0.2f, -0.4f, 0.2f, 0.0f, 1.0f, 0.2f,
                                           0.8f, -0.4f, 0.2f, 0.0f, 1.0f, 1.0f,
                                           0.8f, 0.6f, 0.2f, 0.0f, 1.0f, 0.4f,
                                           -0.2f, 0.6f, 0.2f, 0.0f, 1.0f, 0.0f};

        uint[] sIndices = new uint[] { 0, 1, 2,
        0,3,2};

        GL.GenVertexArrays(2, mVertexArrayObjectIDs);
        GL.BindVertexArray(mVertexArrayObjectIDs[1]);

        GL.GenBuffers(2, mSquareVertexBufferObjectIDArray);
        GL.BindBuffer(BufferTarget.ArrayBuffer, mSquareVertexBufferObjectIDArray[0]);
        GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(sVertices.Length * sizeof(float)), sVertices, BufferUsageHint.StaticDraw);

        int sSize;
        GL.GetBufferParameter(BufferTarget.ArrayBuffer, BufferParameterName.BufferSize, out sSize);

        if (sVertices.Length * sizeof(float) != sSize)
        {
            throw new ApplicationException("Vertex data not loaded onto graphics card correctly");
        }
        GL.BindBuffer(BufferTarget.ElementArrayBuffer, mSquareVertexBufferObjectIDArray[1]);
        GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(sIndices.Length * sizeof(int)), sIndices, BufferUsageHint.StaticDraw);

        GL.GetBufferParameter(BufferTarget.ElementArrayBuffer, BufferParameterName.BufferSize, out sSize);

        if (sIndices.Length * sizeof(int) != sSize)
        {
            throw new ApplicationException("Index data not loaded onto graphics card correctly");
        }

        GL.VertexAttribPointer(vPositionLocation, 3, VertexAttribPointerType.Float, false, 6 *
        sizeof(float), 0);
        GL.VertexAttribPointer(vColourLocation, 3, VertexAttribPointerType.Float, false, 6 *
        sizeof(float), 3 * sizeof(float));

        //GL.EnableVertexAttribArray(vColourLocation);
        //GL.EnableVertexAttribArray(vPositionLocation);

        //triangle
        float[] tVertices = new float[] { -0.8f, 0.8f, 0.4f, 1.0f, 0.0f, 0.6f,
                                          -0.6f, -0.4f, 0.4f, -0.2f, 0.5f, 1.0f,
                                          0.2f, 0.2f, 0.4f, -1.0f, 0.0f, 1.0f};

        uint[] tIndices = new uint[] { 0, 1, 2 };

        //GL.GenVertexArrays(2, mVertexArrayObjectIDs);
        GL.BindVertexArray(mVertexArrayObjectIDs[0]);

        GL.GenBuffers(2, mTriangleVertexBufferObjectIDArray);

        GL.BindBuffer(BufferTarget.ArrayBuffer, mTriangleVertexBufferObjectIDArray[0]);
        GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(tVertices.Length * sizeof(float)), tVertices, BufferUsageHint.StaticDraw);

        int size;
        GL.GetBufferParameter(BufferTarget.ArrayBuffer, BufferParameterName.BufferSize, out size);

        if (tVertices.Length * sizeof(float) != size)
        {
            throw new ApplicationException("Vertex data not loaded onto graphics card correctly");
        }
        GL.BindBuffer(BufferTarget.ElementArrayBuffer, mTriangleVertexBufferObjectIDArray[1]);

        GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(tIndices.Length * sizeof(int)), tIndices, BufferUsageHint.StaticDraw);

        GL.GetBufferParameter(BufferTarget.ElementArrayBuffer, BufferParameterName.BufferSize, out size);

        if (tIndices.Length * sizeof(int) != size)
        {
            throw new ApplicationException("Index data not loaded onto graphics card correctly");
        }

        GL.VertexAttribPointer(vPositionLocation, 3, VertexAttribPointerType.Float, false, 6 *
        sizeof(float), 0);
        GL.VertexAttribPointer(vColourLocation, 3, VertexAttribPointerType.Float, false, 6 *
        sizeof(float), 3 * sizeof(float));

        GL.EnableVertexAttribArray(vColourLocation);
        GL.EnableVertexAttribArray(vPositionLocation);

        base.OnLoad(e);
    }
    protected override void OnRenderFrame(FrameEventArgs e)
    {
        base.OnRenderFrame(e);

        GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

        GL.BindVertexArray(mVertexArrayObjectIDs[1]);
        GL.DrawElements(PrimitiveType.Triangles, 6, DrawElementsType.UnsignedInt, 0);

        GL.BindVertexArray(mVertexArrayObjectIDs[0]);
        GL.DrawElements(PrimitiveType.Triangles, 3, DrawElementsType.UnsignedInt, 0);

        GL.BindVertexArray(0);
        this.SwapBuffers();
    }

    protected override void OnUnload(EventArgs e)
    {
        base.OnUnload(e);
        GL.BindVertexArray(0);
        GL.DeleteVertexArrays(2, mVertexArrayObjectIDs);
        GL.DeleteBuffers(2, mTriangleVertexBufferObjectIDArray);
        GL.DeleteBuffers(2, mSquareVertexBufferObjectIDArray);
        GL.UseProgram(0);
        mShader.Delete();
    }
}

```

}

EDIT:

# Answer
I was not using the shader after I loaded it.

Added GL.UseProgram(mShader.ShaderProgramID);

After shader loading code.
> 0 votes

# Answer
You draw with

```
GL.BindVertexArray(mVertexArrayObjectIDs[1]);
GL.DrawElements(PrimitiveType.TriangleFan, 4, DrawElementsType.UnsignedInt, 0);

```

however the indices you use are for `PrimitiveType.Triangles`

Replace that with

```
GL.BindVertexArray(mVertexArrayObjectIDs[1]);
GL.DrawElements(PrimitiveType.Triangles, 6, DrawElementsType.UnsignedInt, 0);

```
> 1 votes

---
Tags: opengl
---


# Question
Title: Event Driven Behavior Tree: deterministic traversal order with parallel
I've studied several articles and listen some talks about behavior trees (mostly the resources available on AIGameDev by Alex J. Champandard).

I'm particularly interested on event driven behavior trees, but I have still some doubts on how to implement them correctly using a scheduler.

Just a quick recap:

**Standard Behavior Tree**

* Each execution tick the tree is traversed from the root in depth-first order
* The execution order is implicitly expressed by the tree structure. So in the case of behaviors parented to a `parallel` node, even if both children are executed during the same traversing, the first leaf is always evaluated first.

**Event Driven BT**

* During the first traversal the nodes (tasks) are enqueued using a scheduler which is responsible for updating only running ones every update
* The first traversal implicitly produce a depth-first ordered queue in the scheduler
* Non leaf nodes stays suspended mostly of the time. When a leaf node terminate(either with success or fail status) the parent (observer) is waked up allowing the tree traversing to continue and new tasks will be enqueued in the scheduler
* Without parallel nodes in the tree there will be up to 1 task running in the scheduler
* Without parallel nodes, the tasks in the queue(excluding dynamic priority implementation) will be always ordered in a depth-first order (is this right?)

Now, from what is my understanding of a possible implementation, there are 2 requirements I think must be respected(I'm not sure though):

Now, some requirements I think needs to be guaranteed by a correct implementation are:

1. The result of the traversing should be independent from which implementation strategy is used.
2. The traversing result must be **deterministic**.

I'm struggling trying to guarantee both in the case of parallel nodes. Here's an example:

```
Parallel_1
-->Sequence_1
---->leaf_A
---->leaf_B
-->leaf_C

```

Considering a `FIFO` policy of the scheduler, before `leaf_A` node terminates the tasks in the scheduler are:

```
P1(suspended),S1(suspended),leaf_A(running),leaf_C(running)

```

When `leaf_A` terminate `leaf_B` will be scheduled (at the end of the queue), so the queue will become:

```
P1(suspended),S1(suspended),leaf_C(running),leaf_B(running)

```

In this case `leaf_B` will be executed after `leaf_C` at every update, meanwhile with a non event-driven traversing from the root node, the `leaf_B` will always be evaluated before `leaf_A`.

So I have a couple of question:

1. do I have understand correctly how event driven BT work?
2. How can I guarantee the depth first order is respected with such an implementation?
3. is this a common issue or am I missing something?

# Answer
Actually the order of execution in my question was wrong. **When a task terminates, if it immediately awake its parent pushing it in front of the queue the depth first order is respected**.

Here's how the queue status is supposed to be just after leaf\_A task terminates:

> S1(running), P1(suspended),leaf\_C(running) | \[leaf\_A(completed)\]

When `leaf_A` terminates it must awake immediately its parent (`S1`) pushing it in front of the `FIFO` queue, so it will be executed first.

When it gets executed, will be suspended and it's next child task is scheduled (`leaf_B`) in front of the queue so, it will be executed before `leaf_C` as supposed to be:

> leaf\_B(running), P1(suspended),leaf\_C(running), | S1(suspended)
> 0 votes

# Answer
I'm not sure that I'd call what you describe Event Driven BTs, but then again, driving a BT fully with events is no small feat.

Addressing your specific issue, you're right. If you have a unique scheduler you'll run into ordering issues as you've shown. The answer is to have hierarchical schedulers, to support parallel nodes.

In your example, you'd have three schedulers: one for the root of the tree, one for each of the branches of the parallel node. Each scheduler runs sequentially as you'd expect, only instead of queuing just nodes they can queue other schedulers.

```
Root: P1(suspended),SCH1(running),SCH2(running)
SCH1: S1(suspended),leaf_A(running)
SCH2: leaf_C(running)

```

So now when leaf\_A transitions into leaf\_B, the order will be maintained.
> 0 votes

---
Tags: ai, events, behavior
---


# Question
Title: 2D planetary system simulation- how to improve gravity model? How to control simulation speed?
I'm making a simple planetary system simulator. I've run into some problems with physics model and simulation speed and I'd like to learn how to fix them.

My main class is Body:

```
public abstract class Body {

private double x, y; // position
private double w, h; // dimensions for drawing
private double vx = 0, vy = 0; //velocities along x, y axes
private double ax = 0, ay = 0; // accelerations along x, y axes
private double mass = 1;        //default = 1
private boolean stationary = false; //stationary body is centered during simulation

...
}

```

Then, in this class, the method I'm using to calculate the force of gravity. I decided to have another body as a parameter, so when I call the method it updates both of the bodies. If that's not the best way to do it, please tell me. I also know that using "this" inside a public method is not necessary, but it makes the code more clear for me.

```
public void interact(Body b2) {
    double x = calculateDistX(b2);
    double y = calculateDistY(b2);
    double r = calculateDistance(x, y);

    double f = (this.getMass() * b2.getMass()) / Math.pow(r, 2); // gravitational
                                                                    // force

    double fx = f * (x / r); // x component of the force - f times cosine of
                                // the angle
    double fy = f * (y / r); // x component of the force - f times sine of
                                // the angle

    /* calculate accelerations for both bodies, set vector orientation */
    if (b2.getX() > this.getX()) {
        this.setAx(fx / this.getMass());
        b2.setAx(-fx / b2.getMass());
    } else {
        this.setAx(-fx / this.getMass());
        b2.setAx(fx / b2.getMass());
    }

    if (b2.getY() > this.getY()) {
        this.setAy(fy / this.getMass());
        b2.setAy(-fy / b2.getMass());
    } else {
        this.setAy(-fy / this.getMass());
        b2.setAy(fy / b2.getMass());
    }

    /* calculate velocities for both bodies */
    this.setVx(this.getVx() + this.getAx());
    this.setVy(this.getVy() + this.getAy());

    b2.setVx(b2.getVx() + b2.getAx());
    b2.setVy(b2.getVy() + b2.getAy());

    /* calculate positions for both bodies */
    this.setX(this.getX() + this.getVx());
    this.setY(this.getY() + this.getVy());

    b2.setX(b2.getX() + b2.getVx());
    b2.setY(b2.getY() + b2.getVy());
}

```

Now, when I run the simulation it tends to blow up when bodies get too close. I will try to implement the Runge-Kutta or Verlet algorithm in the interact() method to change this, but how do I implement timestep? Should there be some timer that counts time and is used to calculate derivatives? Right now I'm using a Timer in my drawing method:

```
class DrawingPanel extends JPanel {
DrawingPanel() {
    int step = 15; // milliseconds
    ActionListener taskPerformer = new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            repaint();
            }
    };
    new Timer(step, taskPerformer).start();
    Body b0 = new Star();
    addBody(b0);
    Body b1 = new Planet();
    addBody(b1);
    Body b2 = new Planet();
    addBody(b2);
}

List<Body> bodies = new ArrayList<>();

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    bodies.get(2).interact(bodies.get(1));
    bodies.get(0).interact(bodies.get(1));
    bodies.get(0).interact(bodies.get(2));

    for (Body b : bodies) {
        f.draw(b);
    }
}
public void addBody(Body b) {
    bodies.add(b);
}
}

```

I feel like calling the interact() method in my paintComponent() method is not the right solution, but I don't know how to do it. Also, how to make the simulation slower? Right now changing the "step" to bigger value slows the simulation down, but it ends up being just low FPS, because it's just the separation between two drawing events. How should I implement the timer to control the simulation and preserve its smoothness?

# Answer
Edit: Moved from comments; didn't originally feel like a complete answer. May not be still...

**Time-step:**
A typical problem with collisions is when bodies move *beyond* each other, instantly, in the same frame; i.e. "teleport". No collision is detected because the objects moved past, not through, the other. Floating-point error is unavoidable and will always cause your model to deviate from "ideal".

It's important that the centers of bodies not be "teleported" into the center of other bodies during Update(). Calculating the pull due to G, between two "planets" whose volumes are overlapping, will result in Sun-like values, because they are impossibly close. You need to keep things like that in mind when selecting a time-step for the "universe".

Adding additional logic and/or dimensions to the tree-like structure described below, can give you the added flexibility to run physics in more, smaller, chunks on an object-by-object, or case-by-case, basis. Two near-and-heavy objects should take smaller steps until they pass the "danger-zone". For example, a quick check of diminishing distances between near-and-heavy bodies that suddenly start increasing is a probable indicator of a chance-of-collision expiring. They were getting closer, and now they aren't, so there's no more collisions to check between them for awhile. To state the obvious, objects can only collide when they are approaching each other, and the tree structure presented will contain references to enough information to detect this hint and re-optimize on the fly.

Monitor how long the "universe" is taking to Physics() and reduce the overall aggressiveness/LOD, if necessary, to catch up and/or stay caught-up on laggy machines.

**Barycenters:**
Before you go much further, please do some research on barycenters. They will help you simplify many of the calculations. Specifically, the "Center of gravity" section. Also, toward the bottom under "Astronomy", there is an animation showing a barycenter.

The resulting barycenter class will very-loosely perform the function of spatial partitioning. The barycenter contains everything needed to calculate gravitational attraction between all of its' children. To calculate the force on an individual child, you just exclude the child from the pre-computed total, then calculate gravity as usual.

You can also test objects outside of the barycenter against the entire barycenter, including other barycenters. In this way, entire "galaxies" can affect each other realistically, without having to iterate every particle in both systems.

The tree-ish-like functionality has added benefits such as a barycenter being a convenient "bucket" for the bodies within it. They collect Render(), Update(), Gravity(), etc. into logically partitioned chunks, somewhat like a quad-tree. The player is in a ship (barycenter), which is in a solar system (bc), which is in a... Testing any/all against each other becomes trivial.

> How to implement the Barycenter class effectively? There can be many of them, i.e. in star + planet and moon system, there will be one in the planet-moon system and one between star and orbiting planet. Some of the barycenters will move during the simulation. How do I calculate them correctly?

For a minimal number of bodies, you just need the one. For an example "object" (a ship), you could calculate the pull from the moon and affect the ship. Then, calculate the planet, and affect the ship. Then, the star, and affect the ship. Instead, pre-calculate the entire system as one point-mass (barycenter). Subtract the ship's influence from the point-mass, then calculate gravity against the entire rest of the system in one calculation. After an entire frame of gravity has been Update()'d, the barycenter will update itself, using all of the new (MG/D^2)'s.

Using the barycenter, the end-result will be the same force vector you would calculate any other way. It will point toward the nearest-and-heaviest body, weighted by MG/D^2.

You can ask it "whats the pull from everything except X" then apply that directly to X. You get a precise, one-shot answer, regardless of what is being tested, in-, or out-side of the system. When you start needing to test against a second star, you start needing a "quadrant/universe barycenter". The effect of a distant star on a ship near the earth is negligible, but the distant star does pull on the barycenter of Sol. Technically, the distant star pulls on every object within Sol, individually; but we tend to behave as a unit.

**Real-world:**
The center of our solar system's barycenter is nearer to the *surface* of the Sun, than its' center. The vector between those two points represents the pull *on* the sun, from everything *except* the sun.
> 1 votes

---
Tags: java
---


# Question
Title: In Unity, why is adding a Vector2 and a Vector3 ambiguous but assigning isn't?
Given the following two vectors:

```
Vector3 v3 = Vector3.one;
Vector2 v2 = Vector2.one;

```

This line is ambiguous:

```
v3 += v2; // Unity reports dimension ambiguity

```

whilst this assignment isn't:

```
v3 = v2; // Unity assigns despite different dimensions

```

Why is this?

# Answer
> 12 votes
Full issue message:

> error CS0121: The call is ambiguous between the following methods or properties: `UnityEngine.Vector2.operator +(UnityEngine.Vector2, UnityEngine.Vector2)' and`UnityEngine.Vector3.operator +(UnityEngine.Vector3, UnityEngine.Vector3)'

Unity provided a way to implicitly convert a `Vector3` to a `Vector2` and vice-versa. This causes an ambiguity in your case because both + operators can be applied.

Cast your `Vector2` to a `Vector3` explicitly in that operation, so that the compiler knows to use `UnityEngine.Vector3.operator +(UnityEngine.Vector3, UnityEngine.Vector3)`.

If you're curious, Microsoft's docs for that specific error are here.

---

Edit after your edit:

`Vec3 += Vec2` is ambiguous for the same reason described above. Imagine `Vec3 += Vec2` being in fact `Vec3 = Vec3 + Vec2`. `Vec3 + Vec2` can yield both `Vector2` and `Vector3` as answer due to implicit conversions, that's why you have to specify what you want.

`Vec3 = Vec2` is not ambiguous because Vec2 is implicitly converted to a `Vector3` and then assigned to the initial Vec3. So the whole operation is really `Vector3 = Vector3` without you having to cast Vec2 to a `Vector3` manually.

# Answer
> 3 votes
Let me rename the vars (for clarity):

```
Vector3 pos3d = new Vector3 (1f, 2f, 3f);
Vector2 pos2d = new Vector2 (1f, 2f);

```

## Answer

It is because of the section `pos3d + pos2d` of the line. This part is really ambiguous while the `+=` is not. Let me clarify why one and why the other.

## Analysis 1

In this line

```
transform.position = pos3d + pos2d;

```

the compiler first tries to evaluate the expression `pos3d + pos2d` before proceeding, regardless of where the result is going to be placed.

To do so, the system first tries to find any public static function that adds a Vector3 plus a Vector2, for example this possible signature:

```
public static Vector3 operator +(Vector3 a, Vector2 b);

```

or for example this possible signature:

```
public static Vector2 operator +(Vector3 a, Vector2 b);

```

Nevertheless there is not any of those signatures in the API so the compiler tries to "cast" parameters to known signatures.

Then the compiler finds those two potential signatures:

```
public static Vector3 operator +(Vector3 a, Vector3 b);
public static Vector2 operator +(Vector2 a, Vector2 b);

```

These are documented here: http://docs.unity3d.com/ScriptReference/Vector3-operator\_add.html and here: http://docs.unity3d.com/ScriptReference/Vector2-operator\_add.html

So there are two possibilities:

So as both castings are possible, pos2d can be casted to a Vector3 and pos3d is castabale into a Vector2, the compiler then finds to possible ways to compile the same source code (provided automatic hidden castings are in place).

It is either possible to cast pos3d into Vector2 and proceed with the second signature, or either cast pos2d into Vector3 and proceed with the first signature.

As the expression `pos3d + pos2d` is evaluated first, before taking in consideration "where the result will be applied" then the compiler does not know what cast would you -as coder- like it to perform.

If you want to move towards 3D, you can write this:

```
transform.position = pos3d + ( Vector3 )pos2d;

```

and the problem is gone, as now it is clear: first move pos2d into another object of type Vector3, then do the sum of Vector3 + Vector3. Provided that there is this static signature

```
public static Vector3 operator +(Vector3 a, Vector3 b);

```

available, that one will be used with no ambiguity at all.

## Analysis 2

On the other hand, when you do

```
transform.position = pos3d;
transform.position += pos2d;

```

there is no ambiguity: The first line assigns a Vector3 into a Vector3 (no doubts).

The second line is equivalent to

```
transform.position = transform.position + pos2d;

```

with the particularity the transform.position is only evaluated once, and therefore the type is taken in consideration, as you can see in this Microsoft page about the `+=` operator:

https://msdn.microsoft.com/en-us/library/sa7629ew.aspx

It in addition says "The += operator cannot be overloaded directly, but user-defined types can overload the + operator (see operator)." so we should think the `Vector3`'s `+=` operator acts as described by microsoft where it says:

> ```
> x += y
>
> ```
>
> is equivalent to
>
> ```
> x = x + y
>
> ```
>
> except that x is only evaluated once. The meaning of the + operator depends on the types of x and y (addition for numeric operands, concatenation for string operands, and so forth).

so we can be sure the second approach invokes the + operand of the `Vector3` class, which has the signature:

```
public static Vector3 operator +(Vector3 a, Vector3 b);

```

so there is not any other way to achieve this than converting the pos2d into a Vector3 thanks to an implicit hidden cast that cannot be of any other form.

Hope to help!!

---

Edit

In `Unity 5.0.1f1 Personal` with `MonoDevelop-Unit 4.0.1`, as Alex M. says, the lines:

```
transform.position = pos3d;
transform.position += pos2d;

```

still cast the error `"Assets/Scripts/CubeScript.cs(15,27): error CS0121: The call is ambiguous between the following methods or properties: 'UnityEngine.Vector2.operator +(UnityEngine.Vector2, UnityEngine.Vector2)' and 'UnityEngine.Vector3.operator +(UnityEngine.Vector3, UnityEngine.Vector3)'"`

so really the += is using both signatures

```
public static Vector3 operator +(Vector3 a, Vector3 b);
public static Vector2 operator +(Vector2 a, Vector2 b);

```

regardless of the fact of already knowing "where" the result shall be placed (I guess because outputting a Vector2 is castable to the destination (Vector3) and if that cast was not possible probably, maybe, the compiler would choose the one with the proper output type).

Thanks for the point Alex M.

---
Tags: c#, unity, 2d, 3d, vector
---


title: Pause in Seconds and resume in unity

text:
# Question
Title: Pause in Seconds and resume in unity
I want to pause 15 seconds then resume without any input when an object is collision other object this is my code but not working. Thank you

```
 void Start(){
    Eifftower = GameObject.FindGameObjectWithTag ("eiffeldespration");
    Eifftower.renderer.enabled = false;
    Time.timeScale = 1;
}

IEnumerator wait() {
    yield return new WaitForSeconds(15f);
    Eifftower.renderer.enabled = false;
    Time.timeScale = 1;
    Debug.Log("test");
}

void OnTriggerEnter2D(Collider2D collisionObject){
            //remove the game object
            if (collisionObject.tag == "Franch" ) {
            Eifftower.renderer.enabled = true;
            Time.timeScale = 1;
            StartCoroutine(test1());
            }
    }

```

# Answer
> 2 votes
The WaitForSeconds() command does not run/return when Time.timeScale is equal to 0 because it relies on Time.timeScale. I'm assuming because you mention pausing, you set the Time.TimeScale to 0, then call "yield return new WaitForSeconds(15f)" and unpause with Time.timeScale = 1.

You can use Unity's Time.unscaledDeltaTime, which is how much real time has passed since the last frame.

Now in your code:

```
float waitCounter = 0;
IEnumerator wait()
{
     waitCounter = 0;
     while (waitCounter < 15f)
     {
         waitCounter += Time.unscaledDeltaTime;

         //Yield until the next frame
         yield return null;
     }

     Eifftower.renderer.enabled = false;
     Time.timeScale = 1;
     Debug.Log("test");

}

```

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


# Question
Title: Unity Remote 4 on Galaxy S5 won't connect to Unity 5
I'm having some trouble connecting Unity Remote 4 to Unity 5. I'm using a Samsung Galaxy S5. I've searched a bit and the other solutions with other phones aren't working for me.

**What I've tried so far:**

I installed the Android SDK by using Android Studio. I'm not sure if that's part of the problem but either way. I installed the Google USB Driver, the 5.0 (API 21) and 5.1 (API 22) SDKs. My phone is running on Android 5.0. All the SDK tools (Platform tools and build tools) are installed. I set USB Debugging, Stay Awake and Allow Mock Locations in the Developer Options on my phone. I set the Android SDK path in Unity (Program Files/Android/android-sdk) I set, in the Unity Editor Settings, Device to Any Android Device. I made sure my computer sees my phone, which it does. And I tried to open Unity first then the Unity Remote and Unity Remote first then Unity Engine. And set Android as my Platform in Build Settings. And I've tried plugging my phone in a USB 2.0 and a USB 3.0.

All that and each time I press the play button nothing happens in the phone. I have no idea what I'm doing wrong. I tried using Unity 4 and Unity 5.

If my OS is a factor, I'm using Windows 7 Ultimate, 64-bit.

**If the following information is needed:**

Hardware Version: G900P.04

Model number: SM-G900P

Android version: 5.0

Kernal version: 3.4.0

If any other information is needed I will provide it. Anyone have a solution to my problem? Thank you.

# Answer
Oh yeah, the unity remote app can be a pain in the ass. It seems like you set up everything correctly. To see if everything works fine just try to build and run the app for your phone... if it can be built and pushed to your phone everything should be alright.

If you can push the app through unity on your phone I hopefully have a solution for you, which worked for me every time I had problems with the remote app: 1.) Plug in the phone to your computer 2.) In Unity go to Edit-\>Editor and switch the Unity Remote Device to "None" 3.) Restart Unity 4.) Start the remote app on your phone 5.) Once again in Unity go to Edit-\>Editor and set the Unity Remote Device back to "Any Android Device" 6.) Press the play button or control+p and hope for the best
> 1 votes

---
Tags: unity, android
---


# Question
Title: How to draw to a surface, then draw that surface to the screen
i have a 2D MonoGame Game (using DirectX), that was originally an XNA game. It involves prerendered shadows (they are Texture2Ds drawn with SpriteBatch.draw). Right now the shadows are being drawn with an alpha value, so overlapping shadows appear darker. This is **NOT** what i want. Overlapping shadows should be the same shade of black.

So what i want to do is draw all these shadows to a surface, such that the shadows are completely black (alpha == 255), and the surface background is completely transparent (alpha == 0), and then take that surface and draw it to the screen using Color.White\*0.25f to give alpha to the shadows at the end.

I'm not sure how to switch rendering targets, or whatever the terminology is, and go about this. Can someone help?

**what ive tried so far:**

```
GraphicsDevice.SetRenderTarget(RENTAR); // RENTAR is the name of my RenderTarget2D
GraphicsDevice.DepthStencilState = new DepthStencilState() { DepthBufferEnable = true }; // not really sure what this does but it was in examples
GraphicsDevice.Clear(Color.White*0.0f); // i clear it with a totally transparent white background, in other words, white with alpha == 0

// now draw shadows normally, but instead of Color.White*0.25f, i use Color.White so that the black shadows are drawn completely black, with no alpha

GraphicsDevice.SetRenderTarget(null); // switch render target back to the screen
SpriteBatch.Draw(RENTAR, new Rectangle(0, 0, 800, 600), Color.White*0.25f); // see i added the "*0.25f" to try to draw this texture with alpha, but it comes out totally blank

```

So all of this works except that the shadows end up being completely black. I want them completely black in the RenderTarget, so that they dont overlap with any darker shades, and then i want to draw the final RenderTarget on the screen with an alpha of 0.25f, hence "Color.White\*0.25f" in the final spritebatch draw. But its as if that 0.25f doesn't exit.

# Answer
> 1 votes
In general, please refer to Reimer's for everything XNA.

**Stencil texture:**
To avoid duplicating, here's a link to the specific tutorial regarding render targets.

**Stencil buffer:**
You intend on using an off-screen rendertarget as a stencil; why not use the stencil, instead? With the stencil active and always incrementing, draw the shadows, but don't output a color. After the shadows are rendered, the stencil will be filled with the number of times each pixel was shadowed. Reset the stencil to affect only pixels whose stencil value is \>0 (shadowed 1 or more times). Activate the shadow-shader and draw a fullscreen quad using SpriteBatch.

# Answer
> 1 votes
Are you sure that Color.White\*0.25f is the right way to go? I would have used

```
SpriteBatch.Draw(RENTAR, new Rectangle(0, 0, 800, 600), new color(255,255,255, 64));

```

I think it's the only way to ensure that you're getting the transparency level in to the draw color.

---
Tags: xna, monogame
---


# Question
Title: What does the number in TextMesh.lineSpacing refer to?
I have a TextMesh with some text, and mutliple lines.

The 4 examples have these settings:

1. lineSpacing = 220, characterSize = 10
2. lineSpacing = 220, characterSize = 25
3. lineSpacing = 220, characterSize = 30
4. lineSpacing = 110, characterSize = 25

I don't understand what the lineSpacing number signifies. It's not pixels. As the relative spacing between lines stays the same with different character sizes, it doesn't seem to be proportional to characterSize either.

# Answer
My bitmap font has glyphs that are 22 pixels high. So it looks like the `lineSpacing` property needs 10x the pixel height of the glyphs to have no gap between lines, and no overlap. I don't know why, but empirically this appears to work.

Seems related to this question:

http://answers.unity3d.com/questions/932474/unitys-textmesh-fontlineheight-and-the-number-975f.html

This is because when creating a Font, lineSpacing of the Font object defaults to 0.1:

But this property is not available except through the editor, apparently. \>:(
> 0 votes

# Answer
It's the space between the lines, it's not relative to size or font, it's an absolute value. This should do.

Edit : I apologize for not understanding your question. Line spacing is in world units, it should snap to a pixel as long as its a multiple of 1 / pixels per meter.
> -1 votes

---
Tags: unity
---


# Question
Title: Why don't I have some settings in GameMaker?
I recently bought GameMaker for Mac, however upon watching a few GameMaker videos I've realized that I don't have all options available.

For example, in "Sound Properties" in other videos people have the option to change the volume and the pan, whereas I don't.

Does anyone know why this is happening?

# Answer
You need to enable "advanced mode" in GameMaker. From the "File" menu, choose the "Advanced Mode" option.
> 1 votes

---
Tags: game-maker
---


title: Unity Issue with Vector3 and Transform

text:
# Question
Title: Unity Issue with Vector3 and Transform
I am currently running into this error:

> Cannot implicitly convert type `UnityEngine.Vector3` to `Unity.Engine.Transform`

I am not sure on how to fix this issue because, here's the code where the issue is occurring.

```
target = pickedNumber.transform.position;
ball.transform.position = Vector3.MoveTowards(transform.position, target.position, step);

```

Here's the `for` loop that contains the above snippet:

```
float waitTime = 8;
    float step = speed * Time.deltaTime * 2;

    yield return new WaitForSeconds (waitTime);

    for (int i = 0; i <= 19; i++) {
        //Finding Game Objects
        numbers = GameObject.FindGameObjectsWithTag ("num");
        ball = GameObject.FindGameObjectWithTag ("ball");

        //Picking the random cube
        index = Random.Range (0, numbers.Length);
        pickedNumber = numbers [index];

        //Moving ball to cube
        target = pickedNumber.transform.position;
        ball.transform.position = Vector3.MoveTowards(transform.position, target.position, step);

        //Pause here
        yield return new WaitForSeconds (waitTime);

        //Ball Returns to position
        ball.transform.position = new Vector3 (0, 0, 0);
    }

```

# Answer
> 1 votes
If *target* is a transform, you want it to be `target = pickedNumber.transform;`, (no transform.**position**).

~~If *target* is a Vector3, you want the next line to be `ball.transform.position = Vector3.MoveTowards(transform.position, target, step);`, (no target.**position**).~~

I assume it's the first one, because of the wording of the error, but the second one is to show that it could be fixed another way.

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


# Question
Title: How do I rotate a cube around an axis, relative to the camera view?
I want to be able to rotate a cube, either by

* dragging *vertically* to rotate it around the *Y-axis*, or
* dragging *horizontally* to rotate it around the *X-axis*.

However, when the camera is rotated 90 degrees or more, these directions become wrong relative to the view screen. How can make rotating ‘up’ always mean ‘up’ relative to the camera view?

---

Here's a picture explaining the situation:

# Answer
# The camera up-vector

A property of the camera you could use to solve this problem is the **up-vector**. This vector indicates which direction in 3D space should correspond with the (upward) vertical axis of your screen. Usually, cameras will use the positive y-axis for this, thus: (0, 1, 0).

---

# The scalar product of two vectors

The **scalar product** of two 3D vectors (x1, y1, z1) and (x2, y2, z2) is defined as:

```
(x1 . x2) + (y1 . y2) + (z1 . z2)

```

It has the property that it will be **zero** for **two perpendicular vectors** and **one** for **two parallel vectors**. Note that this last property assumes your vectors are normalized (=they are unit length).

For **intermediate angles**, the value of the scalar product **increases monotonically** with increasing angle between the vectors.

---

# Solution: Finding the "most vertical" axis using the scalar product

You can use the above bits of information to solve your problem. In essence you have two local axes of your cube (the X-axis and the Y-axis) and you want to figure out **which one aligns most** with the **vertical axis of your screen**. The other axis will naturally align more with the horizontal axis of your screen.

The up-vector of your camera corresponds with this vertical axis. Knowing that the scalar product of two vectors is bigger, the more they align in direction, you can do the following:

1. **Normalize** the local **X-axis** and **Y-axis** vectors of your cube
2. Calculate the **scalar product** of your up-vector with both these normalized axis vectors
3. If the **scalar product** with the **X-axis is bigger**, bind horizontal mouse movement to its rotation and bind vertical mouse movement to the Y-axis rotation. If the scalar product with the **Y-axis is bigger**, do the inverse.

---

In summary, you can calculate the scalar product of the camera up-vector with the normalized X- and Y-axis vectors of the cube to find which axis best aligns with the vertical axis of your screen.
> 1 votes

---
Tags: unity, camera, rotation, vector
---


title: box2d not centered in sprite

text:
# Question
Title: box2d not centered in sprite
I am trying to create a bounding box for my sprite using box2d, but the box is being created at the wrong spot. I followed a tutorial on the wiki using this code

```
    BodyDef bodyDef1 = new BodyDef();
    bodyDef1.type = BodyDef.BodyType.DynamicBody;
    bodyDef1.position.set(player.getX(), player.getY());
    playerBody = world.createBody(bodyDef1);
    PolygonShape square = new PolygonShape();
    square.setAsBox(player.getWidth() / 2, player.getHeight() / 2);
    FixtureDef fixtureDef1 = new FixtureDef();
    fixtureDef1.shape = square;
    fixtureDef1.density = 0.1f;

```

Player is a just the sprite that I am trying to create the box around.

# Answer
> 2 votes
The position of a Box2D body is defined as its center. So if you set the body's position to the lower left corner of the Sprite, then it will be displayed as you showed in the image.

What you need to do is set the Body's position to the center of the Sprite like so:

```
bodyDef1.position.set(player.getX() + player.getWidth() / 2, player.getY() + player.getHeight() / 2);

```

---
Tags: libgdx, box2d
---


# Question
Title: In Unity, what does the camera script's "Behaviour missing" error mean?
I started in Unity few days ago and made a cube with a tank control style. Now I'd like to create controls similar to 3D fighting games (Gunz, Blade Symphony, …): Control body direction with the mouse and walk with WASD.

However, the Camera is giving me a error called "Behaviour missing" each time I try, with all the cameras scripts I saw. I think that is a error with tagging the character movement in the camera, but I don't know how to do that.

What might be the problem?

# Answer
> 2 votes
It's not wrong with the camera or with the content of any script you might have. This error occurs when you have a script attached to a gameobject and you deleted, moved or renamed it outside of unity. Unity can't find the related script for the MonoBehaviour component.

If you want to rename or move a script do it always in Unity. To solve your error, just find the component that references this missing script and drag the script that you might have moved onto the component.

---
Tags: unity, camera, control
---


title: Creating a Timer in C# Unity

text:
# Question
Title: Creating a Timer in C# Unity
In my game I have watch video earn coins system, now I want to program a delay so the user cant watch the video every 5 seconds, for example I want to let him watch every 6 hours, but I'm not sure how can I do that, how can I program a timer that will count down even if the app is closed or how does this kind of timer work, I mean everyone saw this in many games where they count down days or hours until some gift or something. Any help is appreciated.

# Answer
There is few ways to do this. Store information of last gifting time to:

1. Local device ( pc, phone, table or what ever is the gaming device)
2. Cloud service. However, this is harder method and requires the actual service hosted at somewhere in internet.

---

File writing method is quite simple to do.

1. Store time to variable
2. When game exits, write time to textfile
3. When game starts again, read that file and get the time
4. Do what you wanna do with the time.

---

```
string text = "This is just example text";
// WriteAllText creates a file, writes the specified string to the file,
// and then closes the file.
System.IO.File.WriteAllText(@"C:\Users\Public\TestFolder\WriteText.txt", text);

// Read the file as one string.
string text = System.IO.File.ReadAllText(@"C:\Users\Public\TestFolder\WriteText.txt");

```

---

Now, if this is very important to keep player doing this over and over again, you cannot store that time as a plain text. You have to use something to scramble it.
> 1 votes

# Answer
Below code will do what you want.

You will need to save and load the value of "DateTime lastPlayDate" between sessions.

```
using System;

public class GameManager : MonoBehaviour {

    DateTime lastPlayDate;

    void Start()
    {
        lastPlayDate = DateTime.Now;
    }

    void Update()
    {
        DateTime currentTime = DateTime.Now;
        TimeSpan timePassed = currentTime - Convert.ToDateTime(lastPlayDate);
        if (timePassed.TotalDays > 0 timePassed.TotalHours > 0 && timePassed.TotalMinutes > 1)
        {
            Debug.Log("Well that went quick...");
        }
    }
}

```
> 0 votes

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


title: 3D GUI Shader Problem

text:
# Question
Title: 3D GUI Shader Problem
So I want to create one of these in my directX11 project.

The little axis there that shows you the direction.

I have a nice 3d shader for my world geometry that I tweaked from Frank D. Luna (He writes books on directX.) and another for my 2D UI so I thought I'd look at those and see what I could conjure up since I didn't know all that much about shaders to begin with. But this is what I came up with.

```
float4x4 gWorldViewProj;

struct VertexIn
{
    float3 PosL    : POSITION;
    float3 NormalL : NORMAL;
    float2 Tex     : TEXCOORD;
};

struct VertexOut
{
    float4 PosH       : SV_POSITION;
    float2 Tex        : TEXCOORD;
};

VertexOut VS(VertexIn vin)
{
    VertexOut vout;

    // Transform to homogeneous clip space.
    vout.PosH = mul(float4(vin.PosL, 1.0f), gWorldViewProj);

    // There are no transformations for texture coordinates.
    vout.Tex = vin.Tex;

    return vout;
}

```

This code works if I pass in a quad and render a texture too it. Then for gWorldViewProj I give it just the world matrix of the UI. Renders fine.

But when I tried it with 3D objects (anything that wasn't a quad.) nothing would render. The only way I could get it to render is by passing in world * view * proj but then it rotates around the scene when you look around because of the view matrix.

So the obvious work around was to create a view matrix with no transformations and that worked.

I thought I could just give it a world matrix since that's what I did with the 2D UI. I also tried world * proj but no prevail. Why does this shader render quads without a view matrix but can't render other more complex sets of geometry without the view matrix. Here is how I generated the quad.

# Answer
> Please also expand on this: "world matrix of the UI" and show how it's constructed.

If you do not explicitly supply a World, View, or Projection, Identity is used. This has the effect of multiplying everything by 1 (no change). Using a world matrix without a view matrix is the same as using a view matrix without a world matrix; (X\*1)==(1\*X)==(X). I might be misunderstanding, but I suspect your confusion is stemming from that.

If World, View, and Projection are all Identity, then world-space, view-space, projection-space, and screen-space all have the same origin and units. If any matrix is not Identity, coordinates from the previous coordinate system are being moved/scaled into the next. When all objects have been located in world-space by their individual world-matrices, the entire world is moved/rotated/scaled at once by the view matrix. If the view matrix happens to be Identity, the objects are, now, *already in* projection space.

This is *what* you are doing, but its not clear, to me, exactly *how* yet; will update as necessary.

**Keep in mind that:**

```
translating coordinates (away from (0,0)), Then rotating them (around (0,0))

```

is **not** the same as:

```
rotating coordinates (around (0,0)), Then translating them (away from (0,0))

```

> So the obvious work around was to create a view matrix with no transformations and that worked.

Your intuition is spot-on; it is very common to keep the rotation component of the view matrix separate.

**Another note about view matrices:**
The view matrix does not typically scale coordinates; it only moves or rotates them. That means that world-units and camera-units are usually the same; only the origin and orientation are changed. When the camera moves "left 5", the objects in view appear to move "right 5", instead. View-space's origin (0,0) is the "camera"; to "make the camera become (0,0)", the entire world (including the camera) is "un-moved" by the camera's 3D position. Similarly, the world is "un-rotated" by the camera's rotation. A view-matrix is an "un-world-matrix".

If you wanted to render a mesh representing *a* camera (not THE camera, obviously), you'd locate the mesh in world-space with a world matrix. That same world matrix (excluding scale), inverted, is the view matrix that you'd use to render from that camera's perspective.
> 1 votes

---
Tags: c++, shaders, directx, hlsl
---


title: Button detection in unity3d

text:
# Question
Title: Button detection in unity3d
we are developing a a game in unity 3D . To play the game we need a number of instruments. we have given a set of buttons to activate the instruments: each button corresponds to a particular instrument. when a button is clicked, the texture of the corresponding instrument becomes the cursor. different instruments are to be taken at different stages of the game. Now how do we detect if it is a wrong instrument that is taken and then display an error message ? The player should be able to play further only after he clicks the button of the right instrument. how to accomplish this?

refered link :http://www.games.jocuri-unity3d.com/heart-surgery.html

# Answer
I played the game. Each of the separate games appear to be "maps" loaded in the same basic surgery game. Each "map" seems to have a pre-determined script that the player follows, or else.

Each button/tool is given a ToolID.

For the heart-surgery "map":

```
toolsNeeded = {1,3,2,6,3,5,1,0}; //Loaded from "map"
currentToolIndex = 0; //New game
while(patientAlive && surgeryIncomplete) //Wherever win/loss is evaluated
{
   currentTool = toolsNeeded[currentToolIndex]; //Do this next
   nurse.RecommendTool(currentTool); //Tell the player
}

```

During ToolClick():

```
   if (clickedTool == currentTool) //Correct tool?
   {
      activateTool(currentTool); //Apply new texture
   }
   else nurse.BeratePlayer(); //ID10-T error

```

During PatientClick():

```
   if (correctPointClicked) //Not hack-n-slash
   {
      nurse.GoodJobWith(currentTool);
      currentToolIndex++; //Next step/tool
   }
   else patient.MaimOrKill();

```

You also pick which room to perform the surgery in. In this phase, the three doors can be evaluated like they are "tools"; the toolbox just looks a little different.
> 1 votes

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


title: DirectX11 Equivalent of OpenGL code

text:
# Question
Title: DirectX11 Equivalent of OpenGL code
I am currently porting parts of my engine over to D3D11 from OpenGL and was trying to figure out how I would accomplish the following blending functions in D3D11.

```
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE);
glDepthMask(GL_FALSE);
glDepthFunc(GL_EQUAL);

```

I believe it should be something like this:

```
D3D11_BLEND_DESC blendDesc;
ZeroMemory(&blendDesc, sizeof(blendDesc));

D3D11_RENDER_TARGET_BLEND_DESC rtbd;
ZeroMemory(&rtbd, sizeof(rtbd));

rtbd.BlendEnable = true;
rtbd.SrcBlend = D3D11_BLEND_ONE;
rtbd.DestBlend = D3D11_BLEND_ONE;

rtbd.BlendOp = D3D11_BLEND_OP_ADD;
rtbd.SrcBlendAlpha = D3D11_BLEND_ONE;
rtbd.DestBlendAlpha = D3D11_BLEND_ONE;
rtbd.BlendOpAlpha = D3D11_BLEND_OP_ADD;
rtbd.RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
blendDesc.AlphaToCoverageEnable = true;
blendDesc.RenderTarget[0] = rtbd;

m_D3D->GetDevice()->CreateBlendState(&blendDesc, &m_blendMode);

```

However this does not work. How can I achieve the same effect as in the first code snippet?

Thanks

# Answer
This portion of your code is not technically blend state, but could be affecting the behavior here:

`glDepthMask(FALSE)
glDepthFunc(GL_EQUAL)`

D3D11 does have corresponding state to this, and you can set it by creating and binding a ID3D11DepthStencilState object, in a similar way to what you're doing with the ID3D11BlendState.

See https://msdn.microsoft.com/en-us/library/windows/desktop/ff476506(v=vs.85).aspx for details.

Essentially you'd be filling out an D3D11\_DEPTH\_STENCIL\_DESC descriptor to create that object, and given that descriptor 'desc':

* desc.DepthWriteMask maps to glDepthMask value
* desc.DepthEnable = true/false corresponds to glEnable(GL\_DEPTH\_TEST)/glDisable(GL\_DEPTH\_TEST) respectively
* desc.DepthFunc maps to glDepthFunc value
* only turn on stenciling and assign the rest of the fields if you're using stenciling.
> 1 votes

---
Tags: opengl, c++, directx, directx11, alpha-blending
---


title: Big 2D world Unity3d

text:
# Question
Title: Big 2D world Unity3d
I am planning to make a 2d tile based platformer with big world like in terraria.

I have some questions to ask on how to manage this big world in Unity3D.

**The Scenario**

World Size = 1000 x 1000 = 1 Million Tiles

Tiles Viewable in Camera = 32 x 24

Chunk Size = 32 x 24

There will 9 Chunks present in the scene at one time ( Center,Left,Right,Top,Bottom and 4 diagonal), total tiles present at one time 6912

**Questions**

Every tile is a gameObect with a box collider on it, a script containing the tile information(health,type), wouldn't this take a lot of memory and processing because there are 6912 tiles present in the scene all the time?

If I generate a mesh of chunk, how will the collision be handled(Considering every tile is destructible)? Will I have to redraw the mesh even if a single tile is destroyed? Won't this be less optimized as compared to the tile based approach?

I'd really like to if anyone here has done this in unity and will be really thankful if you share your approach of handling big world. Thanks!

# Answer
> 1 votes
I try with some consideration. 1000 * 1000 is similar to a bitmap 1024\*1024 , something you can easly store in memory.

You can "cablate" the type and health of each block in the color / alpha of each pixel. Then you istantiate / deistantiate (or activate / deactivate) the blocks at runtime refering the camera position. So you can have 32 x 24 blocks (+ a delta for caching) active on the screen gaining in performance.

If you don't like the bitmap approach you can define a bidimensional array of structs..

Finaly, the "destructibles" tiles are only a sub set of the tiles (for example the top ones where some character walks?), again activate / deactivate the "destructible" script at run time. (i.e when you destroy a block , check if you can activate the neighbourg scripts)

---
Tags: unity, mesh
---


title: GL_SPOT_CUTOFF not working properly

text:
# Question
Title: GL_SPOT_CUTOFF not working properly
I'm new to OpenGL. I'm studying OpenGL 2.1 and I'm trying to make a little program to test the GL\_SPOT\_CUTOFF property, but when I set a value between 0.0-90.0, the light doesn't work and everything is dark.

The code:

```
void lightInit(void) {

    GLfloat light0Position[] = {0.0,0.0,2.0,1.0};
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 45.0);
    glLightfv(GL_LIGHT0, GL_POSITION, light0Position);
}

void reshapeFunc(int w, int h) {

    glViewport(0, 0, (GLsizei) w, (GLsizei) h);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    if (w <= h)
        glOrtho(-4, 4, -4*(GLfloat)h/(GLfloat)w, 4*(GLfloat)h/(GLfloat)w, -4.0, 4.0);
    else
        glOrtho(-4*(GLfloat)w/(GLfloat)h,4*(GLfloat)w/(GLfloat)h, -4, 4, -4, 4.0);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    gluLookAt(0,0,0,0,0,-1,0,1,0);

}

void displayFunc(void) {

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // center sphere
    glutSolidSphere(1, 100,100);

    // right sphere
    glPushMatrix();
        glTranslatef(3,0,0);
        glutSolidSphere(1, 100,100);
    glPopMatrix();

    // left sphere
    glPushMatrix();
        glTranslatef(-3,0,0);
        glutSolidSphere(1, 100,100);
    glPopMatrix();

    glutSwapBuffers();

}

void keyboardFunc(unsigned char key, int x, int y) {

    if (key==27) {
        exit(EXIT_SUCCESS);
    }

}

int main(int argc, char** argv) {

    //freeglut init and windows creation
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
    glutInitWindowSize(600, 500);
    glutInitWindowPosition(300, 100);
    glutCreateWindow("OpenGL");

    //glew init and errors check
    GLenum err = glewInit();
    if (GLEW_OK != err) {
      fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
      return 1;
    }
    fprintf(stdout, "---GLEW %s---\n\n", glewGetString(GLEW_VERSION));

    //general settings
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glShadeModel(GL_SMOOTH);
    glEnable(GL_DEPTH_TEST);

    //light settings
    lightInit();

    //callback functions
    glutDisplayFunc(displayFunc);
    glutReshapeFunc(reshapeFunc);
    glutKeyboardFunc(keyboardFunc);

    glutMainLoop();

    return 0;

}

```

This code produces this image:

If I delete `glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 45.0);`, the next image is produced:

Is there some kind of bug ?

# Answer
Code works for me, exactly as presented in the question (after adding the missing #include lines). (Ubuntu 14.10, AMD Radeon HD 5870, running the latest Catalyst drivers)

Middle sphere is hit by the spotlight, left and right spheres are not.

Whatever your problem is, it's presumably not the code (although I haven't tested this on any devices other than the one mentioned above. Possible that there's an "undefined behaviour" bug which happens to work nicely under my driver but which isn't working so nicely under yours).
> 0 votes

---
Tags: opengl, lighting
---


# Question
Title: Programatically find out which app store install came from?
**Background**

In my app, I have a 'rate me' button. It follows the usual path - user clicks in, it starts an intent and opens the app's listing on the Play Store. All well and good. Now I wish to try to distribute my app via different app stores (Amazon for example), so obviously, if the user hits the 'rate me' button I don't want it to take the user to the Google Play Store but to whatever store they got it from.

**APK For each store**

This is possible, true, but I think it would be a complete nightmare to manage (like creating a new APK for each store every time I issue a new update.

So I'm looking for something like this pseudo code:

```
if(rate-me button pressed){

    if (from Google Play Store){
        Go to Google Play Store
    }
    else if (from Amazon Store){
        Go to Amazon Store
    }
}

```

And so on.......

I'm guessing there is a way (that some apps must surely use) but I have no idea how to go about it.

# Answer
I'm going to assume you're writing in Java as you're writing for Android, but if you're not you can look up methods in your language of choice to get the same sort of result. Since Java has no built in support for conditional compilation, there's some pretty easy things you can do here; sometimes the low-tech solution is the best one.

**Deploy a different app compiled from different code for each app store.** It can be that simple. Just have a global string (or not, encapsulate it where the appropriate logic is) and simply assign it a value, compile, and deploy. It's that easy.

It can be a string, an enum value or integer. It doesn't really matter -- as long as each value is unique per app store. I'd suggest a quick strongly-typed enum with options like "Amazon", "GooglePlay", "XXXX", "ZZZZ", "YYYY". Write scripts to change this value or pass in compilation flags using 3rd party tools if you want this to be automated.

**Automating it up**

If you want to take this one step further, parse the option as **resource file**. Write scripts, one for each deployment. Have a file called "store.dat" and write the value of the store it's being deployed to the file when deployed, if you're under Linux or OSX it could be something as simple as

```
echo "Google" > resources/store/store.dat
RUN COMPILATION STUFF HERE

```

Make one script to execute all of these scripts in lock step and you have a robust, automated solution.
> 7 votes

# Answer
try this:

```
try {
    String packagename = context.getPackageName();
    final PackageManager pm = context.getPackageManager();
    PackageInfo pInfo = pm.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS);
    String installerPackagenName = pm.getInstallerPackageName(packageName);
    if(installerPackagenName.equalsIgnoreCase("com.amazon.venezia")){
        //Go to Amazon Store
    } else if (installerPackagenName.equalsIgnoreCase("com.android.vending")){
        //Go to Google Play Store
    } else {

    }
} catch (PackageManager.NameNotFoundException e) {
    e.printStackTrace();
}

```
> 2 votes

---
Tags: android, appstore, google-play
---


# Question
Title: How can I store additional attributes on DCEL edges?
I am currently working on a city generator, and I've ran into some issues with data storage while working on the roads. I currently use a doubly-connected edge list (DCEL for short), to store the road data. Each road would consist of two half edges, each connecting to a vertex.

The advantage of a DCEL is that I can easily access the space partitions of the roads, or the faces contained by the half edges. However, I am running into trouble storing additional data for roads.

I currently store (alongside the DCEL) a vector that simple contains all the roads as simple pairs of the indices of their beginnings and ends. However, I only use this vector to access data in bulk (for a bounding box test or rendering), nothing specific.

I want to store additional information about roads as some struct, but I don't know where to store it. I would need to access it easily through the DCEL, but I don't want to duplicate the data between the two half edges. What should I do?

# Answer
> 1 votes
Store road attributes in separate `struct`s and have pointers to them from your DCEL edges. It doesn't matter if some edges point to the same location in memory—the attribute data has still been allocated only once.

---
Tags: c++, maps, data-structure
---


title: Unity: scaling and animations

text:
# Question
Title: Unity: scaling and animations
In my Unity project I have a script that programmatically changes the scaling of an object during the game.

Recently I wanted to add a spawning animation clip to my object, which modifies the object's scaling (but only during a short delay). So I added an animation controller to the object, containing the spawning animation clip.

I can now successfully run the spawning animation but the in-game programmatic scaling changes don't work anymore, even when my animation is not running.

Any idea?

# Answer
> 1 votes
I think you have to move all procedural animation to LateUpdate(). This will allow you to override Unity animation.

UPD: and you have to animate **lossyScale** instead on **localScale**, since localScale is animated by Unity (look for Mitchell's answer for details)

# Answer
> 4 votes
As others have pointed, your animation is most likely overwriting the transform of your GameObject.

Generally, you can't (cleanly) have both an animation and a script modify the transform of the same GameObject without conflicting between each other.

So how about, instead of fighting against Unity to get an animation and a script to modify the same transform, you put the GameObject that has the MeshRenderer inside another object.

This way, the animation will affect the child object, the script will affect the parent object, and you get the benefit of both transforms at the same time.

# Answer
> 1 votes
The clean way is to add a new property, eg called animatedScale, to your script which you animate instead of directly animating the object's scale. then, in your Update, you set the gameobjects scale to 'animatedScale * yourScale' or whatever you want. This way the animation and your scaling are seperated and applied in a controlled way.

# Answer
> 0 votes
Somewhere in your code you're still setting the scale, so each time you try to modify the scale in the editor when running the game, it resets the scale. Without being able to look at your code it's impossible to tell you what is exactly causing the problem.

In addition to that, when you are running an animation it overwrites the `localScale`, so you can't possibly combine an animation that changes the scale and programmatical scaling. Basically, animation clips can only have one scale (or none).

So you might want to consider replacing your animation clip with programmatical animation entirely.

---
Tags: unity
---


# Question
Title: Unity 5: 3rd Person Controller runs by default. How to change this?
I have been working with the Third Person Controller of the Standard Assets (called Sample Assets in the beta versions) in Unity 5. When the player press the forward button, the character runs by default, and walks if you hold Left Shift, and I want to swap that.

However, The controller makes use of Blend Trees, and have two scripts to manage movement and input and it's far too complex for me and so I need your help. How can I change the controller so that the player walks by default and has to hold Shift to run?

# Answer
The state of the `Shift` key is checked in the `ThirdPersonUserControl.cs` script which isn't that difficult.

To just swap the states you most likely (I haven't checked it!) would need to replace the

```
#if !MOBILE_INPUT
        // walk speed multiplier
        if (Input.GetKey(KeyCode.LeftShift)) m_Move *= 0.5f;
#endif

```

with

```
        m_Move *= 0.5f; // Do it before the #if to have your character walk by default on mobile devices too.
#if !MOBILE_INPUT
        // walk speed multiplier
        if (Input.GetKey(KeyCode.LeftShift)) m_Move *= 2;
#endif

```

or even with just

```
#if !MOBILE_INPUT
        // walk speed multiplier
        if (!Input.GetKey(KeyCode.LeftShift)) m_Move *= 0.5f;
#endif

```

if you want the character to run by default on mobile devices.
> 0 votes

---
Tags: unity, input
---


# Question
Title: AI for Shogi, dealing with high branching factor due to drop rule
I'm writing a Shogi program with a computer player in Java from scratch as my undergradute dissertation project. Due to the drop rule, when the computer player captures a few pieces, the branching factor increases a lot and the running time becomes infeasible. I haven't manage to find any research or information on drop reduction and my own selection is too slow and not "selective" enough (trying to remove drops that are not safe or not protected and don't have any use like defending or attacking). Does anyone know any heuristics that can be implemented with reasonable time complexity for selecting drops that are worth adding to the game tree ? Cheers.

So, like in (western) Chess a piece can be captured and when a piece is captured the capturing player holds on to it. Now this piece can be dropped on the board anywhere on a free tile in any of the next turns (instead of moving a piece from the board). There are a lot more rules to drops but they are irrelevant. Because of this rule, when a player makes a capture, instead of a decrease in the branching factor like in chess, an increase of the branching factor happens because of the large amount of possible drops that can be made on the next turn. This results in an average branching factor of 80 (much more than Chess which has a average branching factor of 35).

# Answer
> 3 votes
Shogi is well researched, so you should be able to find research papers detailing different methods of implementing pruning or reduction heuristics for Shogi.

I can't offer specific advice since I've never implemented a Shogi engine, but I did implement one for Bughouse/Crazyhouse, which has similar rules (captured pieces can be dropped). My advice would be to simply focus on optimizing the efficiency of the engine as much as possible - I don't only mean speed here, though raw speed shouldn't be neglected. Remember that with alpha-beta pruning the effective branching factor of your engine only goes up by sqrt(average\_legal\_moves), so the increase due to the drop rule is much less as you would naively think (from 6 to 9). Now notice that real chess engines have an effective branching factor of just ~2 because they use more heuristics than basic alpha-beta pruning.

If a high branching factor is making your engine weak, it's much more likely your basic alpha-beta + move ordering + iterative deepening + transposition table + nullmove + futility + LMR implementation isn't good enough and contains bugs. I would focus on those before doing more complicated things specifically for drop-moves.

# Answer
> 0 votes
I have no direct experience with Shogi, but:

1) You should check that your implementation isn't unnecessarily slow - as noted in gcp's answer, it sounds like it should work. How many positions do you evaluate per second? In C++ for a simple game, you can get around 10^7 moves per second. If you have complex heuristics and/or complex game rules, you still should stay at least at 10^6. If you are significantly below, you are probably doing something wrong and should focus on optimizing your code.

2) If your implementation is fast, but branching factor too high, you can use Monte Carlo Tree Search, especially UCT as for example here: http://senseis.xmp.net/?UCT It is not that hard too implement (I did it in C++ in around 3 days) and has worked well for Go, so it should be good for you as well.

---
Tags: java, ai, tree, board-game, heuristics
---