# Question
Title: Load 2 triangles in a simple DX11 example
I'm following this tutorial, where they show how to setup a simple dx11 demo with a green triangle in the middle. I'd like to be able to modify it so that it shows 2 triangles instead, i modified the code of the Graphicsclass.cpp in the tutorial by adding some lines to the Render() function, just after the first triangle is drawn, it's the //ADDITIONAL CODE section:

```
[...]
// Put the model vertex and index buffers on the graphics pipeline to prepare them for drawing.
m_Model->Render(m_Direct3D->GetDeviceContext());

// Render the model using the color shader.
result = m_ColorShader->Render(m_Direct3D->GetDeviceContext(), m_Model->GetIndexCount(), worldMatrix, viewMatrix, projectionMatrix);
if (!result)
{
    return false;
}

//ADDITIONAL CODE
// Reset the world matrix.
worldMatrix = XMMatrixIdentity();

// Translate to the location of the second triangle.
translateMatrix = XMMatrixTranslation(1.0f, 1.0f, 0.0f);
worldMatrix = XMMatrixMultiply(worldMatrix, translateMatrix);

// Put the model vertex and index buffers on the graphics pipeline to prepare them for drawing.
m_Model->Render(m_Direct3D->GetDeviceContext());

// Render the model using the color shader.
result = m_ColorShader->Render(m_Direct3D->GetDeviceContext(), m_Model->GetIndexCount(), worldMatrix, viewMatrix, projectionMatrix);
if (!result)
{
    return false;
}
//END OF ADDITIONAL CODE
// Present the rendered scene to the screen.
m_Direct3D->EndScene();

```

But the second triangle doesn't show up, i also put the complete example on github in case you want to try it yourself. I'm sure i'm missing something pretty basic but i can't figure it out

# Answer
> 1 votes
Ok, i was able to solve it, even if i can't really explain why. In the tutorial, inside the function ColorShaderClass::SetShaderParameters(), i had this:

```
bool ColorShaderClass::SetShaderParameters(ID3D11DeviceContext* deviceContext, XMMATRIX& worldMatrix, XMMATRIX& viewMatrix,
                                       XMMATRIX& projectionMatrix)

[..]
// Transpose the matrices to prepare them for the shader.
worldMatrix = XMMatrixTranspose(worldMatrix);
viewMatrix = XMMatrixTranspose(viewMatrix);
projectionMatrix = XMMatrixTranspose(projectionMatrix);

// Lock the constant buffer so it can be written to.
result = deviceContext->Map(m_matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
if(FAILED(result))
{
    return false;
}

// Get a pointer to the data in the constant buffer.
dataPtr = (MatrixBufferType*)mappedResource.pData;

// Copy the matrices into the constant buffer.
dataPtr->world = worldMatrix;
dataPtr->view = viewMatrix;
dataPtr->projection = projectionMatrix;

```

As you can see, the worldMatrix, viewMatrix and projectionMatrix are passed to the function and used directly. I noticed that sometimes (under which circumstances? i dont know) this and other demos crashed with an ACCESS VIOLATION error, that happened exactly at this line:

```
viewMatrix = XMMatrixTranspose(viewMatrix);

```

Out of ideas, i decided to modify the function so that the 3 matrices are first passed to some local variables, so that the function operates on the copies, like this:

```
// Copy the 3 matrices to local variables

XMMATRIX worldMatrixLocal = worldMatrix;
XMMATRIX viewMatrixLocal = viewMatrix;
XMMATRIX projectionMatrixLocal = projectionMatrix;

// Transpose the matrices to prepare them for the shader.
worldMatrixLocal = XMMatrixTranspose(worldMatrixLocal);
viewMatrixLocal = XMMatrixTranspose(viewMatrixLocal);
projectionMatrixLocal = XMMatrixTranspose(projectionMatrixLocal);

// Copy the matrices into the constant buffer.
dataPtr->world = worldMatrixLocal;
dataPtr->view = viewMatrixLocal;
dataPtr->projection = projectionMatrixLocal;

```

This solved my problem, the 2 triangles are now shown correctly, unfortunately i can't explain why exactly this fix works.

---
Tags: c++, directx
---


# Question
Title: LibGDX Rotate 2D image with touchDragged() event
**Objective: to rotate an image in the center of the screen with movement equal to left or right touchDragged event.**

Right now I have a basic Stage that is created and adds an actor (centerMass.png) to the stage. it is created and rendered like this:

```
public class Application extends ApplicationAdapter {
Stage stageGamePlay;

@Override
public void create () {
    //setup game stage variables
    stageGamePlay = new Stage(new ScreenViewport());
    stageGamePlay.addActor(new CenterMass(new Texture(Gdx.files.internal("centerMass.png"))));

    Gdx.input.setInputProcessor(stageGamePlay);

}

@Override
public void render () {
    Gdx.gl.glClearColor(255f/255, 249f/255, 236f/255, 1f);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    //before drawing, updating actions that have changed
    stageGamePlay.act(Gdx.graphics.getDeltaTime());
    stageGamePlay.draw();

    }
}

```

I then have a separate class file that contains the CenterMass class, extending Image. I am familiar enough to know I could extend Actor, but I am not sure the benefit I would gain using Actor vs Image.

In the CenterMass class I create the texture, set bounds, set touchable and center it on the screen.

Inside CenterMass class I also have an InputListener listening for events. I have an override set for touchDragged where I am trying to get the X and Y of the drag, and use that to set the rotate actions accordingly. That class looks like this:

```
//extend Image vs Actor classes
public class CenterMass extends Image {
public CenterMass(Texture centerMassSprite) {
    //let parent be aware
    super(centerMassSprite);
    setBounds(getX(), getY(), getWidth(), getHeight());
    setTouchable(Touchable.enabled);
    setPosition(Gdx.graphics.getWidth()/2, Gdx.graphics.getHeight()/2);
    setRotation(90f);

    addListener(new InputListener(){
        private int dragX, dragY;
        private float duration;
        private float rotateBy = 30f;

        @Override
        public void touchDragged(InputEvent event, float x, float y, int pointer) {
            //get
            float dX = (float)(x-dragX)/(float)Gdx.graphics.getWidth();
            float dY = (float)(dragY-y)/(float)Gdx.graphics.getHeight();

            duration = 1.0f; // 1 second

            Actions.sequence(
                    Actions.parallel(
                            Actions.rotateBy(rotateBy, duration),
                            Actions.moveBy( dX, dY, duration)
                    )
            );

        }
    });
}

@Override
protected void positionChanged() {
    //super.positionChanged();
}

@Override
public void draw(Batch batch, float parentAlpha) {
    //draw needs to be available for changing color and rotation, I think
    batch.setColor(this.getColor());
    //cast back to texture because we use Image vs Actor and want to rotate and change color safely
    ((TextureRegionDrawable)getDrawable()).draw(batch, getX(), getY(),
            getOriginX(), getOriginY(),
            getWidth(), getHeight(),
            getScaleX(), getScaleY(),
            getRotation());
}

@Override
public void act(float delta) {
    super.act(delta);
    }
}

```

**The Problem:** I have not been able to get it to rotate the way I would like. I have been able to get it to shift around in unpredictable ways. Any guidance would be much appreciated.

# Answer
> 0 votes
`Actions.sequence()` is a convenience method to create a `SequenceAction` object. You have to give this action to your Actor for it to do anything.

```
//addAction() is a member of Actor
this.addAction(Actions.sequence(...))

```

However, this is probably not what you want. Firstly, a `SequenceAction` is an action where it waits for each action to finish before the next action is applied. To execute both at the same time, you don't need the `sequence()` or `parallel()` calls, just

```
this.addAction(Actions.rotateBy(rotateBy, duration));
this.addAction(Actions.moveBy( dX, dY, duration));

```

They will execute in parallel and remove themselves when they have finished after `duration` seconds.

That being said, you might not want to use actions in the first place As your code is now, you will add `Action`s to the image actor each time that the `touchDragged()` event fires, regardless of whether the prior `Action`s have completed. You could wait until the `Action`s are finished (via `Actor.hasAction()`) or clear the existing `Action`s from the `Actor` before re-adding them. Or you could forgo adding any `Action`s at all and have your `touchDragged()` event directly move and rotate the image.

P.S. There really is no reason at this point to inherit from `Actor` since `Image` already inherits from `Actor`

---
Tags: android, libgdx, scene2d
---


title: Game Maker - Random Won't Stop

text:
# Question
Title: Game Maker - Random Won't Stop
I make a project. I want to make randomize number & draw the number result. So, I make `obj_BossText`, which has a draw event & executes a code inside the event. This is the code:

```
randomize();

var ratio = irandom_range(1, 6);
var u7;

u7 = power(ratio, 6);
draw_text(obj_Boss.x, obj_Boss.y,u7);

```

But, the result is, the text won't stop randomizing & keep changing from one number to another. What is wrong? Do I have to stop the random? But, how? Please explain your code. Thanks

# Answer
> 1 votes
First of all, the *Draw Event* is suppose to contain only graphical rendering functions and statements, you are strongly recommended to separate logic from rendering.

Being the *Draw Event* executed `room_speed` times per second, it keeps generating random numbers continuously over the time, and that's another reason to move the variable assignment outside from the *Draw Event*.

I suggest you to edit your `obj_Boss` having a *Create Event* and a *Draw Event* as follow:

```
// Create Event
randomize();
ratio = irandom_range(1, 6);
u7 = power(ratio, 6);

```

and:

```
// Draw Event
draw_text(obj_Boss.x, obj_Boss.y,u7);

```

This way, your random number `ratio` and its power `u7` will be assigned only once, and you will be displaying the value assigned to them. Also, `ratio` and `u7` aren't local variables anymore but instance variables, thus they are accessible by other instances.

You can even save memory space by removing your variable `ratio` and perform the computation on one line only:

```
// Create Event
u7 = power(irandom_range(1, 6),6);

```

That's a legal statement as first `irandom_range()` is executed, and its return value is used as argument for function `power()`.

# Answer
> 1 votes
only run the `irandom_range` once when you start showing the text and store the result in `obj_BossText`

---
Tags: random, game-maker
---


title: texelFetch weird behavior

text:
# Question
Title: texelFetch weird behavior
I am writing an isometric game engine on OpenGL (version 3.3 specifically). For each wall tileset i have volume mask tileset for the wall relative volume coordinates.

Volume mask looks like this:

Now i am trying to write a simple lighting system (it kinda looks like that old game, Nox):

The idea is simple - i generate one-dimensional z-buffer for each light source (in the example i use only one test light spot), in the fragment shader for each fragment i'm figuring out is it lit or not etc.

Here's the vertex shader:

```
attribute vec3 scenePosition;
attribute vec3 screenPosition;
attribute vec2 screenTexCoord;
attribute vec2 volTexCoord;
attribute vec2 normalMaskTexCoord;
const int MAX_LIGHTS = 12;
uniform mat4 projectionMatrix;
uniform mat4 scrollingMatrixScreen;
out vec2 texCoordFrag;
out vec2 volTexCoordFrag;
out vec2 normalMaskTexCoordFrag;
out vec3 scenePosFrag;

void main(){
    texCoordFrag = screenTexCoord;
    volTexCoordFrag = volTexCoord;
    normalMaskTexCoordFrag = normalMaskTexCoord;
    scenePosFrag = scenePosition;
    gl_Position = projectionMatrix * scrollingMatrixScreen * vec4(screenPosition, 1.0);
}

```

Fragment shader:

```
const float specificLength = 0.177469939;
const float M_PI = 3.14159265358979323846;
const int LIGHT_Z_BUFFER_SIZE = 1024;

uniform sampler2D tex;
uniform sampler2D volumeMask;
uniform sampler2D normalMask;
uniform samplerBuffer testLightZBuffer;
uniform vec3 changingVec;

in vec2 texCoordFrag;
in vec3 scenePosFrag;
in vec3 testColorFrag;
in vec2 volTexCoordFrag;
in vec2 normalMaskTexCoordFrag;
in float wallLengthFrag;

out vec4 fragColor;

void main(){
    vec4 trueColor = texture(tex, texCoordFrag);
    if (trueColor == vec4(0.0, 0.0, 0.0, 0.0))\
        discard;

    float testLightRadius = 4.0;
    vec2 testLightCenter = vec2(2.0, 2.0);
    float lightBrightness = 0.0;
    float lightHeight = 2.0;

    vec3 volCoords = vec3(texture(volumeMask, volTexCoordFrag));
    vec3 trueSceneCoords = vec3(volCoords.x/specificLength, volCoords.y/specificLength, volCoords.z/specificLength) + scenePosFrag;
    vec3 normalCoords = normalize(vec3(texture(normalMask, normalMaskTexCoordFrag)));
    vec2 lightTangentRel = vec2(trueSceneCoords) - testLightCenter;

    if (length(lightTangentRel) <= testLightRadius)
    {
        float angle = acos(dot(normalize(lightTangentRel), vec2(1.0, 0.0)));
        float currentZBufferPoint = angle / (2*M_PI);
        int currentTexelId = int(round(LIGHT_Z_BUFFER_SIZE * currentZBufferPoint));
        vec4 obstRad = texelFetch(testLightZBuffer, currentTexelId);

        if (length(lightTangentRel) < testLightRadius)
        {
            float lightIntensity = cos((length(lightTangentRel)*M_PI/2)/(testLightRadius));
            lightBrightness = lightIntensity;

    }

    vec4 nightColor = vec4(trueColor.x*0.1, trueColor.y*0.1, trueColor.z*0.2, trueColor.w);
    vec4 lightColor = trueColor;
    if (0.0 <= lightBrightness && lightBrightness <= 1.0)
        fragColor = mix(lightColor, nightColor, 0.0);
}

```

The problem is, texelFetch can't handle *currentZBufferPoint* variable, it just doesn't draw ANYTHING, but *lightBrightness* should be at least 0, therefore it must draw at least black pixels. Looks like shader program crashes somewhere, but it compiles completely fine.

So, after several hours i figured out where is the problem - it is here:

```
vec3 volCoords = vec3(texture(volumeMask, volTexCoordFrag));

```

If i replace *texture(volumeMask, volTexCoordFrag)* with anything else, it works. Pls help.

# Answer
> 1 votes
Well, i just figured it out - i just set uniform samplers variables incorrectly.

---
Tags: opengl, glsl, texture-atlas
---


# Question
Title: How can I defer the initialization of my level's entities until I need them?
I intend to use a level-entity-components hierarchy in my C++ game engine where a "level" is just a container for entities. However, since I'd like to setup all the levels at once (and thus all entities and components) I've stumbled upon a memory management dilemma: since only one level can be run at a time I need somehow to delay an initialization of other level's entities. How can I accomplish that?

I've considered a solution where all the levels derive from some `Level` base class and are initialized in the constructor when needed, but that would require creating a class with just the constructor in it for each level.

# Answer
> I need somehow to delay an initialization of other level's entities

Why not add an `init()` and a `terminate()` methods to your Level class that does just that? `init()` populates your level when you're ready to play it, and `terminate()` cleans everything up when you're done with it.

You might want to consider changing your architecture to have `Level` created only when you need it: with that, you put the initialization code in the constructor, and the termination in the destructor. This would be more in line with RAII's principles.
> 1 votes

---
Tags: c++, architecture, design-patterns
---


title: Android OpenGL Sprite Component Pattern

text:
# Question
Title: Android OpenGL Sprite Component Pattern
Ok so I have a 2D OpenGL project that was originally a class assignment, and now I am using it to experiment with and to broaden my knowledge. Originally, I had been using the Normalized Devices Coordinates \[-1 , 1\], which creates headaches when dealing with the logic that handles sprites' position on the screen. Since then I have found out how to manipulate the camera so that all the action takes place inside of the coordinates \[0, 1\]. Programmatic Ibuprofen!

However, now I am getting a strange behavior that I believe has to do with how I am creating sprites. There is a parent/child relationship that is created along with the first drawn sprite and the one immediately subsequent, i.e. when the first sprite's position is updated all of the others are updated as if it were the first one.

The picture above sorta shows what I am talking about. The background should scroll in the direction of the arrow (which it does), but the ship in the center should be stationary. However, it is scrolling downward with the background.

Now back to the method I am using to create the sprites: I have a singleton class that I use to load textures and handle the draw calls. My reasoning for this is that each object that has a sprite that will be drawn to the screen calls all of the exact same functions, the only difference between them is what image we want to draw.

**Question**

Is my reasoning and choice of implementation a good one? Or should I be using interfaces and a factory pattern? Also is the reason for the pair scrolling together have to do with the fact that Sprite is a static class?

Here are the three classes; Sprite, Space (scrolling background), and Ship.

**Sprite class**

```
public class Sprite {
    private final String vertexShaderCode =
            "uniform mat4 uMVPMatrix;" +                                                    // This matrix member variable provides a hook to manipulate
            "attribute vec4 aPosition;" +                                                   // the coordinates of the objects that use this vertex shader
            "attribute vec2 aTexCoordinate;" +                                              // Per-vertex texture coordinate information that is passed in.
            "varying vec2 vTexCoordinate;" +                                                // This will be passed into the fragment shader.
            "void main() {" +
            "  gl_Position = uMVPMatrix * aPosition;" +                                     // The matrix must be included as a modifier of gl_Position
            "  vTexCoordinate = aTexCoordinate;" +                                          // Pass through the texture coordinate.
            "}";                                                                            // Note that the uMVPMatrix factor *must be first* in order
                                                                                // for the matrix multiplication product to be correct.
    private final String fragmentShaderCode =
            "precision mediump float;" +
            "uniform vec4 vColor;" +
            "varying vec2 vTexCoordinate;" +                                                // Interpolated texture coordinate per fragment.
            "uniform sampler2D uTexture;" +                                                 // The input texture.
            "void main() {" +
            "  gl_FragColor = " +                                                           // Final texture output
            "  texture2D(uTexture, vTexCoordinate);" +
            "}";

    private static FloatBuffer vertexBuffer;
    private static FloatBuffer textureBuffer;

    private int mProgram = -1;
    private int mTextureDataHandle;
    private int mMVPMatrix;
    private int mPositionHandle;
    private float[] mModelView = new float[16];

    static final int COORDS_PER_VERTEX = 3;                                                 // number of coordinates per vertex in this array

    static float squareCoords[] = {
             1.0f, 0.0f, 0.0f,                                                              // point0 : bottom right
             0.0f, 0.0f, 0.0f,                                                              // point1 : bottom left
             1.0f,  1.0f, 0.0f,                                                             // point2 : top right
             0.0f,  1.0f, 0.0f };                                                           // point3 : top left

    static float textureCoords[] = {
            1.0f, 1.0f,                                                                     // point0 : top right
            0.0f, 1.0f,                                                                     // point1 : top left
            1.0f, 0.0f,                                                                     // point2 : bottom right
            0.0f, 0.0f };                                                                   // point3 : bottom left

    private static Sprite reference = null;

    public static Sprite getInstance() {
        if(reference == null){
            reference = new Sprite();
        }
        return reference;
    }

    public int initialize(int resId) {

        ByteBuffer bb = ByteBuffer.allocateDirect(squareCoords.length * 4);                 // initialize vertex byte buffer for shape coordinates
        bb.order(ByteOrder.nativeOrder());                                                  // (# of coordinate values * 4 bytes per float)
        vertexBuffer = bb.asFloatBuffer();
        vertexBuffer.put(squareCoords);
        vertexBuffer.position(0);

        ByteBuffer tb = ByteBuffer.allocateDirect(textureCoords.length * 4);                // initialize texture byte buffer for texture coordinates
        tb.order(ByteOrder.nativeOrder());                                                  // (# of coordinate values * 4 bytes per float)
        textureBuffer = tb.asFloatBuffer();
        textureBuffer.put(textureCoords);
        textureBuffer.position(0);

        int vertexShader = OpenGLRenderer.loadShader(                                       // prepare shaders and OpenGL program
                GLES20.GL_VERTEX_SHADER,
                vertexShaderCode);
        int fragmentShader = OpenGLRenderer.loadShader(
                GLES20.GL_FRAGMENT_SHADER,
                fragmentShaderCode);

        mProgram = ShaderCompiler.createProgram(                                            // create OpenGL program executables
                vertexShader,
                fragmentShader,
                new String[]
                        {"aPosition", "aTexCoordinate"});

        return TextureLoader.loadTexture(resId);                                             // load the texture
    }

    public void preDraw(int resId, float[] viewMatrix){
        mTextureDataHandle = resId;
        mModelView = viewMatrix;
        GLES20.glUseProgram(mProgram);                                                      // Add program to OpenGL environment

                                                                                // Set program handles for drawing.
        mMVPMatrix = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");                   // get handle to shape's transformation matrix
        mPositionHandle = GLES20.glGetAttribLocation(mProgram, "aPosition");                // get handle to vertex shader's vPosition member
        int mTextureUniform = GLES20.glGetUniformLocation(mProgram, "uTexture");            // get handle to fragment shader's uTexture member
        int mTextureCoordinate = GLES20.glGetAttribLocation(mProgram, "aTexCoordinate");    // get handle to vertex shader's aTexCoordinate member

        GLES20.glActiveTexture(GLES20.GL_TEXTURE0);                                         // Set the active texture unit to texture unit 0.
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mTextureDataHandle);                     // Bind the texture to this unit.
        GLES20.glUniform1i(mTextureUniform, 0);                                             // Tell the texture uniform sampler to use this texture
                                                                                // in the shader by binding to texture unit 0.

        GLES20.glEnableVertexAttribArray(mPositionHandle);                                  // Enable a handle to the triangle vertices
        int vertexStride = COORDS_PER_VERTEX * 4;                                           // 4 bytes per vertex
        GLES20.glVertexAttribPointer(                                                       // Pass in the triangle coordinate data
                mPositionHandle, COORDS_PER_VERTEX,
                GLES20.GL_FLOAT, false,
                vertexStride, vertexBuffer);

        GLES20.glEnableVertexAttribArray(mTextureCoordinate);                               // Enable a handle to the texture vertices
        int mTextureCoordinateDataSize = 2;                                                 // How many values are in each Coordinate
        GLES20.glVertexAttribPointer(                                                       // Pass in the texture coordinate information
                mTextureCoordinate, mTextureCoordinateDataSize,
                GLES20.GL_FLOAT, false,
                0, textureBuffer);

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

    }

    public void move(float x, float y) {
        Matrix.translateM(mModelView, 0, x, y, 0f);                                        // Move the sprite in X and Y directions
    }

    public void rotate(float theta) {
        Matrix.rotateM(mModelView, 0, theta, 0f, 0f, 1.0f);                                // Rotate the sprite CW or CCW
    }

    public void scale(float width, float height) {
        Matrix.scaleM(mModelView, 0, width, height, 0f);                                   // Shrink or Expand the sprite
    }

    public void draw(){
        GLES20.glUniformMatrix4fv(mMVPMatrix, 1, false, mModelView, 0);                    // Apply the projection and view transformation
        GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP,0,4);                                 // Start at point 0 and draw 4 vertices
        GLES20.glDisableVertexAttribArray(mPositionHandle);                                // Disable vertex array
    }

```

**Space class**

```
public class Space {
    private int mTextureDataHandle;
    private float[] mMVPMatrix = new float[16];             // mMVPMatrix is an abbreviation for "Model View Projection Matrix"

    private float mCenterX;
    private float mCenterY;
    private float mWidth      = 1.0f;
    private float mHeight     = 2.0f;
    private float mRotation   = 0.0f;

    private World mWorld;
    private Sprite mSprite = Sprite.getInstance();

    public Space(World world){
        mWorld = world;
        initialize();
    }

    public void initialize() {
        mTextureDataHandle =
            mSprite.initialize(R.drawable.space);           // load the texture
    }

    public void update(float[] viewMatrix){
        mMVPMatrix = viewMatrix;

        if( mCenterY <  -1.0f) {                            // If the texture has completely scrolled of screen
             mCenterY = 0.0f + ( mCenterY + 1.0f);          // reset the texture to original position
        }
        mCenterY -= 1.0f * mWorld.getDeltaTime();           // Move the Y-value of each vertex by this amount
    }

    public void draw() {
        mSprite.preDraw(mTextureDataHandle, mMVPMatrix);

        mSprite.move(mCenterX, mCenterY);
        mSprite.rotate(mRotation);
        mSprite.scale(mWidth, mHeight);

        mSprite.draw();
    }

}

```

**Ship class**

```
public class Ship {
    private int mTextureDataHandle;
    private float[] mMVPMatrix = new float[16];                     // mMVPMatrix is an abbreviation for "Model View Projection Matrix"
    private float mCenterX  =  0.5f;
    private float mCenterY  =  0.48f;
    private float mWidth    =  0.08f;
    private float mHeight   =  0.1f;
    private float mRotation =  0.0f;
    public  float mDeltaTime;

    private Sprite mSprite = Sprite.getInstance();
    private Collider hitbox;

    public Ship() {
        hitbox = new Collider(mCenterX,mCenterY,mWidth, mHeight);
        initialize();
    }

    public void initialize() {
      mTextureDataHandle = mSprite.initialize(R.drawable.ship);
    }

    public void update(float shipX, float shipY, float deltatime, float[] viewMatrix){
        mDeltaTime = deltatime;
        mMVPMatrix = viewMatrix;

        if(shipX > 0) {
            if(shipX > mCenterX && mCenterX < 0.6){
                mCenterX += ((shipX))*deltatime;
            }
        } else {
            if(shipX < mCenterX && mCenterX > -0.6) {
                mCenterX -= ((-shipX))*deltatime;
            }
        }

        if(shipY > 0) {
            if(shipY > mCenterY && mCenterY < 0.88){
                mCenterY += ((shipY))*deltatime;
            }
        } else {
            if(shipY < mCenterY && mCenterY > -0.88) {
                mCenterY -= ((-shipY))*deltatime;
            }
        }
        hitbox.update(mCenterX,mCenterY,mWidth, mHeight);
    }

    public void draw() {
        mSprite.preDraw(mTextureDataHandle, mMVPMatrix);

        mSprite.move(mCenterX, mCenterY);
        mSprite.rotate(mRotation);
        mSprite.scale(mWidth, mHeight);

        mSprite.draw();
    }

    public float getCenterX() { return mCenterX; }

    public float getCenterY() { return mCenterY; }

    public float getWidth() { return mWidth; }

    public float getHeight() { return mHeight; }

    public Collider getCollider() {
        return hitbox;
    }

```

Thanks for any advice / guidance! If you need to know more just comment and I will be happy to oblige.

# Answer
Here's what I think is happening: the matrices in your static singleton sprite class (say that three times fast) -- specifically the model-view matrix -- is being modified on drawing every sprite without being reset to how it was before the modification. As such, any transformation you perform for one object is also applied to any subsequently drawn object in that render cycle.

What you might want to do is have a matrix stack, like in legacy OpenGL. Before you transform the model-view matrix, you copy it and push it to a stack. After you've drawn the sprite, you pop it from the stack to revert all transformations, and then move on to the next sprite.
> 1 votes

---
Tags: opengl, android, graphics, sprites, software-engineering
---


title: DX11 Camera not working properly

text:
# Question
Title: DX11 Camera not working properly
I'm currently trying to implement a ArcBall Camera which should fly around a given XMFLOAT3 position stored in a cb with a spezified distance to the position. I used the code from Allen Sherrod for this but the constant buffer that should pass the viewmatrix and the second one for the position to the shaders doesn't update. Any ideas?

This should return the view mat:

```
    XMMATRIX ArcCamera::GetViewMatrix()
{
    XMVECTOR zoom = XMVectorSet(0.0f, 0.0f, distance_, 1.0f);
    XMMATRIX rotation = XMMatrixRotationRollPitchYaw(xRotation_, -yRotation_, 0.0f);

    zoom = XMVector3Transform(zoom, rotation);

    XMVECTOR pos = XMLoadFloat3(&position_);
    XMVECTOR lookAt = XMLoadFloat3(&target_);

    pos = lookAt + zoom;
    XMStoreFloat3(&position_, pos);

    XMVECTOR up = XMVectorSet(0.0f, 1.0f, 0.0f, 1.0f);
    up = XMVector3Transform(up, rotation);

    XMMATRIX viewMat = XMMatrixLookAtLH(pos, lookAt, up);

    return viewMat;
}

```

The rotation (xRotation, yRotation) increases every frame.

The shaders:

```
Texture2D colorMap : register( t0 );
SamplerState colorSampler : register( s0 );

cbuffer cbChangesEveryFrame : register( b0 )
{
    matrix worldMatrix;
};

cbuffer cbNeverChanges : register( b1 )
{
    matrix viewMatrix;
};

cbuffer cbChangeOnResize : register( b2 )
{
    matrix projMatrix;
};

cbuffer cbCameraData : register( b3 )
{
    float3 cameraPos;
};

struct VS_Input
{
    float4 pos  : POSITION;
    float2 tex0 : TEXCOORD0;
    float3 norm : NORMAL;
};

struct PS_Input
{
    float4 pos  : SV_POSITION;
    float2 tex0 : TEXCOORD0;
    float3 norm : NORMAL;
    float3 lightVec : TEXCOORD1;
    float3 viewVec : TEXCOORD2;
};

PS_Input VS_Main( VS_Input vertex )
{
    PS_Input vsOut = ( PS_Input )0;
    float4 worldPos = mul( vertex.pos, worldMatrix );
    vsOut.pos = mul( worldPos, viewMatrix );
    vsOut.pos = mul( vsOut.pos, projMatrix );

    vsOut.tex0 = vertex.tex0;
    vsOut.norm = mul( vertex.norm, (float3x3)worldMatrix );
    vsOut.norm = normalize( vsOut.norm );

    float3 lightPos = float3( 0.0f, 500.0f, 50.0f );
    vsOut.lightVec = normalize( lightPos - worldPos );

    vsOut.viewVec = normalize( cameraPos - worldPos );

    return vsOut;
}

float4 PS_Main( PS_Input frag ) : SV_TARGET
{
    float3 ambientColor = float3( 0.2f, 0.2f, 0.2f );
    float3 lightColor = float3( 0.7f, 0.7f, 0.7f );

    float3 lightVec = normalize( frag.lightVec );
    float3 normal = normalize( frag.norm );

    float diffuseTerm = clamp( dot( normal, lightVec ), 0.0f, 1.0f );
    float specularTerm = 0;

    if( diffuseTerm > 0.0f )
    {
        float3 viewVec = normalize( frag.viewVec );
        float3 halfVec = normalize( lightVec + viewVec );

        specularTerm = pow( saturate( dot( normal, halfVec ) ), 25 );
    }

    float3 finalColor = ambientColor + lightColor * diffuseTerm + lightColor * specularTerm;

    return float4( finalColor, 1.0f );
}

```

Must I update all subresources and stuff before every time I call the context's draw method to render every my objects by the way?

# Answer
You are doing more than you should to generate your arc ball matrix. The code below should be enough for your need.

```
DirectX::XMMATRIX ComputeArcBallViewMatrix(DirectX::XMVECTOR origin,float distance,float yaw,float pitch,float roll = 0.f) {
    auto rotation = DirectX::XMMatrixRotationRollPitchYaw(pitch,yaw,roll);
    auto offset = DirectX::XMVectorScale(rotation.r[3],-distance); // assuming camera see positive Z, move back in camera axis
    offset = DirectX::XMVectorAdd(offset,origin); // camera to center of interest offset
    rotation.r[3] = DirectX::XMVectorSetW(offset,1.f); // finalize the cam to world
    return DirectX::XMMatrixInverse(nullptr,rotation); // invert to get world to cam from cam to world
}

```
> 1 votes

---
Tags: camera, directx11, matrix
---


# Question
Title: Gamemaker studio - Rooms Object doesn't stick inside the square grid
I keep trying to put an object into the square of the grid but the object keeps going to the top corner of the square; also I can't place multiple objects by grabbing the 4 point on the vertex of the object. Here is a screen shot:

Thanks!

# Answer
> 1 votes
Possible ways:

1. Change `Sanp X` and `Snap Y` from `32` to `16`, place objects and then change back to `32`.
2. Move center of sprite to position `0, 0`.
3. Shift all objects (all objects in the room) using 4th icon of the room editor (arrow right).

For place mulitple objects you need select an object, press `Shift` \+ `Ctrl` and then use left mouse button.

---
Tags: game-maker
---


# Question
Title: In Unity, is there a way to Set a new MeshRenderer?
Here is what I want to do in Unity for a given `GameObject go = new GameObject()`. I want to create a `MeshRenderer`, change its properties and only in the end set it as the component of `go`. For instance:

```
MeshRenderer newmeshrenderer;
(...) //do stuff with newmeshrenderer
go.AddComponent<MeshRenderer>() = newmeshrenderer;
(or)
go.GetComponent<MeshRenderer>(newmeshrenderer);

```

But both way fail. What is the correct way of setting a MeshRenderer previously created to be the MeshRenderer of an object?

# Answer
> 3 votes
You'd do this in the opposite order. Rather than:

1. Create
2. Modify
3. Attach to GameObject (there's no way provided to do this)

the order is:

1. Create and attach to GameObject (one fused step)
2. Modify

Like so:

```
GameObject go = new GameObject();
MeshRenderer newmeshrenderer = go.AddComponent<MeshRenderer>();
// Do stuff with newmeshrenderer, eg...
newmeshrenderer.sharedMaterial = theAwesomeMaterial;
newmeshrenderer.shadowCastingMode = ShadowCastingMode.off;
// etc.

```

The MeshRenderer doesn't actually do anything until the script finishes and the next frame is rendered, so there's no harm in configuring it in-place like this.

If you want to apply a MeshRenderer with identical settings to many GameObjects, the best way is to create a convenience method for yourself:

```
void AddAndConfigureMeshRenderer(GameObject recipient)
{
    MeshRenderer mr = recipient.AddComponent<MeshRenderer>();
    // Configure mr the way you want it...
    mr.sharedMaterial = theAwesomeMaterial;
    //etc..
}

```

Then you can call this repeatedly, passing each GameObject you want to attach this custom MeshRenderer to. You could also add parameters if you want to be able to do this with multiple distinct MeshRenderer configurations.

# Answer
> 2 votes
It should work like the example on the Scripting API for AddComponent http://docs.unity3d.com/ScriptReference/GameObject.AddComponent.html

```
MeshRenderer mr = gameObject.AddComponent("MeshRenderer");
(...) //do stuff with mr

```

---
Tags: unity, c#, game-component
---


title: Lerp velocity in specific time

text:
# Question
Title: Lerp velocity in specific time
How to lerp velocity to 0 in specific time? For example in two seconds? I need this for jumping.

```
velocity.Y = MathHelper.Lerp(velocity.Y, 0, [time]);

```

# Answer
> 1 votes
```
float Timer = 2f;
float TIMER = 2f;
float StartVelocity = 10;
float EndVelocity = 0;

void Update()
{
     float elapsed = (float)gameTime.elapsedSecondsOrWhatever;

     Timer -= elapsed;
     if (Timer < 0)
         Timer = 0;

     velocity.Y = MathHelper.Lerp(EndVelocity, StartVelocity, Timer/TIMER);
}

```

# Answer
> 0 votes
Your question is vague (could you please elaborate?), so I'll assume that you don't know how lerping works and that you don't have access to the math function, then you can write your own like this:

```
float lerp( float value1, float value2, float alpha, float range ){

  alpha = alpha/range;

  if( alpha < 0 )
    alpha = 0;
  if( alpha > 1 )
    alpha = 1;

  return value1 + (alpha) * (value2-value1);
}

```

Optionally, using alpha blending:

```
return (1-alpha) * value1 + alpha * value2;

```

Then, you can call

```
velocity.y = lerp( velocity.y, 0, delta_time, 2.0);

```

---
Tags: c#, xna, lerp
---


# Question
Title: How should I apply Ambient Occlusion from greyscale AO maps?
I've seen many tutorials on SSAO, but none for simple ambient occlusion maps.

I can see myself working things out alone, as AO maps are simple greyscale maps that indicate where there should be more lighting and where less, right? Something like

```
float ao = texture(ambientOcclusionMap, uvCoords);
vec3 lighting = ambient + (diffuse + specular) * ao;

```

Is there something more to it?

# Answer
> 3 votes
Correct approach is to multiply ambient component with AO:

```
vec3 lighting = ambient * ao + diffuse + specular;

```

\** *it is not a coincidence, that both items have the the word "ambient" in them ;-)*

---
Tags: shading, ambient-occlusion
---


title: How to generate a city street network?

text:
# Question
Title: How to generate a city street network?
I would like to create a city generator for a game, but I am facing a problem at the very start of the generation: the road system.

As it is a medieval world, I don't want a grid plan like many modern cities. I would ideally prefer a pseudo-random generation of large avenues and smaller streets, where it could be possible to get lost, but with still some logic - not a complete labyrinth.
Something that would look like a naturally grown town.

In order to keep it simple, let's say my cities would be on flat and stable terrains, without any river-crossing or relief problems. I could try to integrate it to a solution after.

I didn't decide of a precise size or disposition for my cities, so if you have a solution that would work only with cities of a precise form (square, circle, rectangle etc), I would take it.

# Answer
> 23 votes
A good place to start with procedural city generation is Parish and Müller's Procedural Modeling of Cities. Their paper presents an L-System in which rules concerning population density & road patterns (rectangular grid, radial & least elevation change) are combined and then fixed to accommodate local constraints such as water fronts & road aesthetics. While the results of this system are impressive, it has been criticized as being unnecessarily complicated. Barrett's alternative solution is restated in Rudzicz's Spare Parts dev blog as follows:

* maintain a list of "proposed" roads
* evaluate them in some order
* if they are acceptable (with or without some minor modifications)
* store each accepted road while "proposing" a handful more branching from it

This approach removes most of the symbol rewrite housekeeping inherit in Parish and Müller's L-System. You can see an demo of this approach here.

A benefit of this approach is that it is city shape agnostic - you can add outline constraints as needed, so your city shape can be determined by your game design needs rather than the algorithm. Depending on your city size, this might be good enough as is. Here's a result from the above demo with a segment limit of 100:  But if you need something big, you may have trouble; here's a result with a segment limit of 500:

In part, you can adjust this by changing the road branching rules, avoiding 90 degree angles, etc. If your layout is still too regular, here's my correction:

Transform your city grid into a graph where each street is an edge & each intersection is a node. Next, use whatever algorithm you prefer to convert the graph into a maze. Here's the last example turned into a maze:

Now the output has the opposite problem, it's too maze like. But now we can apply a couple of techniques from the Secret Workings of Jamis Buck's Dungeon Generator. First, increase the sparseness by removing some dead end corridors. Next, increase the connectivity by adding in roads that create loops (i.e. introduce cycles to the graph). Here's an example result:

Note: it is possible to achieve the same final result directly from the earlier grid oriented layout stage (before generating the maze), by only apply edge removals to the city grid. The problem with that approach is you must ensure removing an edge doesn't partition the city thereby making portions unreachable.

# Answer
> 6 votes
If you look for medieval/old city plans on Google you'll find many different variations, mostly based on city origins (e.g. random settlement vs. organized military position).

I assume you're looking for a more naturally grown/chaotic settlement.

For these I'd try an approach like this:

* Start out with a main road going from one end to the other (and ideally connecting some other settlements. If you want, create a third road so you get a junction on which to start your settlement.
* Place some houses along the road (on one side only).
* Now widen that road along the houses and add a major landmark on the other side (typically a church, but this could also be some mill or similar). This is going to be your center/marketplace.
* Now pick two positions outside the area with the houses and create a new road enclosing the houses.
* Optionally create some smaller allies between houses connecting the old and new road.
* Now repeat until you're happy with your "core":
    + Add a few more houses.
    + Add another road enclosing them.
    + Add back alleys connecting the roads.
* Once you're happy with that, you're done. If it's supposed to be a town, surround it with walls and repeat the last steps a few more times, adding additional houses outside the walls.

# Answer
> 4 votes
First of all, there are loooooot of ways to do procedural generation and none of them is easy at all, i will make kind of approach to how you could make it work, is up to you take it, modify it or discard it.

Will pseudo-code in JS as it's easier to understand.

1º define an entry point, as you want to build a medieval city we gonna start with a square, so lets say your town will have 300 squared units and the square will be in the middle of it (represented with an X).

```
       300
________________
|               |
|               |
|               | 300
|       X       |
|               |
|               |
|_______________|

const square = [ 150, 150 ];

```

2º now we will the avenues, there will be a random number of them, they will be straight and will start from the middle square or from other avenues

```
let avenues = [] // will contain start and end [[sx,sy],[ex,ey]]
const n_avenues = RANDOM(4, 8); // number of avenues
const n_av_from_square = RANDOM(0, avenues); // starting in the square

for av in av_from_square
  avenues.push(square, [RANDOM(0, 200) + 100, RANDOM(0, 200) + 100])
  // we want avenues to have, at least 100 units length, thats why we randomize just te last 200 units of the whole town size

```

This should give you a square and couple main streets

```
       300
________________
|   \\          |
|    \\         |
|     \\        | 300
|       X=====  |
|               |
|               |
|_______________|

```

Now we have to set the avenues that doesn't start in the main square, they will intersect the other avenues

```
for av in (n_avenues - av_from_square){
  const av_to_intersect = avenues[RANDOM(0,avenues.length)];

  //check av_to... and get a perpendicular vector (explained bellow)
  av[0] = [ av_to_intersect[0][1], - av_to_intersect[0][0] ];
  av[1] = [ av_to_intersect[1][1], - av_to_intersect[1][0] ];

}

```

To get perpendicular vectors you have to swap the x,y cords and negate the new y:

> swiped == x: noswiped.y, y: -1 * (noswiped.x)

Right now you should have something similar to this, doesnt it look like a town? :P

```
       300
________________
|   \\  //      |
|    \\//  ||   |
|     \\   ||   | 300
|    //\X=====  |
|   //     ||   |
|          ||   |
|_______________|

```

3º now you only have to interconnect the avenues with short streets, also, you could spawn random squares all along the town and make the same as above for all of them, or just spawn small streets from some secundary squares, it's up to you.

Remember, the shortest your streets are, the chaotic the town looks like.

---
Tags: procedural-generation
---


# Question
Title: How to ensure a condition in a behaviour tree when processing following nodes?
Example tree (Source):

As far as I understood, a sequencer iterates over the children until one failed or all are successful. If one children returns "running", the sequencer will start to process from that child on the next tick.

Let's say "Do I have food?" takes longer than one tick because the AI has to walk to the fridge. When "Am I Hungry" was successful, it won't be processed anymore. Now while walking to the fridge, the hunger magically disappears. How do I prevent the tree from processing the other nodes even though I am not hungry anymore? Should every following node check the condition again? That doesn't seem to fit the idea of a behaviour tree.

How do I implement a condition that has to stay true while following nodes are processed?

# Answer
> 1 votes
Found an answer here.

I thought a behaviour tree should start at the last running node to start computation time but that lead to the problem stated in the article.

> Treating Running States
>
> One common question when implementing a Behavior Tree is that: what to do in the next tick after a node returned a running state? There are two answer to it: starting the graph traversal from the running node or starting it over from the first node.
>
> The major drawback of starting the tick at the node that returned the running state is that this node can take too much time running an action and, thus, avoiding the execution of most important behaviors. For instance, suppose a robot performing an action to follow a certain path; in the half way the robot finds a hole, but it cannot avoid it because the tree is running the action of path following.
>
> Therefore, the best option is always start over the tree, and if a most-important behavior wants to run, the previous node stops.

---
Tags: ai, behavior, tree
---


# Question
Title: How to enable depth test with QOpenGLWidget? It renders black screen
Currently I am writing a small application with Qt and OpenGl and I choosed `QOpenGLWidget` for rendering graphics.

That's how I declared my widget:

```
class GLWidget : public QOpenGLWidget, protected QOpenGLFunctions{
     // Methods, slots, e.t.c
}

```

And that's the constructor:

```
GLWidget::GLWidget(QWidget *parent) : QOpenGLWidget(parent)
{
    /* Tried this, it didn't help.
    QSurfaceFormat format;
    format.setDepthBufferSize(24);
    this->setFormat(format);
    */
}

```

In my init function I set `GL_CULL_FACE` and `GL_DEPTH_TEST`:

```
void GLWidget::initializeGL()
{
    /* Some initialization stuff regarding the scene */

    glEnable(GL_CULL_FACE);
    glEnable(GL_DEPTH_TEST);
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

}

```

And I really don't know why the widget renders the black screen. Here are some pictures. First one: with disabled `GL_CULL_FACE` and disabled `GL_DEPTH_TEST`.

Second one: with enabled `GL_CULL_FACE` and disabled `GL_DEPTH_TEST`. Maybe it's not a good picture, but I can assure you, you can see some surfaces through the other.

Third one: with enabled `GL_CULL_FACE` and enabled `GL_DEPTH_TEST`. Actually, it doesn't matter if `GL_CULL_FACE` is enabled. Anyway it renders the black screen.

And here's the image without any shading just to show you that the model is fine.

I tried to set the format manually, but it didn't help. Still the black screen:

```
QSurfaceFormat format;
format.setDepthBufferSize(24);
this->setFormat(format);

```

Oh and yes, I set `glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);` at the beginning of my `paintGL()` function.

# Answer
> 0 votes
First of all, please give a complete source code of (small error-prone version of) your project, because this kind of problem depends on lots of things.

However, there are lots of reasons that can make unwanted black screen, most common mistakes that I can guess in your case, are:

* mathematics mistakes
    + camera matrix (in your case see your clipping range)
    + shader mistakes
* scissor test (check if your scissor is correctly working)
* soon or late clearing of framebuffer

---
Tags: opengl, c++, depth-buffer, qt, depth
---


# Question
Title: Type `UnityEngine.UI.Text' does not contain a definition for `Text'
I came from Unreal Engine 4. I created a script, and I keep getting an error:

> Assets/scripts/UpgradeManager.cs(17,18): error CS1061: Type \`UnityEngine.UI.Text' does not contain a definition for \`Text' and no extension method \`Text' of type \`UnityEngine.UI.Text' could be found (are you missing a using directive or an assembly reference?)

My code is:

```
using UnityEngine;
using System.Collections;

public class UpgradeManager : MonoBehaviour {

    public Click click;
    public UnityEngine.UI.Text iteminfo;
    public float cost;
    public int count = 0;
    public int clickpower;
    public string itemName;
    public float _newCost;

    void Update()
    {
        iteminfo.Text = itemName + "/nCost: " + cost + "/nPower: +" + clickpower;
    }

    public void PurchaseUpgrade()
    {
        if (click.money >= cost)
        {
            click.money -= cost;
            count += 1;
            click.moneyperclick += clickpower;
            cost = Mathf.Round(cost * 1.15f);
            _newCost = Mathf.Pow(cost, _newCost = cost);
        }

    }
}

```

# Answer
> 3 votes
Identifiers in C# are case sensitive. You want `iteminfo.text` not `iteminfo.Text`

You can verify in the docs that the UnityEngine.UI.Text.text property is all-lowercase.

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


# Question
Title: Detecting Collision in Next Step when Collider is rotating
In my Gamemaker: Studio game, I have a collision script for my enemy. The enemy is an alien, `oSwarmer`, moving through space which is also filled with drifting, spinning bits of debris. Some debris barely spins at all, others spin quite fast.

When `oSwarmer` executes the following collision script every step. As you can see, if it is about to come into contact with some debris (here called `oSolid`) it changes direction away from the colliding `oSolid` and maintains its original speed.

```
SolidTouching = instance_place(x + hspeed, y + vspeed, oSolid)

if instance_exists(SolidTouching) {

OriginalSpeed = CurrentSetSwarmerSpeed

if speed > 0 {
direction = direction - random_range(130,220)
} else if speed <= 0 {
direction = point_distance(x,y,SolidTouching.x,SolidTouching.y) - random_range(130,220)
}
speed = OriginalSpeed
}

```

However, sometimes when coming into contact with an `oSolid`, they spin madly on the spot. I've noticed that this seems to occur when the `oSolid` is spinning. These creatures do not move very fast, so their initial 'bounce' is not enough to carry them out of the path of the rest of the `oSolid` which is coming around to meet them. I think they then get caught in a loop of constantly trying to move in the opposite direction to the colliding `oSolid` (which is changing every step because it is spinning).

What I cannot work out is how to remedy this. Does anybody have a suggestion?

# Answer
When working with `direction` and `speed`, if you change the value of the former you don't need to update the value of the latter, as GM:S automatically updates `hspeed` and `vspeed` in order to reflect the changes on the speed vector upon its separate components. Also, you can change the value of `speed` making it both greater or smaller than zero, but if you only change values of `hspeed` and `vspeed` you'll find out `speed` will always evaluate to a number greater than or equal to zero. Just sayin'.

That said, you need to make your `oSwarm` avoid space debris by changing smoothly its moving direction. I think there are countless ways to achieve this, so we can focus on an easy solution.

But first, you talked about `oSwarm`s spinning madly when colliding with certain debris. I think that happens because when using `random_range()` you are changing their `direction` using high values, and that may result in jittery movements. Try using smaller values, like `random_value(30,60)` before to proceed with reading my answer.

So, you can test when `oSwarm` collides with an `oSolid` in *Step Event* and change your alien moving direction according to its relative position with the debris:

```
// Check collision
var my_solid = instance_place(x+hspeed,y+vspeed);

// Support variables
var my_dir, my_angle, my_prod;

// Did collision occur?
if (my_solid!=noone)
{
    my_dir = point_direction(x,y,my_solid.x,my_solid.y);  // Direction toward object
    my_angle = ((direction+360)+(my_dir+360))%360;        // Angle between my_dir and direction
    my_prod = direction*my_dir*sin(degtorad(my_angle));   // Cross product

    // Test cross product
    if (my_prod>=0)
        direction -= irandom_range(0,30);  // Better steer clockwise
    else
        direction += irandom_range(0,30);  // Better steer counter-clockwise
}

```

If you need further help with this code, just comment and I'll respond.
> 0 votes

# Answer
May no be a greater answer to your question, but have you tried using GM:S's physics engine?

You can simply assign physics fixtures to the objects and let the program do the collision for you, if these two objects are the only ones you want collision with, you can just give physics properties to these two and everything else stay in your original design.

The coding would look something like this for `oSwarmer` in the "collision" event:

```
if phy_speed>0.1

{
phy_rotation+=random_range(130,220)
}

if phy_speed<=0.1

{
SolidTouching=instance_place(x,y,oSolid)
direction = point_direction(x,y,SolidTouching.x,SolidTouching.y) - random_range(130,220)
}

```
> 1 votes

---
Tags: collision-detection, game-maker, collision-prediction
---


# Question
Title: Moving autonomous robot form one location to another based on array
I have a 3D model of a house, and I want an autonomous robot to move from 1 object in this house to the next one. I have it moving to the first, but it won't move to the second one. This is my code:

```
using UnityEngine;
using System.Collections;

public class MoveTo : MonoBehaviour {

public Transform[] goals;

void Start () {
    NavMeshAgent agent = GetComponent<NavMeshAgent> ();
        agent.destination = goals[0].position;

    if (agent.transform.position == goals[0].position) {
        agent.destination = goals[1].position;
    }

}
}

```

I'm a complete beginner in code, please keep that in mind :)

# Answer
The `Start` method is only executed once at start and the NavmeshAgent won't start moving the object before the `Start` method finished. The moving happens between calls to `Update`.

So check if you reached the destination in your `Update` method, not your `Start` method.

I would also recommend you to use `agent.remainingDistance` to check if the destination is reached. Comparing positions for equality is quite error-prone because even though the == operator for Vector3 is overloaded for returning true even when the positions are just *almost* identical, Unity's definition of *close enough* might be different than yours. *If* you want to compare positions, at least do it by checking if their distance is smaller than what you would consider close enough for "being there".
> 0 votes

---
Tags: unity, c#, scripting, navmesh
---


# Question
Title: Is There a Way To Keep Precision When Transforming GameObjects
I've seen this issue before, but it's never been a particular issue for me until today. I have each "room" of a dungeon created with a class script that contains details of that room. During the process of building the dungeon, rooms may be mirrored or rotated. When I rotate the y-axis, it updates properly the first time, going from `0` to `180`, but if I mirror it back and forth, it begins to get very small variances away from true `0` and `180`. Over time, this could impact some things. The code I'm using to do this is:

```
    public void RoomMirror()
    {
        transform.Rotate(0, (transform.localRotation.y==180) ? 0.0000f : 180.0000f, 0);
        Mirror = !Mirror;
        Swap(ref _east, ref _west);
    }

```

I added the four places in the float to try to overcome this issue, but it doesn't seem to be making any difference. Thanks!

# Answer
As a common rule you should always rebuild that kind of matrix instead of repeatedly applying transforms, or you get the kind of cumulative error you're seeing =) Every new transform and the error gets worse and worse, faster and faster.

This is because floating point numbers are imprecise and a matrix has many multiplications applied to it at each new transform. You suspected this already because of adding the 4 places to the float (which didn't do anything for you here).

How floats work is a tidy little subject to read up on, you can get through several sources both within and without game development in an evening.
> 2 votes

# Answer
```
    public void RoomMirror()
    {
        Vector3 temp = transform.rotation.eulerAngles;
        if (temp.y == 0f)
        {
            temp.y = 180.0f;
        }
        else
        {
            temp.y = 0.0f;
        }
        transform.rotation = Quaternion.Euler(temp);
        Mirror = !Mirror;
        RoomMirror(ref _east, ref _west);
    }

```

This seems to have resolved the issue, though I'm not sure it's the best approach. I may mark this as an answer at some point, unless someone can show me an error in logic or a way to do this that would be cleaner.
> -1 votes

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


# Question
Title: What Collider should I use for my Player object?
I am making a 3rd person game with a simple orbit cam and it works fine most of the time, but since I have a box collider and I walk across an uneven surface, the player tends to tip over. How should I set it up so the player would not tip over anymore?

# Answer
> 2 votes
You should use a capsule collider, because it doesn't have edges and works great and also you could apply some constraints in the `Rigidbody`. It's common to apply.

Freeze position in: x and z

Freeze rotation in: x, y, and z

I hope that this will solve your problem.

Cheers!

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


title: RPG Maker MV and outside screenshots

text:
# Question
Title: RPG Maker MV and outside screenshots
I'm looking into starting a project on RMMV; a medieval fantasy with a heavy focus on storytelling. For part of that storytelling, I was hoping to include "cutscenes" composed on images and text to illustrate important events. I could hire an artist online but I would need a lot of images to accomplish my ends. Now, I've watched my wife play "The Sims" franchise for awhile now, and that game is heavily and widely modded by its fanbase, and a large focus on that is historical in theme. If I were to use a posing mod to illustrate scenes from my game in "The Sims 2" and then edit them to my liking, would I be facing any legal troubles from EA Games? I would certainly credit the game and any modders, but I wonder if that would be enough, especially if I were to attempt a commercial release.

# Answer
Yes, you can face legal issues.

You should talk to a lawyer to review the specific details of your specific scenario, but the assets in The Sims 2 are protected by copyright, and some (such as those relating to product or brand identification) may further be covered by trademark as well.

Copyright, in particular, is the *right of an author of a work to determine* who can make reproductions and derivative works and how. In particular, that means "giving credit" is irrelevant. Copyright is not the right to be credited, it's the right to have the say over who uses the work. Also note that *non*-commercial distribution doesn't save you either; it simply makes it less likely you'll be seen, but it doesn't make it any less illegal.

Using assets from The Sims 2 to create your game would be a violation of that copyright unless you obtain permission from the rights holder. If there are any trademarks involved, such as logos or sub-licensed trademarks like Pepsi logos on shirts, you'd be further in violation.

Modding a game is quite different from taking assets from a game (which may happen to be more easily accessible due to the game being designed for modding) and re-using them elsewhere. In particular, the EULA for a game explicitly supporting mods usually permits you to use the game's assets for the limited purpose of creating a mod, but restricts your ability to effectively do anything else with those assets (like take them out to another game).

The cost of hiring an artist is negligible compared to the cost, stress, and time/work lossage that results from a legal battle. Hire the artist, or get a tool like MakeHuman (which is free!) and learn to do it yourself.
> 3 votes

---
Tags: legal
---


# Question
Title: How do I use the morpher modifier in 3dsmax to morph into several targets simultaneously?
I have a 3D-Face from Facegen here including all necessary phenomes' positions. But these targets are separated into upper, lower teeth, sock and eyes. How do I combine them for the face to morph into each facial position at once?

# Answer
Simply clone a copy of your character's mesh, add a morpher modifier, and then apply all of the morphs you want combined into a separate morph channel. Set all of the morphs to 100%. Then collapse the character mesh's stack and tadaa, you have a single morph target with all of the morphs combined. Now apply this morph target to your original character and delete the cloned mesh if you don't need it anymore.
> 1 votes

---
Tags: animation, 3dsmax, face
---


title: Drag event inverts in landscape mode

text:
# Question
Title: Drag event inverts in landscape mode
I am developing an car game for android with an UI steering wheel to control the car. I'm following Answer example for the wheel rotation. This is the code to rotate the wheel.

```
rectT.localEulerAngles = Vector3.back * wheelAngle;

```

This code working completely fine in unity and in the portrait mode of actual device.

But in the landscape modeof actual devices , the rotation get inverted. Please help me to solve this problem. Thank you

# Answer
> -1 votes
You could maybe detect the orientation of the device and if its in landscape mode, it spins in the other direction.

```
if (portraitMode) {
   rectT.localEulerAngles = Vector3.back * wheelAngle;
} else {
   if (landscapeMode) {
       rectT.localEulerAngles = Vector3.forward * wheelAngle;
   }
}

```

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


title: Handling light bounding volume

text:
# Question
Title: Handling light bounding volume
So, i managed to do deferred shading like yesterday or 2 days ago. I got pretty big impact which causes my fps to drop from 1000fps to around 300~fps for 25 lights (after some optimization, i don't know if this is even normal lol).

Then i read about this bounding volume, so then i implemented this with stencil cubes and it is capable of bumping my fps to 400~fps. The problem is whenever i enter those bounding boxes, lighting for fragments inside the box is now gone. Like so:

I resize the bounding box to half of the size for testing. And i already disable `GL_CULL_FACE` when rendering those bounding volume cubes. Here is how i handle the rendering:

```
glEnable(GL_STENCIL_TEST);
glDisable(GL_CULL_FACE);
for (int i = 0; i < sizeof(lights) / sizeof(Light); i++) {
    glStencilFunc(GL_ALWAYS, 1, 0xFF);
    glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
    glStencilMask(0xFF);
    glClear(GL_STENCIL_BUFFER_BIT);

    // Bind and unbind vao & shaders here for stencil

    // Setting up matrices and uniforms for bounding volume cube
    glDrawArrays(GL_TRIANGLES, 0, 36);

    // Bind and unbind vao & shaders here for lighting

    glStencilMask(0x00);
    glStencilFunc(GL_EQUAL, 1, 0xFF);

    // Setting up uniforms for light's properties
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}
glEnable(GL_CULL_FACE);
glDisable(GL_STENCIL_TEST);

```

Though i don't think the code i supply above is where the problem lies. I think it is because the stencil only draws where the cubes is (the cubes walls) and not the volume inside of it.

Is there a way so that the stencil draws the volume too? Or perhaps a trick so that the lighting is still occur when i'm inside the bounding volumes?

Edit: I thought of checking cam position if it is inside those cubes, if yes then don't use bounding volume for that particular light. But i don't think that's the best solution here..

# Answer
> 0 votes
Okay, after some hours of research, i finally ran into this site which work exactly how i wanted.

> The techique works as follows:
>
> 1. Render the objects as usual into the G buffer so that the depth buffer will be properly populated.
> 2. Disable writing into the depth buffer. From now on we want it to be read-only
> 3. Disable back face culling. We want the rasterizer to process all polygons of the sphere.
> 4. Set the stencil test to always succeed. What we really care about is the stencil operation.
> 5. Configure the stencil operation for the back facing polygons to increment the value in the stencil buffer when the depth test fails but to keep it unchanged when either depth test or stencil test succeed.
> 6. Configure the stencil operation for the front facing polygons to decrement the value in the stencil buffer when the depth test fails but to keep it unchanged when either depth test or stencil test succeed.
> 7. Render the light sphere.

Though, this actually lower my fps a little somehow.. I got 100-200~fps for 125 lights now and 300~fps for 25 lights..

---
Tags: opengl, lighting
---


# Question
Title: Autonomous robot - moving from 1 object to the next object
This question falls in line with my last question: Unity 3D - create autonomous moving robot in house + first person camera movement

**What I have**

I have a 3D model of a house; a first-person camera with movement through the house; a robot that autonomously moves.

**What I want**

I want the autonomously moving robot to search the house for certain objects. I have placed 4 guns (same model) in the house.

This is the code I have now. This works for 1 gun; not multiple game objects:

```
using UnityEngine;
using System.Collections;

public class MoveTo : MonoBehaviour {

public Transform goal;

void Start () {
    NavMeshAgent agent = GetComponent<NavMeshAgent>();
    agent.destination = goal.position;
  }
}

```

**What I want - extra**

If possible, I want it to communicate with the person navigating the "game" with the first-person camera. For example, if it finds a gun, I want it to say to the person "playing" the game: I found a gun. If it finds the next one: I found 2 guns; I found 3 guns; etc etc.

For that, I used the following code for the player:

```
using UnityEngine;
using System.Collections;

public class UGV : MonoBehaviour {

    public Player player; //assign this variable in the inspector, or using another method

    public void CallMethodBInPlayer(){
        if(player != null){
            player.MethodB();
        }
    }

    public void MethodA(){
        //do something (Robot)
    }
}

```

And the same for the robot (but changed accordingly).

I will be honest with you that I have very little understanding of programming or Unity. I want you to know I've been looking for an answer for many hours but even though the idea might be too complicated for me just yet, I still hope you can (and want) to help me :)

# Answer
To solve all of this problems you still have to write quite a lot of code. So this answer is just a general overview of what you need to do, not a complete implementation. When you need specific help with one of these points, feel free to ask it as a new question.

1. When you want multiple goals, you need to change `public Transform goal;` into an array of transforms by changing it to `public Transform[] goals;`. You can then assign as many goals as you want in the inspector.
2. Next you need to decide which of the goals to move to. Finding the ideal order to visit all the goals is a problem which is actually far more complicated than it looks at first glance. But a reasonable algorithm to get you going with a "good enough" order is to just move to the closest destination at first. How do you find which one is the closest? By creating one NavMeshAgent for each goal, call `CalculatePath` on each of them, see which one returns the shortest path and discard all the others. When you reached the chosen destination, reevaluate which remaining one is the closest now.
3. How do you define "finding a gun"? A possible definition could be "having an unobstructed direct line of sight". The method which can help you to find if there is such a line between the robot and the goal is the method `Physics.Linecast`.
> 1 votes

# Answer
You don't need to add the Guns via the inspector one by one. Just execute `FindObjectsOfType` at the start of your game:

```
Gun[] guns;

void Start () {
    guns = FindObjectsOfType<Gun> ();
    foreach (Gun gun in guns) {
        Debug.Log("Found " + gun.gameObject.name);
        //Now you can access their location with gun.gameObject.transform.position
    }
}

```

What do you mean by "talking to the player"?
You could make a GUI for that:

Set up the OK-Button to close (hide) the Message:

...and now you'll just have to add a little bit of code to the robot:

```
public UnityEngine.UI.Text playerMessage;
public GameObject panel;

public void showMessageToPlayer(string message){
    playerMessage.text = message;
    panel.SetActive (true);
}

```

Assign the two variables via the inspector and now the robot can show a text-message to the player by calling the `showMessageToPlayer`-method.
> 1 votes

---
Tags: unity, c#, 3d, movement, scripting
---


# Question
Title: Increment int in array - int i is out of scope?
This is my scenario:

I have a 3D model of a house, and an autonomously moving robot moving through the house picking up multiple objects. I have an array of 3 objects I want it to pick up, but I don't know how to make it move from item 1 (goals\[0\]) to item 2 (goals\[1\]) to item 3 (goals\[2\]). I do have it from item 1 to 2, but I don't know how to update the i value. It gives me an error and I don't know what to do.

**This is my code:**

```
using UnityEngine;
using System.Collections;

public class MoveTo : MonoBehaviour {

public Transform[] goals;

private bool printDone;
int i = 0;

void Start () {
    NavMeshAgent agent = GetComponent<NavMeshAgent> ();
    agent.destination = goals[i].position;
    printDone = false;

}

void Update () {

    NavMeshAgent agent = GetComponent<NavMeshAgent> ();
    if (agent.remainingDistance < 2 && !printDone) {

        print ("Found an item: " + goals [i].name + ". This is a " + goals [i].tag);
        printDone = true;
        agent.destination = goals [i + 1].position;
        int i = i + 1;
    }
}
}

```

the int i = i + 1 gives the bug: Assets/MoveTo.cs(26,29): error CS0136: A local variable named `i' cannot be declared in this scope because it would give a different meaning to`i', which is already used in a \`parent or current' scope to denote something else

Anyone knows how I can solve this and get what I want?

Thank you kindly!

# Answer
Its because you have declared `int i` two times. If you want to save new value change:

```
int i = i + 1;

```

to:

```
i = i + 1;

```
> 2 votes

---
Tags: unity, c#, 3d, scripting
---


title: 2d vector flips during rotation

text:
# Question
Title: 2d vector flips during rotation
I have a 2d game (C++ and SDL) and I want the player object rotate to follow the mouse. The player object and the mouse location are both stored in 2d vectors.

In order to have the player's rotation look nice, I applied this lerp code between the "current" and "future" angle.

This is the function i'm using below, it should be straightforward:

```
void Vector2D_LerpAngle(const Vector2D& future, const float& dt, Vector2D& current)
{
    float a = 0.0f, b = 0.0f, c=0.0f;

    Vector2D_GetAngleDegrees(future, a);
    Vector2D_GetAngleDegrees(current, b);

    c = (a*t + b * (1.0 - t) - b);

    Vector2D_RotateByDegrees(c, current);
}

```

This actually works great - until the player rotates past 0 degrees. Then, it suddenly rotates in the opposite direction for almost an entire circle.

The only way I've been able to find to fix this is adding logic to catch the special case of being within 0-360 degrees, but to do that properly I'm going to have to take the velocity of the mouse into account, and that's just going to be a pain. I feel like I'm probably missing something obvious here or else I'm doomed to failure with this particular method.

**edit:**

It turns out lerping the vectors themselves rather than the angle works. I should have just trusted the math.

```
void Vector2D_Lerp(const Vector2D& future, const float& t, Vector2D& current)
{
    current = future*t + current*(1.0f - t);
}

```

# Answer
Rather than fiddling with angles, you can use a cross-product to know in which direction you should rotate. Don't be scared by the theory dump : it's actually pretty simple to use!

Let C be `current` and F be `future`. They are both 3-dimensional vectors, with z = 0. Then the cross-product P = C×F has the following properties:

* Px = 0 and Py = 0;
* Pz = CxFy \- CyFx, which is rather easy to compute, but also:
* Pz = ||C||⋅||F||⋅sin θ, θ being the smaller directed angle from C to F;
* sin θ and θ have the same sign, unless θ = 180°.

In short: compute (C×F)z, look at its sign:

* \< 0, you need to turn right
* \> 0, you need to turn left
* = 0, you're either dead centered towards your goal, or facing exactly away.

In the zero case, you can know which situation you're in with the dot product, d = CxFx \+ CyFy:

* If d \> 0, the vectors face the same direction;
* If d \< 0, the vectors face away from each other;
* If d = 0, the vectors are orthogonal (but we don't care here).

I hope I managed to be clear enough :)
> 1 votes

---
Tags: 2d, rotation, vector
---


# Question
Title: How can I make an object visible only on the minimap in GameMaker?
I am making a game in which I have created a minimap using views. I want in the minimap (the copy of the world) to add an object, but I want it to be visible *only* from the minimap. Is there any way to do this?

Any help is much appreciated.

# Answer
> 0 votes
In the *Draw Event* of the object you want to draw in the minimap only, if the minimap has `view` index `1` (assuming the main `view` with index `0` is what the player is actually seeing) you can simply write:

```
// Draw event for minimap-only object
if (view_current==1)
{
    // Draw event for this object
    // for minimap only (view 1)
}
else
{
    // Draw onto any other view (only if needed)
}

```

This way the *Draw Event* of your object will draw only in the `view` with index `1`, your minimap.

# Answer
> 0 votes
Is it an object that exists in the game as well, even while it's not visible? If so then could you use that object to draw a sprite on the mini-map?

---
Tags: game-maker
---


# Question
Title: Is it cheaper to let each tile have its own collision?
I'm just now playing around with Tiled, and I think this is the way I'm going to go to create tilesets for my game maps, but I'm curious about the cost (memory/CPU) difference between setting a collision for a specific tile so that Tiled creates them all individually versus manually drawing collision polys around larger sections by hand. For instance:

By Tile:

Manual:

There are fewer polygons in the manual draw (4), and it's not terribly difficult to create them, but is there a benefit one way or the other?

# Answer
Depending on how collision is implemented, the per-tile boxes may actually be more efficient (in case the bodies are in a Quad Tree most of them are easily discarded, but in the second case it may check all the edges). I think the only real way to find out is to do some testing with huge maps (I doubt you'll notice any difference with such a small map).

You may also look into something in between. Merging tiles horizontally but not vertically, you'll still just have just rectangles but there will be less of them. That will definitely be more efficient than using many small boxes, and it will also avoid potential physics simulation issues where the edges meet.

Finally, you should probably look at avoiding all this manual work and try out Tiled2Unity. It can handle complex tile collision shapes and can merge them all together into various meshes as desired.
> 4 votes

---
Tags: unity, tiled
---


# Question
Title: How can I access the members of XMVECTOR?
So I have been reading these articles, and I find implementing them a trouble. Currently, all I am trying to do is add two vectors together, leaving my question more specifically this: How can I add specific members of two given vectors together? An example would be this:

```
XMVECTOR v1 = XMVectorSet(1.0, 2.0, 3.0, 4.0);
XMVECTOR v2 = XMVectorSet(1.0, 1.0, 1.0, 1.0);

```

Then I would need to be able to lets say add v1's third member (3.0) and v2's second member (1.0). How can I pull this off? I tried using:

```
v1.z += v2.x;

```

To no avail. Any help is very much appreciated.

# Answer
> 4 votes
DirectXMath's `XMVECTOR` is an opaque platform-optimal type that you can only manipulate via free functions, on x86 something akin to a `_m128`.

You can set/get individual elements with functions like `XMVectorSetZ`, but note that this is cumbersome for a reason, as such non-wide operations are likely to be more expensive than expected on SIMD types.

If you want a more traditional CPU-friendly type for extensive non-SIMD work, consider `XMFLOAT4` as it's more of a "struct of four floats" which you seem to desire.

You can always roundtrip between the types based on local needs with `XMLoadFloat4` and `XMStoreFloat4`.

# Answer
> 2 votes
You don't access the vector's members directly, you have to copy the vector to a XMFLOAT4 first:

```
XMVECTOR v2 = XMVectorSet(1.0, 1.0, 1.0, 1.0);
XMFLOAT4 v2F;    //the float where we copy the v2 vector members
XMStoreFloat4(&v2F, v2);   //the function used to copy

```

now you can access and manipulate the v2F members simply like so:

```
v2F.x = 4.5f;

```

when you are done, just copy back the v2F to v2:

```
v2 = XMLoadFloat4(&v2F);

```

---
Tags: c++, directx
---


# Question
Title: Unwanted highlight on far side of objects near the edges of the screen when using orthographic camera
I was creating a simple unity game with a sphere as a ball. The problem is that the ball face towards the camera origin renders material correctly but the one away from camera does not.  The ball has a standard material , the scene has directional light which faces in the camera's direction.The camera is orthographic and the background is solid.

Let me explain, in the material inspector window preview the ball is properly shaded from all sides as you can see. But in the game screenshot I have posted, the left half of the ball abruptly becomes lighter. Now this lighter shade is not because of the directional light or any other light source its because of the camera. because as I move near the camera center origin the original material shade returns but the farther I move the lighter shade nearly takes over half of the ball. I tried changing the camera rendering path to a vertex legacy lit and that solves the problem but I don't think that is the ideal solution. I am a newcomer to Unity and this is my first game. I tried going through the documentation but didn't find anything helpful. Any help will be greatly appreciated. :) .

# Answer
The default shaders in Unity 5+ use something called physically-based rendering. This means they try to model a number of quirks we observe in real materials, which aren't included by the Lambertian/Phong approximations that have been popular in games in the past.

One of those effects is Fresnel reflection, where the shiny reflection off of a surface becomes more intense at glancing angles.

These effects often look great when we're trying to model a realistic-looking scene, but when we try to inject non-realism, we can run into artifacts.

Here, the trouble comes from the combination of a physically-based material and an orthographic camera. Orthographic cameras don't exist in reality, so applying reflection models meant for (comparatively) realistic perspective cameras can reveal some artifacts. When a sphere is far from the center of the view, a normal camera will lose sight of the far edge, but an orthographic camera will still see a whole hemisphere - effectively seeing "around" the object to parts that are normally invisible:

This means that Fresnel reflection effect at the edges is able to hit a brightness peak we normally won't see, because a surface will be occluded from view for a perspective camera before it ever turns away at such an angle. This creates the unwanted highlight you're observing.

The best thing to do, if the physically-based material is giving you artifacts you don't want in a non-photoreal scene, is to use a different material that doesn't try to model these effects, like the **Legacy-\>Diffuse** or **Mobile-\>Diffuse** materials.

**"But isn't it wrong to use a legacy diffuse shader if it has been deprecated?"**

Not really. The new shaders are meant to give consistency for setting up scenes with real-world effects like global illumination. If you're not using that, then you can skip all that complexity. The Legacy shaders still work just fine.
> 5 votes

---
Tags: unity, camera, materials
---


# Question
Title: Project camera-to-pixel ray in world coordinates
I'm trying to implement a very simple ray tracing function but I have a problem with projecting the camera ray (from camera to pixel) to the world space.

In the screen coordinates have the pixel position (between -1,-1 and 1,1), the field of view (45°). My course tells me that the direction of my ray is

```
vec3 screenDir = (screen_x, screen_y, -1/tan(fovy)) = (screen_x, screen_y, -1)

```

So this should give me the direction of the camera ray in screen coordinates.

After that I multiply the direction by the inverse of my ModelViewProjection matrix and divide by the w component:

```
vec4 worldDir = inverse(MVP) * vec4(screenDir, 1.0);
worldDir /= worldDir.w;
vec3 d = normalize(worldDir.xyz);

```

In theory this should be my ray direction in world space.

I have implemented a small plane-intersection formula to check if this works but the result is completely false (I get a small circle that stays bellow my camera)

```
float t = dot((cam_pos - pointOnPlane), planeNormal) / dot(d, planeNormal);
vec3 intersection = cam_pos + t * d;
vec4 test = MVP * vec4(intersection, 1.0);
test /= test.w;
if(distance(screen_coord, test.xy)<0.1)
    color = vec3(1.0);

```

Is there a problem with my code ? I've read so many tutorial and courses and forum posts and I don't understand why my code doesn't work...

# Answer
If I understand your question: Your asking how to get the world coordinates of the camera, with a look vector to raytrace?

Start by getting the position of your camera, which is simple how you translated the world to get from it's position relative to 0,0 (where the camera always is). Then, look at how you rotate the scene to do the same. From there, you have angle and position of the world from the camera. This is also a normal vector to the screen plane. To raytrace/get a look vector, just use some trigonometry.
> 0 votes

---
Tags: opengl, coordinates, raycasting, raytracing, projection-matrix
---


# Question
Title: How to set only one collider with OnCollisionEnter(Collision col) in Unity?
I tried with this:

```
void OnCollisionEnter(Collision col)
{
    Debug.Log("hit everything");
    if (col.gameObject.layer != LayerMask.NameToLayer("bico"))
    {
        if (col.gameObject.tag == "Floor")
        {
            Debug.Log("hit");
            Destroy(gameObject);
            ShipHealth ShipHealth = this.GetComponentInParent<ShipHealth>();
            if (ShipHealth != null)
            {
                Destroy(gameObject);
                ShipHealth.TakeDamageMissile(100);
            }
        }
    }
}

```

What I want is that it only chooses one collider and not all: I only want the capsule collider.

# Answer
> 2 votes
I'm a little uncertain about your question, but I believe you are asking how to determine which collider triggered the collision so that you can perform distinct actions.

I can think of two ways to do this. First, if the capsule collider area (let's call it the bridge) and the box collider area (the hull) have a lot of distinct functionality, it may be wise to have separate MonoBehavior scripts handling collisions for each. For example, consider this game object hierarchy in Unity:

Ship (Empty parent)

* Bridge (Capsule collider and BridgeSystem script)
* Hull (Box collider and HullSystem script)

BridgeSystem would have an OnCollisionEnter method that only detects the capsule collider, and HullSystem would have its own OnCollisionEnter method for the box collider. If you want additional collision detection for both, I believe you could also attach a MonoBehavior to the Ship parent, which would receive all collisions. Alternatively, the bridge and hull collisions could call a public method in the parent.

If you really want to keep a single script that distinguishes between the two colliders, you should be able to use Collision.ContactPoint. For example, col.contacts\[0\].thisCollider should allow you distinguish between the box and the capsule.

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


# Question
Title: AI using character controller makes unwanted change to it's y position
The enemy parent object does not have any colliders except for the character controller. It starts out with y = .57 and immediately jumps to y=1.6355 because of my call to CharacterController.Move(.)

A code snippet is as follows:

```
myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(targetPos - myTransform.position), rotationSpeed*Time.deltaTime);
Vector3 forward = myTransform.TransformDirection (Vector3.forward);
character.Move (forward * moveSpeed * Time.deltaTime);

```

The above occurs in my update function. I am reluctant to post more code because this is for an assignment.

I feel like I've tried everything. Using rigidbodies, I fixed this problem but then the enemies began to overlap when they got close. So I reverted back to character controllers. In either case I have been trying different ways of keeping y constant, freezing it, making the y rotation component zero, you name it.

One other thing I'll note is that the enemy moves to this y position regardless of where it is initially placed. My main character also starts a distance in the sky and falls down. It so happens that the y position it ends up is this same one that the enemy teleports to.

EDIT: Also I am on Unity 5.2
EDIT 2: This is for a script I use to make the AI follow my player. It is similar to many you will find just googling, because I based it off of those. I have even tried other people's scripts and had the same problem.
EDIT 3: If I put the enemy lower to the ground (say y=.55) he will not pop up like before. However, he doesn't move toward the player anymore.

# Answer
It seems to me that your character collider is partially embedded in the ground plane at y=0.57, and the rounded bottom of the capsule collider pushes it up to y = 1.6355, which is the height at which your collider rests on the ground. This seems almost certain given that the main character collider ends up at the same height after falling from above.

At y = 0.55, the collider may be low enough that the ground plane is intersecting with the cylindrical portion of the collider, which would not provide the same upward push.

If you want your parent object to have a y value of 0.55, you'll need to move the character collider upwards, relative to the parent, so that the bottom of the capsule lines up with the ground plane.
> 1 votes

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


# Question
Title: How to include a new file js in a project cocos2d js?
I'm trying to include a new js file containing a new scene on a cocos2d js project, but every time try occurs the following error:

> Uncaught ReferenceError: GameScene is not defined.

I included my file in jsList and in appList:

```
"jsList"        : ["src/game_scene.js"],
    "appFiles"      : ["src/game_scene.js"]

```

The code of my scene looks normal:

```
var GameScene = cc.Scene.extend({
    onEnter:function(){
        this._super();

        var gameLayer = new GameLayer();
        this.addChild(gameLayer);
    }
});

```

The code on app.js to call my scene looks good too:

```
var gameScene = new GameScene();
cc.Director.runScene(gameScene);

```

What should I do?

# Answer
I solved the problem. I included the file in "jsList" of "project.json".
> -1 votes

---
Tags: javascript, cocos2d-x-js
---


# Question
Title: js canvas tiled map - for loop, while, or matrix
I am making a top-down view tiled map in canvas, where player is always in the middle of the screen, and map scrolls depending on where you go, like in moba games. I also want it to loop infinitely in every direction.

That means that when I cross the top border of the map I should end up at the bottom of the map, when I cross the left side of the map I should end up on the right side, etc. At the same time I only want the part visible on screen to be rendered.

Normaly I would just use for loop, but in cases when I am at the border, or corner of a map, and I need to display the same map, but the other end of it, it gets complicated with lots of nested loops.

I could make the map as math.matrix, and do multiple operations to fragment it and arrange so that it represents only the part visible on screen, like so:

So when I am at one of bottom tiles for example and I am at the center of the screen, I will need to fill the bottom with top tiles, and since the map is bigger than what is displayed on screen I would need to also extract only part of it to render.

But that would require a few math functions each draw, and I wonder if it is ok to do it.

It is hard to explain, especially in a language that is not my native, but I hope that someone will help me.

What is the right way to do it?

# Answer
My answer contains the following assumptions:

1. You want to get the the x,y-coordinates in order from the upper left to the bottom right, even if your viewport overlaps the map. If it overlaps, you want to look at the repeated map.
2. Your viewport does not exceed the size of the map.

```
var mapDimensions = {x: 20, y: 20}; // Width of the map
var viewportDimensions = {x: 10, y: 10};

function iterateOverMap(viewportCenterPosition) {
"use strict";

var halfWidth = viewportDimensions.x / 2.0;
var halfHeight = viewportDimensions.y / 2.0;

var right = (viewportCenterPosition.x + halfWidth) % mapDimensions.x; // Positive overlap is solved using modulo
var left = (mapDimensions.x + (viewportCenterPosition.x - halfWidth)) % mapDimensions.x; // Modulo using negative numbers is strange sometimes, thats why I add mapDimensions.x before.

var up = (mapDimensions.y + (viewportCenterPosition.y - halfHeight)) % mapDimensions.y;
var down = (viewportCenterPosition.y + halfHeight) % mapDimensions.y;

for(var y = up; y != down; y = (y + 1) % mapDimensions.y) {
  for(var x = left; x != right; x = (x + 1) % mapDimensions.x) {
    //Here you got your x,y position
    console.log(x+" "+y);
  }
  console.log("\n");
}
}

var center = {x: 19, y: 19};
iterateOverMap(center);
```

Does this make sense to you?
> 1 votes

---
Tags: javascript, html5, matrix, tilemap, html-canvas
---


title: Bullets Stop Working Error

text:
# Question
Title: Bullets Stop Working Error
I've made a vector which is used by a universally accessible namespace called 'BULLET\_HANDLER'. This vector stores and updates all bullets that are produced from the 'shootBullet' function. The problem I'm facing is that after a while of firing bullets, the vector does not draw or update the bullets and does not push back anymore bullets. It also doesn't crash the game and the game continues normally but none of the objects can fire bullets.

Here is the code for the Bullet Handler:

```
#include "BULLET_HANDLER.h"

static vector<Bullet*> BULLET_ARRAY;

void BULLET_HANDLER::shootBullet(Bullet *BULLET) {
  BULLET_ARRAY.push_back(BULLET);
}

void BULLET_HANDLER::Update() {

  for (unsigned int i = 0; i < BULLET_ARRAY.size(); i++) {
    if (BULLET_ARRAY.size() > 0) {
      if (
        BULLET_ARRAY[i]->getX() <= 0 - BULLET_ARRAY[i]->getW() ||
        BULLET_ARRAY[i]->getX() >= WINDOW_WIDTH) {

        BULLET_ARRAY.erase(BULLET_ARRAY.begin() + i);
      }
    }

    BULLET_ARRAY[i]->Update();
  }
}

void BULLET_HANDLER::Draw(SDL_Surface *Window_Surface) {

  for (unsigned int i = 0; i < BULLET_ARRAY.size(); i++) {
    BULLET_ARRAY[i]->Draw(Window_Surface);
  }
}

void BULLET_HANDLER::clearBulletArray() {
  BULLET_ARRAY.clear();
}

```

# Answer
> 4 votes
You're shooting yourself in the foot:

```
for (unsigned int i = 0; i < BULLET_ARRAY.size(); i++) {
  if (BULLET_ARRAY.size() > 0) {
    if (
      BULLET_ARRAY[i]->getX() <= 0 - BULLET_ARRAY[i]->getW() ||
      BULLET_ARRAY[i]->getX() >= WINDOW_WIDTH) {

      BULLET_ARRAY.erase(BULLET_ARRAY.begin() + i);
    }
  }

  BULLET_ARRAY[i]->Update();
}

```

You modify the collection while you iterate over it: if you delete an item while you iterate, the `BULLET_ARRAY.size()` will change over the course of the loop and at some point you'll never be able to reach the end of your vector.

There are a couple of ways to get around that: use a list\** instead of vector. In your case when you erase an element from the list, an iterator to the next item is returned, so you can easily erase elements as you inspect them. If you still want to use a vector, you'll have to find a way to erase the elements in another way.

Also, please note that even though you call `erase(BULLET_ARRAY.begin() + i)`, this does not mean that the underlying bullet is deleted (because you use pointers), so we can assume one of two things: 1) you know about it and you take that into consideration somewhere else in the code or 2) you have a memory leak there. If you assume that the vector is the owner of the bullet, you should consider looking into `std::unique_ptr`s for your memory management. If the ownership of the bullets is shared, look into `std::shared_ptr`s.

Finally, I suggest you learn to use the debugger and verify case-by-case situations in your code to make sure that what you get is what you expect.

---

\** The list is less memory-access efficient (due to cache misses) than the vector. In your specific case, I don't think you have the requirement for that much of a memory efficiency, so I still suggest you use the list.

# Answer
> 1 votes
My answer is merely a small addition to the excellent answer by Alexandre. Your problem really is modifying a vector while iterating over it. The solutions mentioned by Alexander are great, but I just wanted to share a trick I've been using for removing elements from vectors while iterating over them.

Basically, you would keep a separate container (this can be an array if that'll do, but a vector would probably be the easiest), and place your "dead" bullets into this other list. Once you are done with your iterating, you would then just loop over the bullets in the dead container, and remove those from the other container.

```
std::vector<Bullet*> bullets;
std::vector<Bullet*> deadBullets;

for (Bullet* bullet : bullets)
{
    if (bullet->IsAlive())
    {
        bullet->Update();
    }
    else
    {
        deadBullets.push_back(bullet);
    }
}

for (Bullet* deadBullet : deadBullets)
{
    removeFromVector(deadBullet, deadBullets);
}

```

Apparently to some people it is not obvious how to remove items from an `std::vector`, so for those (even though this is not actually related to the question here, it's merely a small implementation detail) you can take a loot at the SO answer here.

Now, this might have a small impact on your memory usage, but all in all this is a very clear and clean solution, and is easily extendable if you want to start adding new bullets to the list. Just add another vector `addedBullets`, and iterate over those after the loop, adding those to the bullet container.

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