title: Libgdx spawning enemies at random time

text:
# Question
Title: Libgdx spawning enemies at random time
Hello I want to spawn enemies at certain location but at random time,like for example every 10 seconds. Atm I am spawning enemies whenever I click to spawn heroes but with delay, but I sure does not work good, you are unable to get to the enemies base. Here is my code:

PlayStage.java

```
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.utils.viewport.StretchViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
import com.nitheism.uveggfruit.ActorScripts.FirstLevelScript;
import com.nitheism.uveggfruit.Players.FruitPlayer;
import com.nitheism.uveggfruit.Players.VeggiePlayer;
import com.nitheism.uveggfruit.UVeggFruit;
import com.uwsoft.editor.renderer.SceneLoader;
import com.uwsoft.editor.renderer.data.CompositeItemVO;
import com.uwsoft.editor.renderer.scene2d.CompositeActor;

public class PlayStage implements Screen {

private OrthographicCamera camera;
private Stage stage;
private BitmapFont bitmapFont;
private FruitPlayer fruitPlayer;
private VeggiePlayer veggiePlayer;
private UVeggFruit uvf;
private float densityT = 30 * Gdx.graphics.getDensity();

public PlayStage(UVeggFruit uvf) {
    this.uvf = uvf;

}

public void draw() {
    MenuStage mStage;
    if (veggiePlayer.getHealth() <= 0) {
        stage.getBatch().begin();
        bitmapFont.draw(stage.getBatch(), "DEFEAT", 640, 360);
        stage.getBatch().end();
        mStage = new MenuStage(uvf);
        this.hide();
        uvf.setScreen(mStage);
    }
    if (fruitPlayer.getHealth() <= 0) {
        stage.getBatch().begin();
        bitmapFont.draw(stage.getBatch(), "VICTORY", 640, 360);
        stage.getBatch().end();
        mStage = new MenuStage(uvf);
        uvf.setScreen(mStage);
    }
    stage.getBatch().begin();
    bitmapFont.draw(stage.getBatch(), Integer.toString(fruitPlayer.getHealth()), 1200, 390);
    bitmapFont.draw(stage.getBatch(), Integer.toString(veggiePlayer.getHealth()), 50, 390);
    bitmapFont.draw(stage.getBatch(), Integer.toString(veggiePlayer.getMoney()), 60, 420);
    stage.getBatch().end();

}

@Override
public void show() {
    camera = new OrthographicCamera();
    Viewport vp = new StretchViewport(1280, 720, camera);
    stage = new Stage(vp);
    Gdx.input.setInputProcessor(stage);
    fruitPlayer = new FruitPlayer();
    veggiePlayer = new VeggiePlayer();

    SceneLoader stageLoader = new SceneLoader();

    FreeTypeFontGenerator FTFG = new FreeTypeFontGenerator(Gdx.files.internal("Karmakooma.ttf"));
    FreeTypeFontGenerator.FreeTypeFontParameter FTFP = new FreeTypeFontGenerator.FreeTypeFontParameter();
    FTFP.color = Color.WHITE;
    FTFP.size = Math.round(densityT);
    bitmapFont = FTFG.generateFont(FTFP);
    FTFG.dispose();
    CompositeItemVO sceneComposites = new CompositeItemVO(stageLoader.loadScene("MainScene").composite);
    CompositeActor UI = new CompositeActor(sceneComposites, stageLoader.getRm());
    FirstLevelScript firstLevelScript = new FirstLevelScript(stageLoader, bitmapFont, stage, veggiePlayer, fruitPlayer);
    UI.addScript(firstLevelScript);

    stage.addActor(UI);
    draw();

}

@Override
public void render(float delta) {
    camera.update();
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    stage.act(delta);
    stage.draw();
    draw();

}

@Override
public void resize(int width, int height) {
    stage.getViewport().update(width, height, true);

}

@Override
public void pause() {
}

@Override
public void resume() {
}

@Override
public void hide() {
}

@Override
public void dispose() {

    bitmapFont.dispose();

       }
  }

```

FirstLevelScript.java

```
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.utils.Timer;
import com.nitheism.uveggfruit.Players.FruitPlayer;
import com.nitheism.uveggfruit.Players.VeggiePlayer;
import com.uwsoft.editor.renderer.SceneLoader;
import com.uwsoft.editor.renderer.scene2d.ButtonClickListener;
import com.uwsoft.editor.renderer.scene2d.CompositeActor;
import com.uwsoft.editor.renderer.scripts.IActorScript;

import java.util.ArrayList;

public class FirstLevelScript implements IActorScript {

private SceneLoader stageLoader;
private BitmapFont bitmapFont;
private Stage stage;
private CompositeActor pear;
private PearScript pScript;
private VeggiePlayer veggiePlayer;
private FruitPlayer fruitPlayer;
private TomatoScript tScript;
private CompositeActor tomato;
private ArrayList<FruitScript> fruits;

    public FirstLevelScript(SceneLoader stageLoader,  BitmapFont    bitmapFont, Stage stage, VeggiePlayer vp, FruitPlayer fp) {
             this.stageLoader = stageLoader;
             this.bitmapFont = bitmapFont;
             this.stage = stage;
             this.veggiePlayer = vp;
             this.fruitPlayer = fp;
}

@Override
public void init(CompositeActor entity) {
    fruits = new ArrayList<FruitScript>();
    ButtonClickListener buttonClickListener = new ButtonClickListener();
    entity.getItem("tomatobtn").addListener(buttonClickListener);
    entity.getItem("tomatobtn").addListener(new ClickListener() {
        @Override
        public void clicked(InputEvent event, float x, float y) {
            super.clicked(event, x, y);
            if (veggiePlayer.getMoney() >= 10) {
                tScript = new TomatoScript(stage.getBatch(), bitmapFont, fruits, fruitPlayer);
                tomato = new CompositeActor(stageLoader.loadVoFromLibrary("tomato"), stageLoader.getRm());
                tomato.addScript(tScript);
                stage.addActor(tomato);
                veggiePlayer.setMoney(-10);
                Timer.schedule(new Timer.Task() {
                    @Override
                    public void run() {
                        pear = new CompositeActor(stageLoader.loadVoFromLibrary("pear"), stageLoader.getRm());
                        pScript = new PearScript(stage.getBatch(), bitmapFont, veggiePlayer);
                        pear.addScript(pScript);
                        stage.addActor(pear);
                        fruits.add(pScript);
                    }
                }, 2);

            }

        }
    });
}

@Override
public void act(float delta) {

}

@Override
public void dispose() {

     }
}

```

I will be glad if someone can help me on how to do it the way I want it, with delay I guess doesn't work I tried. So what I want is to spawn enemies every 10 seconds :) Tnx in advance.

# Answer
You can use the `delta` variable of the `render()` function. This variable is a float value of the time elapsed since last render call (Something like time from frame to frame, not exactly, but this is the idea).

Simply add the delta time value to a variable and then execute the code you want when the variable gets to a specific (or random number).

Generic example:

```
@Override
public void render(float delta) {
    camera.update();
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    stage.act(delta);

    if(timeAux>=10){ //10 seconds
        //Your code to spawn enemy.
        timeAux=0;
    }else{
        timeAux+=delta;
    }
}

```

`timeAux` is a global variable.

`10` is just an example value, you can create a variable and assign a new random value every time you create an enemy.
> 1 votes

---
Tags: libgdx, timer, timing, spawning
---


# Question
Title: How to encrypt Save Files without using a key?
Say I made a simple program that takes a file `.dat` that is encrypted in **Binary Format**, then I decrypt it into a *byte array* and then everything is rewritten again into the file decrypted.

For Example:

*I've made a binary encryption algorithm.* =\> 0100100001100101001000000110100001100101011000...

But this is very very easy to decrypt...

Is there any way, that, if it's possible does not need any sort of key, to encrypt my save progress?

# Answer
In general you should never invent your own cryptographic algorithms, unless you have at least a PhD in both mathematics **and** computer science. But there are many good stock algorithms which have no known attacks and have free implementations in many programming languages. For example RC5, AES or Blowfish. Depending on which technology you use to develop your game, it might even offer secure encryption out-of-the-box.

However, the question is if encrypting savegames is a good idea.

First, when you have your game executable do the encryption and decryption, you have to include both the algorithm and the key in your game executable. That means a determined hacker can find them, extract them, and use them to build a savegame editor. So it can never be 100% secure.

Second, why do you want to do this anyway? When it is an online game, you should store the gamestate online where the players can not modify it. When it is an offline game, then why bother? A cheater can only hurt their own game experience at worst. The honest players who want to enjoy your game as intended won't be affected by this at all. On the other hand, allowing players to cheat can *add* value to your game. It allows players to experience the game in a different way which can just increase their long-term enjoyment of your game.
> 79 votes

# Answer
To encrypt and decrypt locally, you will need to store the key in your program, so people will be able to crack the encryption if they disassemble your code. There are tricks to obfuscate keys, but even with those a dedicated attacker will find the key and then post it online for all those who are less dedicated to see. The only thing encryption does prevent is people who use a hex editor - you can easily foil that with compression and anything that makes the file unreadable by an unzip program. E.g. add one byte in front of the data.

Alternatively you can append the md5 of the savefile at the end of the file, so you'll notice if a file has been tampered with. You can then use this to either refuse loading the savegame, or to flag support tickets appropriately so you don't waste time on issues caused by manually modified savegames. Again, this is trivial to circumvent by anyone who can read your code.

If you want something that can't be circumvented by someone who has access to the binaries on their device, you need to run part of the program on a server, which is under your control.

To answer your last question, a key plus encryption type just identifies the exact algorithm that needs to be applied to encrypt/decrypt. You cannot encrypt/decrypt data without an algorithm that defines how to do so.
> 10 votes

# Answer
Store a transformed SHA256 hash of the actual save data in the save file.

Compare the stored hash to the SHA256 value of the data as you load it.

If that doesn't match, they've cheated or corrupted the file.

**Edit to clarify:** this makes it *more difficult* to crack the anti-cheat system but *still possible*.
> 4 votes

# Answer
I would use a standard encryption algorithm (because it makes it harder to perform crypto-analysis on the saved file) but not one of the top five most used, and hide it throughout your code (because it makes it harder to understand what algorithm it is and where is the key.)

To hide the encryption algorithm into your code: take an open source version, understand its flow (which functions call which others an in what sequence), then rename all variables, struct fields and function names (just to be sure) and spread the functions all over your codebase, in different objects and modules, possibly separating their execution temporally as well (perform one piece of the encryption, then do something else, then after some ms come back to it from a seemingly unrelated piece of code and perform another phase of the encryption, and so on.) The key can be hidden in the same way, as a number of seemingly unrelated constants throughout your classes, that are accessed at runtime by the various hidden parts of the encryption algorithm.

Whether all this makes economical sense is another topic altogether.
> 1 votes

---
Tags: encryption, binary
---


# Question
Title: Storing and rendering Mesh Data in stl container
I'm trying to refresh my DirectX11 knowledge, and ran into a problem while trying to render multiple meshes instanced.

What I want to do is give my ObjectManager class the name of an .obj file and it then parses the vertex/index data out of that file. If I try to load the same .obj more than once, it should instead add an instance at the desired position in the scene. To do so I have a Vector storing all the Data for the objects. (see code below)

My problem is a massive performance drop when iterating though the vector of mesh info instead of just rendering the first object in the vector (for test purposes). Now, this sounds obvious of course, what I'm struggling to understand is, that this performance drop happens even when the vector only contains 1 element. So simply adding the *for* loop seems to cause this , even without rendering more or even effectively iterating through a bunch of items. (it drops from 2000+ fps to around 300, plus a very regular lag while moving. This is so substantial with so little change that I must assume something funny is going on).

So my assumption is either:

1. Vector is not a good way to store the mesh data and render all of it every frame. Is a vector not the common, or at least a feasible way, of storing this kind of data?
2. I might be doing something wrong while creating/updating the buffers for every object.

ObjectManager should hold all the objects i spawn in the scene, and in it's render function it will render all objects I have registered with it. To reduce draw calls I want to instance multiple calls of the same object, so my idea was to have a struct like this:

`struct MeshDataBundle
{
 std::string name; //used as ID to not spawn multiple struct with same Model
 std::shared_ptr<Model> model;
 std::vector<Instance> instances; //Instance = struct with just XMFLOAT3 for position
};`

My ObjectManager class now has a std::vector of this struct. In the render function, it should iterate though the vector and render the Model in it with the instance information in the included instances vector.

The render function looks like this:

```
//D3D class, passed as paramter, has the Device, DeviceContext etc.
public void ObjectManager::render(D3D& d3d)
{
    //called only the first time
    if (!initialized)
    {
        initBuffers(d3d);
    }

    //run through all models
    for (auto val : modelData)
    {
        //update the subresources and buffers
        DirectX::XMMATRIX tempWorld;
        tempWorld = XMLoadFloat4x4(&val.model->getWorld());
        //cbPerObject is a struct with only a XMMATRIX world world-matrix
        m_cbPerObject.world = DirectX::XMMatrixTranspose(tempWorld);

       //Update Buffers with vertices and instance information. Using CComPtr's, thus the "..Buffer.p".
       //Dynamic buffers bc updated multiple times per frame
        D3D11_MAPPED_SUBRESOURCE mappedResource = { 0 };
        d3d.DevCon->Map(cbPerObjectBuffer.p, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
        memcpy(mappedResource.pData, &m_cbPerObject, sizeof(cbPerObject));
        d3d.DevCon->Unmap(cbPerObjectBuffer.p, 0);

        D3D11_MAPPED_SUBRESOURCE mappedResourceInst = { 0 };
        d3d.DevCon->Map(cbInstanceBuffer.p, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResourceInst);
        memcpy(mappedResourceInst.pData, &val.instances[0], sizeof(Instance)*val.instances.size());
        d3d.DevCon->Unmap(cbInstanceBuffer.p, 0);

        d3d.DevCon.p->VSSetConstantBuffers(0, 1, &cbPerObjectBuffer.p);

        //model class has its own vertex and index buffer, which we get and use
        CComPtr<ID3D11Buffer> bufferPointers[2] = { val.model->getVertexBuffer(), cbInstanceBuffer.p };

        UINT32 strides[2] = { sizeof(Vertex), sizeof(Instance) };
        UINT32 offsets[2] = { 0, 0 };

        d3d.DevCon.p->IASetVertexBuffers(0, 2, &bufferPointers[0].p, strides, offsets);

        d3d.DevCon.p->IASetIndexBuffer(val.model->getIndexBuffer(), DXGI_FORMAT_R32_UINT, 0);
        d3d.DevCon.p->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

        d3d.DevCon.p->DrawIndexedInstanced(val.model->getIndexCount(), val.instances.size(), 0, 0, 0);

    }
};

```

MISC:

Things I suppose might also be of relevance:

1.Creating the buffers in the ObjectManager (the class containing the above)

```
D3D11_BUFFER_DESC cbbd;
ZeroMemory(&cbbd, sizeof(D3D11_BUFFER_DESC));

cbbd.Usage = D3D11_USAGE_DYNAMIC;
cbbd.ByteWidth = sizeof(cbPerObject);
cbbd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
cbbd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
cbbd.MiscFlags = 0;

hr = d3d.Device.p->CreateBuffer(&cbbd, NULL, &cbPerObjectBuffer);

D3D11_BUFFER_DESC cbbd2;
ZeroMemory(&cbbd2, sizeof(D3D11_BUFFER_DESC));

cbbd2.Usage = D3D11_USAGE_DYNAMIC;
cbbd2.ByteWidth = sizeof(Instance)*maxInstanceBufferSize;//largest possibly needed buffer for instances
cbbd2.BindFlags = D3D11_BIND_VERTEX_BUFFER;
cbbd2.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
cbbd2.MiscFlags = 0;

D3D11_SUBRESOURCE_DATA instanceData;
instanceData.pSysMem = &modelData[largestIndex].instances[0];
instanceData.SysMemPitch = 0;
instanceData.SysMemSlicePitch = 0;

hr = d3d.Device.p->CreateBuffer(&cbbd2, &instanceData, &cbInstanceBuffer);

```

2.The Model class has it's own vertex and index buffers. These are used in the above rendering function via getter functions. The Buffers of every Model are created like this:

```
vertexCount = v.size();
indexCount = i.size();

//VERTEX BUFFER
vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
vertexBufferDesc.ByteWidth = sizeof(Vertex) * vertexCount;
vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertexBufferDesc.CPUAccessFlags = 0;
vertexBufferDesc.MiscFlags = 0;
vertexBufferDesc.StructureByteStride = 0;

vertexData.pSysMem = &v[0];
vertexData.SysMemPitch = 0;
vertexData.SysMemSlicePitch = 0;

result = device->CreateBuffer(&vertexBufferDesc, &vertexData, &vertexBuffer);

// INDEX BUFFER
// Set up the description of the static index buffer.
indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
indexBufferDesc.ByteWidth = sizeof(UINT32) * indexCount;
indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
indexBufferDesc.CPUAccessFlags = 0;
indexBufferDesc.MiscFlags = 0;
indexBufferDesc.StructureByteStride = 0;

// Give the subresource structure a pointer to the index data.
indexData.pSysMem = &i[0];
indexData.SysMemPitch = 0;
indexData.SysMemSlicePitch = 0;

result = device->CreateBuffer(&indexBufferDesc, &indexData, &indexBuffer);

```

So, sorry for the very long post, but hopefully all info needed is in there.

# Answer
> 1 votes
The primary thing that stands out is that your loop copy initializes the `auto val` loop variable with the elements as you iterate.

Even though your type is reasonably small, there's a bunch of overhead in doing so and it's likely that you would gain some by going for `auto& val`.

Of secondary concern is that you're using strings for non-textual things. Consider using integers or pointers as keys. If you need an actual printable string, you can have a string repository on the side from which you can register and look up strings with IDs.

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


# Question
Title: How to apply force to rigid bodys at a specific point?
I am trying to write a physics engine from scratch to get a better understanding of them. It worked pretty good so far, but there is one thing, i can't get my head around:

If i have a rigid body ( for example circles or rectangles) and i am applying a force F at a point P to it. Now my problem is to figure out, how this force will affect translation speed and rotation speed of the rigid body. So far i have figured out, that it might has to do with the center of mass and the moment of inertia.

# Answer
> So far i have figured out, that it might has to do with the center of mass and the moment of inertia.

You're right, it does have to do with the center of mass and the inertia.

The resultant force is simply, the original force plus the force applied. The resultant torque is equal to the original torque plus the cross product of the force vector with the radius (the vector from the COM to the point of application of force. This holds true for both 2 dimensions and 3 dimensions.

All in all, the simple AddForceAtPosition function will be:

```
void AddForceAtPosition(Vector3 f, Vector3 point)
{
    force += f;
    torque += cross(point - centerOfMass, f);
}

```

In 2D the cross product of two vectors is a scalar in the Z direction, whose value is governed by this formula:

```
cross(a, b) = a.x * b.y - a.y * b.x

```

Or simply the determinant of both the 2D vectors A and B.
> 6 votes

# Answer
Might not be useful but for a simple equation F=(mv^2)/r where f is the force, m is mass, v velocity and r radius. I'm not 100% sure but I think inertia is the force acting to slow down an object not speed it up.
> 0 votes

---
Tags: physics, rigidbody
---


title: Can't set color of returned sprite?

text:
# Question
Title: Can't set color of returned sprite?
So, I have some variables in my game :

This is all the tiles in my game / the map.

```
std::vector<Sprite*> tiles;

```

This is the sprite variable which I have in a custom Sprite class.

```
sf::Sprite* sprite;

```

And here are my functions :

in main :

gameScreen.GetSpriteByPosition(window.mapPixelToCoords(sf::Mouse::getPosition(window), view), &window)-\>setColor(sf::Color::Black);

(That gives me a exception thrown error, Access violation reading 0x000000B4)

And this is the getSpriteByPosition function :

```
sf::Sprite* GameScreen::GetSpriteByPosition(sf::Vector2f mousePos, sf::RenderWindow* window)
{
    sf::FloatRect mouseBound(mousePos, sf::Vector2f(1, 1));

    for (int i = 0; i < tiles.size(); i++)
    {
        if (lastSprite == i)
        {
            tiles[i]->setColor(sf::Color::Black);
        }

        else if (tiles[i]->getGlobalBounds().intersects(mouseBound) && lastSprite != i)
        {
            tiles[lastSprite]->setColor(sf::Color::White);
            tiles[i]->setColor(sf::Color::White);

            std::cout << "Found tile, index : " << i << std::endl;
            lastSprite = i;
            return tiles[i]->getDrawable();
        }

    }

    return nullptr;
}

```

And here's my getDrawable() function :

```
sf::Sprite* Sprite::getDrawable()
{
    return sprite;
}

```

# Answer
> 3 votes
While not necessarily at fault here, `GetSpriteByPosition` returns a pointer to a temporary returned by `getDrawable`. You may not return pointers or references to locals or temporaries, as they do not outlast the function they appear in.

As for your error, you can divine some information from the faulting address. `0xB4` is almost zero, which usually means that it's a member access or array indexing with a null pointer. There are no valid objects down near zero in the address space. Look at your call stack in your debugger to see where/how incorrect data creeps in.

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


# Question
Title: Implementing Shadow Mapping in Python and OpenGL 2.1
I am trying to create a little shadow mapping demo.

My code is currently divided into three rendering passes:

* Pass 1 - Create the depth texture that will be used for shadow mapping on an offscreen framebuffer
* Pass 2 - (Attempt to) render the scene with shadows using that depth texture
* Pass 3 - Display the shadow map in the upper right corner (debug purposes)

I have successfully created and rendered a depth texture (passes 1 and 3). However, I am struggling to render the scene with shadows from the camera's POV. There is some flickering at the edges of thick floor plane as well as on one cube corner. The results look nothing like shadows and the scene looks fully lit. I am thinking that either my second pass or my shaders for that pass that I am using to display the scene are incorrect, but I cannot seem to find the error. It is a relatively short demo written using python 2.7, opengl 2.1, and GLSL 120. Below is the main method that includes most of the relevant code (aside from some window creation, shader compilations, and primitive matrix math libraries I wrote):

```
from window import Window
from shader import Shader
from mat4 import Mat4
from vec3 import Vec3

from OpenGL.GL import *
from OpenGL.GLU import *
import math
import numpy as np
from PIL import Image

#Loads my special model file format
#Basically a super-simplified obj without indexing
def loadAA7(dataUrl):
        vData = []
        tData = []
        nData = []
        inFile = open(dataUrl, "r")
        for line in inFile.readlines():
            lineList = line.strip().split("\t")
            vData.extend([float(v) for v in lineList[0:3]])
            tData.extend([float(v) for v in lineList[3:5]])
            nData.extend([float(v) for v in lineList[5:]])
        vertexData = np.array(vData, dtype=np.float32)
        texCoordData = np.array(tData, dtype=np.float32)
        normalData = np.array(nData, dtype=np.float32)
        return vertexData, texCoordData, normalData

def createMeshBuffers(vertices, texCoords, normals):
    v, t, n = vertices, texCoords, normals
    vbo, tbo, nbo = glGenBuffers(3)
    glBindBuffer(GL_ARRAY_BUFFER, vbo)
    glBufferData(GL_ARRAY_BUFFER, len(v)*4, v, GL_STATIC_DRAW)
    glBindBuffer(GL_ARRAY_BUFFER, tbo)
    glBufferData(GL_ARRAY_BUFFER, len(t)*4, t, GL_STATIC_DRAW)
    glBindBuffer(GL_ARRAY_BUFFER, nbo)
    glBufferData(GL_ARRAY_BUFFER, len(n)*4, n, GL_STATIC_DRAW)
    glBindBuffer(GL_ARRAY_BUFFER, 0)
    return vbo, tbo, nbo

if __name__ == "__main__":
    window = Window("Shadow Mapping Test", 800, 600, 60)
    glClearColor(0.0, 0.0, 0.0, 1.0)
    glEnable(GL_CULL_FACE)
    glEnable(GL_TEXTURE_2D)
    glEnable(GL_DEPTH_TEST)
    time = 0

    v, t, n = loadAA7("./data/blockworld.aa7")
    vbo, tbo, nbo = createMeshBuffers(v, t, n)
    shadowMapShader = Shader("./shaders/shadowMap.vert", "./shaders/shadowMap.frag")
    shadowMapShader.compile()
    displayShader = Shader("./shaders/display.vert", "./shaders/display.frag")
    displayShader.compile()

    img = Image.open("./data/blockworld.png")
    imgWidth, imgHeight = img.size
    imgData = np.array(img)
    modelTex = glGenTextures(1)
    glBindTexture(GL_TEXTURE_2D, modelTex)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, imgWidth, imgHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, imgData)
    glBindTexture(GL_TEXTURE_2D, 0)

    rendertarget = glGenTextures(1)
    glBindTexture(GL_TEXTURE_2D, rendertarget)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
    glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, 512, 512, 0, GL_DEPTH_COMPONENT, GL_FLOAT, None)
    fbo = glGenFramebuffers(1)
    glBindFramebuffer(GL_FRAMEBUFFER, fbo)
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, rendertarget, 0)
    glBindFramebuffer(GL_FRAMEBUFFER, 0)

    lightPos = Vec3(150, 150, 0)
    cameraPos = Vec3(0, 200, -300)

    while True:
        window.update()
        time += 1

        #Pass 1: Render to Texture
        shadowMapShader.enable()
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        lightProj = Mat4().perspective(60, float(512)/512, 1, 1000)
        lightView = Mat4().lookAt(lightPos, Vec3(0, 0, 0), Vec3(0, 1, 0))
        modelMatrix = Mat4().rotateY(time)
        glMatrixMode(GL_PROJECTION)
        glLoadMatrixf(lightProj.data)
        glMatrixMode(GL_MODELVIEW)
        glLoadMatrixf(lightView.data)
        glMultMatrixf(modelMatrix.data)
        glBindFramebuffer(GL_FRAMEBUFFER, fbo)
        glViewport(0, 0, 512, 512)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glEnableClientState(GL_VERTEX_ARRAY)
        glVertexPointer(3, GL_FLOAT, 0, v)
        glDrawArrays(GL_TRIANGLES, 0, len(v)/3)
        glDisableClientState(GL_VERTEX_ARRAY)
        shadowMapShader.disable()

        #Pass 2: Render the scene with shadows
        bias = Mat4([0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0])
        biasMVPMatrix = bias.mul(lightProj).mul(lightView).mul(modelMatrix)
        glViewport(0, 0, 800, 600)
        glBindFramebuffer(GL_FRAMEBUFFER, 0)
        cameraProj = Mat4().perspective(30, float(800)/600, 1, 1000)
        cameraView = Mat4().lookAt(cameraPos, Vec3(0, 0, 0), Vec3(0, 1, 0))
        modelMatrix = Mat4().rotateY(time)
        glMatrixMode(GL_PROJECTION)
        glLoadMatrixf(cameraProj.data)
        glMatrixMode(GL_MODELVIEW)
        glLoadMatrixf(cameraView.data)
        glMultMatrixf(modelMatrix.data)
        displayShader.enable()
        glActiveTexture(GL_TEXTURE1)
        glBindTexture(GL_TEXTURE_2D, rendertarget)
        glActiveTexture(GL_TEXTURE0)
        glBindTexture(GL_TEXTURE_2D, modelTex)
        displayShader.setUniform("u_modelTexture", "sampler2D", 0)
        displayShader.setUniform("u_shadowMap", "sampler2D", 1)
        displayShader.setUniform("u_biasMVPMatrix", "mat4", biasMVPMatrix.data)
        glEnableClientState(GL_VERTEX_ARRAY)
        glEnableClientState(GL_TEXTURE_COORD_ARRAY)
        glVertexPointer(3, GL_FLOAT, 0, v)
        glTexCoordPointer(2, GL_FLOAT, 0, t)
        glDrawArrays(GL_TRIANGLES, 0, len(v)/3)
        glDisableClientState(GL_VERTEX_ARRAY)
        glDisableClientState(GL_TEXTURE_COORD_ARRAY)
        displayShader.disable()

        #DEBUG: Display the render texture
        glViewport(0, 0, 800, 600)
        glBindFramebuffer(GL_FRAMEBUFFER, 0)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        glOrtho(-1, 1, -1, 1, -1, 1)
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()
        glActiveTexture(GL_TEXTURE0)
        glBindTexture(GL_TEXTURE_2D, rendertarget)
        glBegin(GL_QUADS)
        glColor3f(1,1,1)
        glTexCoord2f(0, 0); glVertex3f(0.5, 0.5, 0)
        glTexCoord2f(1, 0); glVertex3f(1, 0.5, 0)
        glTexCoord2f(1, 1); glVertex3f(1, 1, 0)
        glTexCoord2f(0, 1); glVertex3f(0.5, 1, 0)
        glEnd()

```

I am also including my shadows for pass 1 (shadowMap.vert/frag) and pass 2 (display.vert/frag) in case the error is in one of these, but they seem to make sense to me (pass 1 outputs linearizes fragment depth while pass 2 transforms the vertices with a biased light space matrix before performing a depth comparsion between the depth texture and the scene).

**shadowMap.vert**

```
#version 120

void main()
{
    gl_Position = gl_ProjectionMatrix * gl_ModelViewMatrix * gl_Vertex;
}

```

**shadowMap.frag**

```
#version 120

void main()
{
    float z = gl_FragCoord.z;
    float n = 1.0;
    float f = 1000.0;
    //convert to linear values
    //formula can be found at www.roxlu.com/2014/036/rendering-the-depth-buffer
    float c = (2.0 * n) / (f + n - z * (f - n));
    gl_FragDepth = c;
}

```

**display.vert**

```
#version 120

uniform mat4 u_biasMVPMatrix;
varying vec4 v_shadowCoord;

void main()
{
    mat4 bias = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);
    gl_Position = gl_ProjectionMatrix * gl_ModelViewMatrix * gl_Vertex;
    v_shadowCoord = u_biasMVPMatrix * gl_Vertex;
    gl_TexCoord[0] = gl_MultiTexCoord0;
}

```

**display.frag**

```
#version 120
uniform sampler2D u_modelTexture;
uniform sampler2D u_shadowMap;
varying vec4 v_shadowCoord;

void main()
{
    vec3 projCoords = v_shadowCoord.xyz/v_shadowCoord.w;
    float closestDepth = texture2D(u_shadowMap, projCoords.xy).r;
    float currentDepth = projCoords.z;
    float shadow = currentDepth > closestDepth  ? 1.0 : 0.0;
    gl_FragColor = shadow * texture2D(u_modelTexture, gl_TexCoord[0].xy);
}

```

**Update:** Here is a picture of the results achieved when using this as the pass 2 fragment shader:

```
gl_FragColor = vec4(v_shadowCoord.xyz/v_shadowCoord.w, 1.0);

```

I also found it interesting that I get "shadows" when I use this as the shader instead (but I have no idea what it mean):

```
#version 120

uniform sampler2D u_modelTexture;
uniform sampler2D u_shadowMap;
varying vec4 v_shadowCoord;

void main()
{
    vec3 projCoords = v_shadowCoord.xyz/v_shadowCoord.w;
    float closestDepth = texture2D(u_shadowMap, projCoords.xy).z;
    gl_FragColor.rgb = vec3(closestDepth);
    gl_FragColor.a = 1.0;
}

```

# Answer
> 0 votes
As Krom Stern pointed out in the comments, the issues with my shadow mapping stemmed from two issues in the pass 2 fragment shader. First, I needed to divide the v\_shadowCoord by the w component in addition to performing the correct bias model-view-projection multiplication. This division would normalize my coordinates between 0 and 1 and provide valid texture coordinates for looking up depths in my shadow map. Second, I needed to fix my comparison between current and closest depth by performing the same linearization function that I did on closestDepth in pass 1 to currentDepth in pass 2.

I have reorganized the code to somewhat separate the lighting and shadowing calculations in the shader. Here is my updated shader (display.frag) for the shadow mapping demo:

```
#version 120

struct Light
{
    vec3 color;
    vec3 direction;
    vec3 position;
    float innerAngle;
    float outerAngle;
};

uniform sampler2D u_modelTexture;
uniform sampler2D u_shadowMap;
varying vec4 v_shadowCoord;
varying vec3 v_position;
varying vec3 v_normal;
varying mat4 v_mvMatrix;
uniform Light u_light;//spotlight in the demo!

vec4 calcShadow()
{
    vec3 projCoords = v_shadowCoord.xyz/v_shadowCoord.w;
    float closestDepth = texture2D(u_shadowMap, projCoords.xy).z;
    float z = projCoords.z;
    float n = 1.0;
    float f = 1000.0;
    float currentDepth = (2.0 * n) / (f + n - z * (f - n));
    vec3 shadow = u_light.color;
    float bias = 0.00005;//simple bias works here well enough, but needs to be tweaked based on the scene to avoid peter-panning.

    if(closestDepth + bias < currentDepth)
    {
        shadow = vec3(0.5, 0.5, 0.5);//ambient light
    }

    //We have artifacts on sides that should be in shadow.
    //Let's remove those with a partial lighting calculation.
    vec3 normal = normalize(v_normal);
    vec3 lightPos = vec3(v_mvMatrix * vec4(u_light.position, 1.0));
    vec3 lightDir = normalize(lightPos - v_position);
    float diffCont = max(0.0, dot(normal, lightDir));
    if (diffCont == 0.0)
    {
        shadow = vec3(0.5, 0.5, 0.5);//ambient light
    }
    return vec4(shadow, 1.0);
}

vec3 calcLight()
{
    vec3 normal = normalize(v_normal);
    vec3 outLight = vec3(0.0, 0.0, 0.0);
    vec3 lightPos = vec3(v_mvMatrix * vec4(u_light.position, 1.0));
    vec3 spotDir = normalize(vec3(v_mvMatrix * vec4(u_light.direction, 0.0)));
    float innerAngle = u_light.innerAngle;
    float outerAngle = u_light.outerAngle;
    vec3 lightDiffuse = u_light.color;
    vec3 lightDir = normalize(lightPos - v_position);
    float diffCont = max(0.0, dot(normal, lightDir));
    if (diffCont > 0.0)
    {
        float angle = degrees(acos(dot(-lightDir, spotDir)));
        if (angle < outerAngle)
        {
            if (angle < innerAngle)
            {
                vec3 diffuse = diffCont * lightDiffuse;
                outLight = diffuse;
            }

            else
            {
                float att = 1 - pow(((angle - innerAngle) / (outerAngle - innerAngle)), 2);//squaring to approximate inverse-square law falloff
                vec3 diffuse = diffCont * lightDiffuse * att;
                outLight = diffuse;
            }
        }
    }
    return outLight;
}

void main()
{
    vec3 ambientLight = vec3(0.5, 0.5, 0.5);
    vec3 diffuseLight = calcLight();
    vec4 totalLight = vec4(ambientLight + diffuseLight, 1.0);
    vec4 shadow = calcShadow();
    vec4 color = texture2D(u_modelTexture, gl_TexCoord[0].st);
    gl_FragColor = shadow * color * totalLight;
}

```

I have also made several changes to the rest of the code. These include:

1. Sending light uniforms to the pass 2 shader.
2. Actually using the vertex buffer objects I had created during initialization instead of just using vertex array objects.
3. Applying culling to move artifacts to the faces that should be in shadow by the lighting calculations.
4. Changing the model I am displaying (just for fun).

Below is a screenshot of the result:

There is still room for improvements such as PCF soft shadows and removing deprecated OpenGL variables and function calls, but I think it is a good starting point. The complete code for the demo can be found here. Just unzip the contents and run main.py. Note that there are several dependencies, which include pysdl2 (used for window management), PIL/pillow, PyOpenGL, and numpy.

---
Tags: opengl, python, shadow-mapping
---


title: Entity Interpolation (Lost Packets?)

text:
# Question
Title: Entity Interpolation (Lost Packets?)
I'm working on a networked game for a while. I'm aware of `client-side prediction` and `lag compensation (shooting)` but I'm not sure about entity interpolation client-side. I'm sending update/sync packets at 10fps from server and client interpolates from current position to newly received position. Interpolation takes 100ms (because of 10fps) to reach target position but what if new position arrives late or 2-3 packets drop? There will be no target position and sync'd (client-side) entity will be idle until new position packet but entity continuously moving forward server-side. Basically, I don't know what to do in this situation.

# Answer
> 0 votes
The point of interpolation is to take the last received position from the server and *predict where the object should be now* based on how long ago the last packet was received.

This is called "linear interpolation" as we assume that the object moves at a constant, fixed velocity based on the motion vector last received from the server. There are problems with this when a true disconnect occurs (if you've played Second Life for any period of time, watching yourself suddenly go flying through walls and off into the void is the result of client-side linear interpolation with no resync from the server).

This is a decent article on how to go about setting up interpolation and resync in unity. It's a little above my head to try and provide a summary, but it has to do with storing input, acting on it immediately on the client, then when the data is sent to the server and validated, some computation is performed on the reply back to the client to keep things in synchonization.

---
Tags: unity, networking, interpolation, lerp, latency
---


title: Java Slick2d lighting using Raycasting

text:
# Question
Title: Java Slick2d lighting using Raycasting
I am trying to make a top down view game in java using the Slick2d library, for lighting I wanted to do something like this : http://www.redblobgames.com/articles/visibility/. I was wondering if there was a way to tint or light places on the screen in Slick. I would have my map rendering in the background and a lightmap in front.

Solution : https://github.com/ariejan/slick2d/blob/master/src/org/newdawn/slick/tests/AlphaMapTest.java

# Answer
> -1 votes
I suggest to check this project, Shade. There is real-time lighting and moving shadows, I think could be useful for you

---
Tags: java, lighting, graphics-programming, slick
---


# Question
Title: How to achieve a layered terrain simlar to Godus
I'm currently playing around with a few examples and techniques for terrain generation and suddenly remembered the game Godus - seen below.

Youtube clip of Godus

Looking at the material above, it seems to me that they aren't just using a classic heightmap system, as there appears to be some bevel or flexibility in the angle of the edge faces (shadows aside).

However, more technical approaches, such as GPU GEMS 3 marching cube example seem a bit over the top.

Could I achieve this aesthetic with a heightmap and clever manipulation of vertices in a vertex / tessellation shader, or is there a better approach?

# Answer
> 3 votes
A hill like this could be created with the following algorithm:

1. Start with a small circle in form of a regular n-gone (the mountain top).
2. Create a larger "blob" on height 0 by taking the corner-vertices of the previous circle and move each one further away from the center by a random distance.
3. every few iterations, interpolate new vertices on straight lines between the existing ones to avoid it becoming too blocky on the lower levels.
4. move all "blobs" up by one unit
5. repeat from step 2 until desired size is reached.

---
Tags: procedural-generation, terrain, terrain-rendering, heightmap, tessellation
---


# Question
Title: XNA's GameTime.ElapsedGameTime.TotalSeconds isn't working as expected
As I've seen at quite a few website, the best way to handle variable frame rate and movement (moving projectiles, monsters, swinging swords)... looks something like this:

```
//This
position += TotalSpeed * (float)gt.ElapsedGameTime.TotalSeconds;

//Or this (direction is being normalized)
position += direction * (float)(TotalSpeed * gt.ElapsedGameTime.TotalSeconds);

```

And then in the Game's main constructor (Game1.cs):

```
        IsFixedTimeStep = false;
        TargetElapsedTime = TimeSpan.FromSeconds(16.666); //16.666 milliseconds, or about 60 FPS.

        graphics.SynchronizeWithVerticalRetrace = true;

```

I started to notice that whenever my FPS was at 30, my projectiles (in this case, arrows) would move slower than when at full speed. Turning V-Sync to false above unlocked the frame rate so then I'm going around 120 FPS. Projectiles are going much faster.

Unfortunately, this applies to everything else.

Am I doing something wrong, or is TotalSeconds just that unreliable/broken? I plan to switch over to Monogame eventually, but I'm not sure if that would fix the issue.

An additional note that may or may not be related: changing 'IsFixedTimeStep' to true causes my game to not run -- no errors, just a blank window-colored (beige-ish) screen.

Thanks in advance.

EDIT: projectile movement code

```
        direction = new Vector2((float)Math.Cos(rotation),
                                (float)Math.Sin(rotation));

        if (direction != Vector2.Zero)
            direction.Normalize();

        position += (direction * TotalSpeed) * (float)gt.ElapsedGameTime.TotalSeconds;

```

Pretty normal movement code. 'rotation' is just the direction the player is looking. 'TotalSpeed' is 2300f.

# Answer
I suspect there is an error in your update or draw loop (note, both have a gametime parameter- but you should only update game logic in the `Update` loop).

To demonstrate I made this demo:

```
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System;
using System.Diagnostics;

namespace TimeStepDemo
{
    /// <summary>
    /// This is the main type for your game.
    /// </summary>
    public class Game1 : Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        Texture2D _pixel; // have a pixel to draw stuff.

        Vector2 _position; //position of the object.
        Vector2 _center; //center of the circle.
        double _angle; //current angle of the circle.
        double _angleSpeed; //how fast the object should go.

        float _frametime; // record the time a frame in the update took.
        long _millisecondsPerCircle; //how many miliseconds to complete a circle (to compare settings).
        Stopwatch _stopwatch; //to recored the time.

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            //----------------------
            // Try different combinations of true and false here!
            //----------------------
            IsFixedTimeStep = true;
            graphics.SynchronizeWithVerticalRetrace = false;

            graphics.ApplyChanges();
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            //have one white pixel texture.
            _pixel = new Texture2D(GraphicsDevice, 1, 1);
            _pixel.SetData<Color>(new Color[] { Color.White });

            //set the position and angle speed of the object.
            _center = new Vector2(300, 300);
            _angle = 0;
            _angleSpeed = 4;

            //initialize the stopwatch to measure the time it takes for the object to complete a circle.
            _millisecondsPerCircle = 1;
            _stopwatch = new Stopwatch();
            _stopwatch.Start();
            //note: this value should be fairly constant
            //regardless of the fixed timestep
            //or vertical retrace.

        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// game-specific content.
        /// </summary>
        protected override void UnloadContent()
        {
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();

            //remember the angle (to measure time).
            double oldangle = _angle;

            //update the moving object:
            _angle = (_angle + _angleSpeed * gameTime.ElapsedGameTime.TotalSeconds) % (2*Math.PI);
            _position = _center + new Vector2((float)Math.Cos(_angle), (float)Math.Sin(_angle)) * 150;

            if(oldangle>_angle) //we have looped if we pass the 0.
            {
                _millisecondsPerCircle = _stopwatch.ElapsedMilliseconds;
                _stopwatch.Restart();
            }

            //record the frametime.
            _frametime = (float)gameTime.ElapsedGameTime.TotalSeconds;

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            spriteBatch.Begin();

            //draw a red moving box:
            spriteBatch.Draw(_pixel,new Rectangle((int)_position.X,(int)_position.Y,7,7),Color.Red);

            //draw the frametime:
            spriteBatch.Draw(_pixel, new Rectangle(0, 2, (int)(10000 *_frametime), 10), Color.Blue);

            //draw the time it took to complete a circle:
            spriteBatch.Draw(_pixel, new Rectangle(0, 22, (int)(_millisecondsPerCircle/10), 10), Color.Green);

            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}

```

The result is a red box going in circles. A blue bar shows the frametime (shorter without fixed timestep). The green bar shows the time it took to complete a circle. The green bar- shown after 1 completed circle, is a constant length regardless of the frametime. This shows that the red object moved equally fast in each scenario. I used bars to visualize the timeframe, since I didn't want to introduce a spritefont- just copy this code and it should work.

In the `Game()` constructor you can change the values for fixed timestep and the vsync to true or false. Note how the fixedtimestep influences the length of the blue bar. Also the vsync influences the frametime. To max out fps, set both to false.

The code for moving an object is a bit different (for demonstration purposes) but the principle of movement and frametime is the same. Hopefully this demonstrates how to `unlock` the fps and have higher framerates while the objects move at the same speed. Perhaps it helps you debug your own code.
> 1 votes

# Answer
My best guess is that you have some rounding errors. You aren't actually showing the movement code for the bullets so it's really hard to tell.

Edit: Looking at the code, it should(tm) work. It definitely works fine to do things like this in the games I've written with XNA. The thing that bothers me is that your game doesn't seem to be running at all when you set FixedTimeStep to true, so something really weird must be going on somewhere. Could it be that you didn't separate Update and Draw logic properly?

Edit2: The TargetElapsedTime is set to 16.666 seconds instead of milliseconds, so that's most likely causing the issues.
> 0 votes

---
Tags: c#, xna, timestep
---


title: How to rotate camera using mouse?

text:
# Question
Title: How to rotate camera using mouse?
I'm looking for a basic example of rotating camera using the mouse. the only problem is I'm not sure of how to rotating the camera around it target. should i do this by an algorithm or is there a method of doing this? I am also only using managed dirextx and no wrappers

# Answer
A very short cutoff tk fhis problem, if you don't want to use trigonometry, is to first translate the view matrix with the distance between the camera and the player on the +z axis, then rozate the matrix, and after that, move it to the correct place, by translating it to the player's position.

However, this is the worst and laziest solution I could think of, so if you want to have a method, that makes sort of sense, then use trigonometry.

You will need the angle aeound the y and x axis, in my example, i refer them to as xa, and ya, they also need to be in radians.

x = cos(xa) * cos(ya) y = sin(xa) * cos(ya) z = sin(ya)

To create a view matrix, first, you simply need a 4 * 4 identity matrix, then translate in the negative direction with the distance you want between the camera and player, in this example, 5.

```
1 0 0  0
0 1 0  0
0 0 1 -5
0 0 0  0

```

After this is done, rotate it on the y and x axis. The y angle is the angle around the player, the x is the "distance" from the ground.

You then multiply these matrices together

```
translateMatrix * rotationMatrix //Note: By doing the multiplication the other way around messes up things, so be aware

```

Now, you have it around the player. Only problem is, that it is placed according to the player, not the world coordinates, So, you need to translate it. The translation matrix should be made like

```
1 0 0 x
0 1 0 y
0 0 1 z
0 0 0 1

```

where x, y and z are the player position. After this, you simply multiply the two matrices together, and voilá, you're done.

I can't help in retrieving mouse coordinates in DirectX, because I never actually used it, only OpenGL, I'm just a math guy. My way of doing it would be to always get the distance between the middle of the screen, and the mouse, and do things according to that, and finally, place the mouse back at the middle of the screen.
> 1 votes

# Answer
A classic solution is to use an arcball.

Here's an example implementation using the SimpleMath wrapper for DirectXMath in the DirectX Tool Kit:

```
class ArcBall
{
public:
    ArcBall() :
        m_width(800.f),
        m_height(400.f),
        m_radius(1.f),
        m_drag(false) { Reset();  }

    void Reset()
    {
        m_qdown = m_qnow = DirectX::SimpleMath::Quaternion::Identity;
    }

    void OnBegin( int x, int y )
    {
        m_drag = true;
        m_qdown = m_qnow;
        m_downPoint = ScreenToVector(float(x), float(y));
    }

    void OnMove(int x, int y)
    {
        using namespace DirectX;
        if (m_drag)
        {
            XMVECTOR curr = ScreenToVector(float(x), float(y));

            m_qnow = XMQuaternionMultiply(m_qdown, QuatFromBallPoints(m_downPoint, curr));
            m_qnow.Normalize();
        }
    }

    void OnEnd()
    {
        m_drag = false;
    }

    void SetWindow(int width, int height)
    {
        m_width = float(width);
        m_height = float(height);
    }

    void SetRadius(float radius)
    {
        m_radius = radius;
    }

    DirectX::SimpleMath::Quaternion GetQuat() const { return m_qnow; }

    bool IsDragging() const { return m_drag; }

private:
    float                           m_width;
    float                           m_height;
    float                           m_radius;
    DirectX::SimpleMath::Quaternion m_qdown;
    DirectX::SimpleMath::Quaternion m_qnow;
    DirectX::SimpleMath::Vector3    m_downPoint;
    bool                            m_drag;

    DirectX::XMVECTOR ScreenToVector(float screenx, float screeny)
    {
        float x = -( screenx - m_width / 2.f ) / ( m_radius * m_width / 2.f );
        float y = ( screeny - m_height / 2.f ) / ( m_radius * m_height / 2.f );

        float z = 0.0f;
        float mag = x * x + y * y;

        if( mag > 1.0f )
        {
            float scale = 1.0f / sqrtf( mag );
            x *= scale;
            y *= scale;
        }
        else
            z = sqrtf( 1.0f - mag );

        return DirectX::XMVectorSet( x, y, z, 0 );
    }

    static DirectX::XMVECTOR QuatFromBallPoints( DirectX::FXMVECTOR vFrom, DirectX::FXMVECTOR vTo )
    {
        using namespace DirectX;
        XMVECTOR dot = XMVector3Dot( vFrom, vTo );
        XMVECTOR vPart = XMVector3Cross( vFrom, vTo );
        return XMVectorSelect( dot, vPart, g_XMSelect1110 );
    }
};

```

To use this class:

```
ArcBall m_ballCamera;

m_ballCamera.SetWindow(m_outputWidth, m_outputHeight);

if (m_ballCamera.IsDragging())
{
    // Rotate camera
    m_ballCamera.OnMove(mouse.x, mouse.y);
    Quaternion q = m_ballCamera.GetQuat();
    q.Inverse(m_cameraRot);
}
else if (m_mouseButtonTracker.leftButton == Mouse::ButtonStateTracker::PRESSED)
{
    m_ballCamera.OnBegin(mouse.x, mouse.y);
}

if (m_mouseButtonTracker.leftButton == Mouse::ButtonStateTracker::RELEASED)
{
    m_ballCamera.OnEnd();
}

```

See Ken Shoemake, "Arcball Rotation Control", Graphics Gems IV, pg 176 - 192
> 0 votes

---
Tags: c#, directx, matrix, directinput, directxmath
---


# Question
Title: Is it possible to trigger a loop with key input
Ok I need to know if it is possible to trigger a gameloop with a key press? ex code

```
 if (GamePad.GetState(PlayerIndex.One).Buttons.X == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Up))
        {
            ball.Update();
        }

```

obviously this is wrong because when I press the up button the ballstarts moving but stops when I release. and yes I looked online and couldn't find anything on this

# Answer
> 1 votes
Yes, make a boolean variable at the start in Game1. Like this:

```
if (ballStart)
{
    ball.update();
}

```

Next, go to where you get the input from the user and change the boolean to be true once the key is pressed. eg.

```
if (player1keyboardState.IsKeyDown(Keys.W))
{
    paddle1.direction.Y = -1;
    ballStart = true;
}

```

Hope this helps.

# Answer
> 0 votes
This is possible. As for how to do it, there are many ways. The simplest is probably to use a boolean variable. When the input is read, set that variable to true. Have a while loop use that boolean flag as its condition. When you press the button, the flag is set to true, and the loop happens. When you want to end the loop, set the flag to false again.

Again, many ways to do it. But this one is almost trivially simple.

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


# Question
Title: Check if GameComponent is ready in Unity?
I am trying to create a MessageBox in Unity, but I'm having some troubles in C#.. This is my code (I'll explain my problem later):

**MsgBox.cs**

```
public class MsgBox : MonoBehaviour
{
    private UIButton _btn_ok;  // NGUI Button
    private UILabel _caption;  // NGUI Label
    private GameObject _box;   // The message box container

    void Start()
    {
        _box = this.gameObject;
        _btn_ok = _box.transform.Find("btn_ok").GetComponent<UIButton>();
        _caption = _box.transform.Find("Title").GetComponent<UILabel>();

        // ** the line below works fine, but I don't want to change the caption here **

        // this.Caption = "This Works";
    }

    public string Caption
    {
        get
        {
            return _caption.text;
        }

        set
        {
            _caption.text = value;
        }
    }
}

```

**My Saved Prefab**

As you can see, my prefab have the MsgBox.cs attached to the Box component (wich is the \_box variable).

But this code doesn't work:

**Fail Code**

```
function createBox()
{
    GameObject wnd = (GameObject)Instantiate(Resources.Load("Box"));
    MsgBox mb = wnd.GetComponent<MsgBox>();
    bool foo = true;

    if (mb == null)
    {
        Debug.Log("MsgBox is null");
        foo = false;
    }

    if (!(mb is MsgBox))
    {
        Debug.Log("mb is not MsgBox");
        foo = false;
    }

    if (foo)
    {
        Debug.Log("passed!");
        mb.Caption = "Hello!";
    }
}

```

**Console Output**

> passed!
> NullReferenceException: Object reference not set to an instance of an object MsgBox.set\_Caption (System.String value) (at Assets/scripts/MsgBox.cs)

If I change this:

```
public string Caption
{
    get
    {
        return _caption.text;
    }

    set
    {
        _caption.text = value;
    }
}

```

to this:

```
public string Caption
{
    get
    {
        return _caption.text;
    }

    set
    {
        if (_caption == null)
            Debug.Log("Caption is null");
        else
            _caption.text = value;
    }
}

```

and call `createBox`, the console give me this:

> Caption is null

Why? Why I can't change the caption from outside the MsgBox? Maybe the `createBox()` is being called first than `Start()`?

PS. Using Unity 5 64 bit. My platform is WebGL.
PS². English is not my native language, sorry.

# Answer
> 3 votes
I notice that you're instantiating a new `MsgBox` instance and then immediately trying to use its members.

At this point, all you can guarantee has run are its `Awake()` and `OnEnable()` methods (in that order).

`Start()` is called just before its first `Update()`, which won't happen until after the function that spawns it has returned (or yielded).

Since `Start()` hasn't had a chance to run yet, `_caption` is still null.

This gives you several possible fixes, in approximate order of increasing complexity:

* Move the initialization from `MsgBox.Start` to `MsgBox.Awake` or `MsgBox.OnEnable`
* Check whether `_caption` is null before accessing its members in the `Caption` property's getters/setters, and populate it via `GetComponent` there if you need.
* Make `_caption` a public or serialized field of `MsgBox`, and wire it up in the inspector so it's already populated when you instantiate the "Box" prefab.
* Make `createBox()` a coroutine that yields after spawning the box, and resumes at the end of this frame's `Update` (ie. `yield return null`) to populate the `MsgBox` instance after `Start` has had a chance to run.

Really, the easiest thing is just to use `Awake` or `OnEnable`. The only reason I mention the other possible fixes is that if we get into the habit of putting everything in these methods, then it becomes very difficult to move something even earlier when we run into order of execution bugs. So, I try to be sparing and only use those when I need to. If this is the only entanglement for this class though, then there's little risk.

---
Tags: unity, game-component
---


title: Local player always at same position

text:
# Question
Title: Local player always at same position
I am trying out UNET ( Unity Multiplayer Service ) and I am building a space invaders like game but with two players at each side of the screen shooting at each other.

I want the local player to always be at the bottom of the screen and see the enemy at the top.

I tried checking isLocalPlayer and isServer and only if both are false -\> this means it's the enemy player and change his transform and rotation to be facing downwards and be at the top. But this brings unexpected behavior like spawning the bullets on the original position.

# Answer
You'll want to take a different approach for this. Rather than trying to change the players' positions based on who the local player is, move/flip the camera to orient around the local player. Here's one way you could do this:

Create a component to attach to your camera:

```
using UnityEngine;
using System.Collections;

public class PlayerCamera : MonoBehaviour {
    [SerializeField]
    [Tooltip("How far to offset the camera from the local player's starting position")]
    Vector3 offset;

    public void OrientOn(Transform target) {
        transform.position = target.position + offset;
        transform.rotation = target.rotation;
    }
}

```

Then add something like this inside your player's NetworkBehaviour:

```
    [SerializeField]
    PlayerCamera playerCam;

    public override void OnStartLocalPlayer() {
        // This will only be called on the local player
        playerCam.OrientOn(transform);
    }

```

You'll want to tweak offset to suit your purposes, and may want to make some changes, but this should make sure the camera always starts oriented correctly in relation to the local player.

As a side note, you'll want to make sure your player movement is all being done with localPosition instead of position. This will make movement work correctly independent of the player's actual facing.

I'd recommend giving the NetworkBehaviour scripting page a read. It's a great starting point if you want to figure out the guts of UNET. The Network callbacks and server/client functions sections in particular are quite useful.
> 1 votes

---
Tags: multiplayer, unity, unity-networking
---


# Question
Title: Creating an isometric map with hexagonal tiles for iPad
I'm new to game development, so I need a little help.

I have to write down a little game which has a floor with hexagonal tiles, but it must be seen in an isometric view like The Sims.

Ignoring the UIKit way, I used CoreGraphics method and I managed to draw a hexagonal map and to get it working but this only in the orthogonal view.

Hoping that Cocos2D could help me, I've studied a little, but I only see that the hexagonal maps are supported only in orthogonal mode. In the stackoverflow community, someone who understand about that much more than me, told me that I simply cannot draw it with Cocos2D tiles, so, thinking at this image:

http://www.issamtp.org/gnfGr.jpg

I guessed that there must be another way, which I hope is not to calculate the "skew" manually.

The nearest results I managed to obtain were with CAAffineTransform which doesn't give the depth effect seen in the image above (at least I didn't managed to give it) or with CATransform3D without perspective.

Can someone tell me if I'm in the right way, and if so, how should I set the parameters of the Transform matrix to get the desired effect?

EDIT:

Here's the code I used

```
sfondo = [[Sfondo alloc] initWithFrame:CGRectMake(sfondoX, sfondoY, sfondoWidth, sfondoHeight)];
/*sfondo = [[Sfondo alloc] initWithFrame:CGRectMake(200, 200, 300, 300)];*/
[sfondo setBackgroundColor:[UIColor clearColor]];
[sfondo setDelegate:self];

CGAffineTransform transform = CGAffineTransformIdentity;
transform.b = 0.5;
transform.a = 1;
sfondo.transform = transform;

```

# Answer
From the image you posted it looks like the only thing you did wrong was the order in which you applied the scale and rotation to your transformation. I don't have any experience with Cocos2D but I just mocked it up in XNA and here are the results:

And here's the transformation matrix I used in XNA. See if you can find any correlation to your code:

```
Matrix matrix = Matrix.CreateTranslation(-origin) *
                Matrix.CreateRotationZ(MathHelper.ToRadians(45f)) *
                Matrix.CreateScale(1f, 0.5f, 0f) *
                Matrix.CreateTranslation(position);

```

The origin and position were just to position it in the middle of the screen and aren't really important here. What's important is that you perform the rotation before the scaling otherwise you'll get the result depicted above.

**Edit**

From taking a quick look at the documentation it seems to me that you should start with `CGAffineTransformIdentity`, apply `CGAffineTransformRotate` to it, and finally apply `CGAffineTransformScale` to the result of the previous operation. I think that should be enough to figure it out.
> 7 votes

# Answer
For anyone looking at this by googling "cocos2d isometric transformation rotate skew" or something like that like I was: I figured out the right skews and rotations. A two-layer approach was needed due to the lack of a diagonal scale or Z rotation. For javascript devs: this makes an isometrically transformed DrawNode. I'm not sure what performance impact this has, but since it's only using the native functions I don't believe it has much if any. For other languages, it should be trivial to port.

```
var MapContainer = cc.Layer.extend({
  ctor: function(){
    this._super();

    this.scaleX = .947;
    this.setAnchorPoint({x:0, y:0});
    this.drawNode = new MapDrawNode();
    this.addChild(this.drawNode);

    return true;
  },
  drawNode: null
});
var MapDrawNode = cc.DrawNode.extend({
  ctor: function(){
    this._super();

    this.setAnchorPoint({x:0, y:0});
    this.y = 360; // shifts everything up, adjust as needed. Mine is 1/2 window size
    this.transform();

    // Your init code here

    return true;
  },
  transform: function(){
    this.setScaleX(0.81649658);
    this.setScaleY(0.81649658);
    this.setSkewX(16.3);
    this.setSkewY(16.3);
    this.setRotationY(45);
    this.setRotationX(45);
  }
});

```

Proof:
> 0 votes

---
Tags: tiles, isometric, cocos2d, objective-c, hexagonal-grid
---


# Question
Title: How to correctly sync an ArrayList of GameObjects on a server/client
I'm experimenting with networking in Unity and I can't seem to get an ArrayList of GameObjects to sync from the server to the client.

Here is the relevant code:

```
[SyncVar]
ArrayList walls = new ArrayList();

void Start ()
{
    grid = new bool[width, height];

    if(isServer)
    {
        // This is an algorithm to generate a Maze.
        // It adds the walls of the maze (GameObjects)
        // to the walls array as the algorithm runs.
        CarvePassagesFrom(0, 0, south, grid);
    }
    // If this instance of the game isn't the server, we want to get the
    // already generated maze from the walls ArrayList (that should have synced)
    else
    {
        foreach (GameObject go in walls)
        {
            Debug.Log("Creating game object: " + go);
            Instantiate(go);
        }
    }
}

```

I have the console tell me how many walls were added in total after the algorithm has run and the walls have definitely been added. But on the client the size of the walls array is 0.

Am I missing something really obvious about the syncing of variables?

# Answer
The `[SyncVar]` attribute only works on simple data types. You can't synchronize generic objects, or lists/arrays of generic objects. `SyncListStruct` will allow you to synchronize lists of structs, however. Probably the closest thing you can get to what you want (without writing your on `OnSerialize` and `OnDeserialize` methods) is something like this:

```
public struct Wall {
    // define wall members here
}

public class SyncListWall : SyncListStruct<Wall> {}

public class MyScript : NetworkBehaviour {

    public SyncListWall walls = new SyncListWall();

}

```

You'll then have build your local ArrayList from the data in the `SyncListStruct`.

Note that you don't need any attributes as with `[SyncVar]`. Also there are a couple things that will get you if you're not careful:

* You need to create a class that inherits from SyncListStruct - you can't just use it directly.
* The class declaration has to be above where the synclist gets used in the class file. If it's after (eg below the NetworkBehaviour) you won't get any errors or warnings, but the list contents won't propagate over the network.

More info on SyncListStruct. In particular, look at SyncListChanged, which you'll need to populate to handle changes to the list after initialization.
> 1 votes

---
Tags: unity, unity-networking
---


# Question
Title: How can the Server send a message to a single Client?
I'm trying to send an `Rpc`, or any sort of message, to a specific client instead of to them all.

I'm completely at the loss trying to associate a `NetworkConnection` with its own authoritative spawned player (from `playerPrefab`).

If I let the `NetworkManager` auto-spawn it, then I don't know how to get the connection from the player object.

If I `override OnServerReady` and I spawn it myself, then it has no authority on the client and I don't know how to give it.

I've browsed all sort of documentation but I couldn't find anything useful. Obviously there must be a way to do that, but I really can't find it.

# Answer
What you want is `NetworkServer.SendToClient` or `NetworkServer.SendToClientOfPlayer`. You'll want to read up on Network Messages, and then check out `NetworkServer` here.
> 3 votes

---
Tags: unity, unity-networking
---


# Question
Title: Unity 5.x Network Synchronization Concepts
Bear with me, It will be long read^^

I am working on the new Unity Networking system. I was using Photon and old (legacy) unity network API's before. But as it seems there are some good benefits of the new system than the previous ones, so I want to stick with it. (Despite of it being uncompleted)

But there are some points that doesn't make sense to me with the API. Data Sync for example. So, in the old systems (both in Photon and legacy unet) we had functions called OnPhotonSerializeView or OnSerializeNetworkView depending on which API we use. Both API's are very similar as you may know. So in these functions we could send and recieve data between clients and server. Which makes sense, and was really usefull.

But aperantly they changed this concept, (or it still exists, and i couldn't find it)

There is a new thing called \[SyncVar\], which syncs the data "ONLY" from server to client automatically. (Which really, literally doesn't make sense, I mean why not sync both server to client AND client to server? That would make everything much easier)

According to the documents, you can ONLY send data from client to server by using \[Command\]'s. Which is basically (as far as I understand), "one way" version of old good \[RPC\] calls. Instead of calling function in all other clients, it calls it in the server.

So, you can send data to server with function parameters like the way we did it with the old \[RPC\]'s before. Which is usefull on point but If this is the only way to send data to server, then it doesn't make any sense to me..

I mean there are variables that needs to be kept synced all the time, back and forth, like position or rotation vectors. And sending them with \[Command\] calls, contradicts with the concept of network framework in my mind. We used to avoid this kind of situation before, right? Why make it the obligation now?

Or are there simply any other ways to send data from client to server that I couldn't find yet? There is a custom serialization with the \[SyncVar\], with OnSerialization and OnDeserializaton functions. Which really looks like the good old OnSerialize functions but apperantly it's diffrent as it does what the \[SyncVar\] does. OnSerialization is only called on server, and Deserialization is only called on client. So we can only send from server to client even with it.

If \[Command\] is the only way to send data to server, please say so. And clarification about why this concept is reasonable would be really nice.

Please enlighten me more with the new concepts of the new UNET framework. Thanks in advance for any help.

# Answer
> 2 votes
In the HLAPI, these are the basic ways to send data from client to server:

* `NetworkTransform` will allow position/rotation/velocity to be sent to server if the player is set authoritative.
* `Command` as you noticed.
* Network Messages

The basic reasoning behind this is that UNET is intended to be authoritative by nature. Essentially, the clients aren't allowed to directly alter server state (the sort-of exception being `NetworkTransform`, though there are callbacks to allow the server to validate all moves). They request server actions via `Command` and notify of events via messages. The old networking system, and Photon, are not designed to be server authoritative, which is why they are/were different.

---
Tags: unity, synchronization, unity-networking
---


title: SDL Convert pixel format

text:
# Question
Title: SDL Convert pixel format
I have two pixes stored in a 32 bit unsigned integer (4 bytes per pixel, using SDL's types for convenience):

```
Uint32 pixel1;        // Source pixel, format: SDL_PIXELFORMAT_BGRA8888
Uint32 pixel2_format; // Format of the pixel2 (can change)
Uint32 pixel2;        // Destination pixel

```

How can I convert the format from `pixel1` to `pixel2`?

# Answer
If I understand it right, you are asking how to extract bites of one bitmask and set it on the other, for example :

```
const uint mask = 0x000000FF; //single color mask
const uint aOff = 3 * 8; //offsets of colors from the end for ARGB
const uint rOff = 2 * 8;
const uint gOff = 1 * 8;
const uint bOff = 0 * 8;

uint pixel1 = 0xFFFF0000; //red in ARGB
uint pixel2 = 0x0;
pixel2 |= ((pixel1 & (mask << bOff)) >> bOff) << (3 * 8);//set b
pixel2 |= ((pixel1 & (mask << gOff)) >> gOff) << (2 * 8);//set g
pixel2 |= ((pixel1 & (mask << rOff)) >> rOff) << (1 * 8);//set r
pixel2 |= ((pixel1 & (mask << aOff)) >> aOff) << (0 * 8);//set a

```

first, you create appropriate mask `(mask << bOff)` by shifting single color mask to correct position (alternatively, because it is static value tied to source pixel format so you can pre-compute it), then you extract all bits of the color channel by `pixel1 & mask` and shift them to get the value `value >> bOff`. After that you shift the value to its correct position in BGRA8888 format `value << (pos * 8)` and last you *or* it with zeroed BGRA8888 pixed `pixel2 |= shiftedValue`.
You can skip some shifting if you know the formats in advance and hardcode it.
> 1 votes

# Answer
Ok, I had to add this answer because I found something on my own:
Basically there is this function `SDL_ConvertPixels()` *hidden in the wiki* and it's located inside `SDL_surface.h` header and not inside `SDL_pixels.h` (mystery...). This function converts pixels from any supported PixelFormat to another one.

Plus, **a suggestion for everybody**: When working with bits, remember to check the endianess of your machine or you'll get pixels with inverted colors (like I did...)!
> 0 votes

---
Tags: sdl2, pixel
---


# Question
Title: Can I generate character with several layers?
*Newbie question:* I wonder if it is possible in terms of performance to generate characters in several layers in phaser (and in general). And overall if it is a good idea/practice in terms of pro/cons.

For instance, one character would be the sum of the following layers (from top to bottom)

* Hairs
* Face
* Head
* hands and forearms
* clothes and shoes
* arms, legs, neck and feet

I suppose that I will have to realize most of the animations for every layers and it will not be possible to change the layer orders during an animation, but by combining all these layers, I could generate more combinations, hence more characters.

# Answer
The short answer is yes.

The long answer is that the specifics of how to do it massively depends on how you handle drawing your characters.

If you use skeletal animations (like when using spine), then you can easily exchange bits of your character by just replacing the texture of it. (Since in skeletal animation systems your character is separated into parts anyway).

You can do the same thing when you use sprite sheets too, but it is slightly more complicated. You already had the right general idea in your post. You split the animation up into the parts that you want to combine **and** you need to remember a draw order for all those parts for each animation. But then you can draw each frame of an animation easily by just combining the parts together.

The drawback is that you need to make a full set of animations for each part, since every hat for example has to move the same in every animation, otherwise some combinations will just look weird.

tl;dr: It is definitely possible and it is much easier if you use skeletal animation.
> 1 votes

---
Tags: character, phaser
---


# Question
Title: How to make an event happen only at the first start of the game?
I want to know how to make something happen only once like a tutorial in a game which appears only when you first start your game and then when your game got saved to a further point it never appears again even when you close your game and start again.

I want to give players some amount of gold when they first got their hands on my game ... but I do not want to give them that again and again whenever they restart the game ...

So I want to know how to make something happen only once in a game application..

I hope you get my point ... thanks ..

# Answer
> 2 votes
You'll want to create some form of persistent data storage. Persistent data, if you're not familiar, is data that can be saved/stored on the hard drive for use in-between scenes, after the game/computer has been shut down, etc. In short, you're writing it to a file of some kind. More info on persistent data can be found here.

As Draco18s mentioned in the comments, your best bet is to store some kind of `OfferTutorial` variable in persistent data. By default, you'll have this set as `OfferTutorial = true`.

Once the user has completed the tutorial and earned the reward, you would switch this variable to `OfferTutorial = false`.

On load, simply check this variable to determine if you want to offer the tutorial to the user.

# Answer
> 1 votes
It is my normal practice in my every game. First I'd like you to add a small script named `Utils.cs` made by me that I do use in my every game. No such requirement but easy to handle these kind of stuff. Main benifit of this script is you can use `bool` in `PlayerPrefs` through `int`.

**Utils.cs**

```
using UnityEngine;
using System.Collections;

public class Utils : MonoBehaviour
{

    public static void SetInt (string key, int value)
    {
        PlayerPrefs.SetInt (key, value);
    }

    public static int GetInt (string key)
    {
        return PlayerPrefs.GetInt (key);
    }

    public static void SetString (string key, string value)
    {
        PlayerPrefs.SetString (key, value);
    }

    public static string GetString (string key)
    {
        return PlayerPrefs.GetString (key);
    }

    public static void SetBool (string key, bool value)
    {
        if (value)
            PlayerPrefs.SetInt (key, 1);
        else
            PlayerPrefs.SetInt (key, 0);
    }

    public static bool GetBool (string key)
    {
        int val = PlayerPrefs.GetInt (key);
        if (val == 1)
            return true;
        return false;
    }
}

```

Now in any script that runs only once per game launch (script in splash screen for example), you can handle very first launch like,

**SplashScreen script**

```
void Start()
{
    if (!Utils.GetBool ("isAppLaunchedFirstTime")) {
            Utils.SetBool ("isAppLaunchedFirstTime", true);
            //TODO: Set initial coins
            //TODO: Set sound flag to true
            //TODO: Set tutorial flag to true
            //TODO: Whatever you want to do only once
        }
}

```

---
Tags: unity, savegame
---


# Question
Title: How does Navigation Mesh path-finding work?
I want to understand how navmeshes work, how to implement them and why it is better than other types of pathing systems.

# Answer
It is same as waypoint pathfinding, only instead of way-points you have way-polygons and You can infer few things about navimesh from it:

* way-polygons are areas where entities can safely walk
    + other areas should probably be not considered
    + way-points need to do leap of faith into space between them; remember NPCs stucking in walls? It was at places where two waypoints were not directly connected.
* There is potentially less nodes (because polygons are biger)
    + Therefore it is most likely faster
    + Therefore it has potentially smaller memory requirements
* It is more realistic (because polygon's area contains in theory infinite amount of points)
> 7 votes

# Answer
Generally they are used with some kind of enhanced A\* algorithm (takes into account jump or fly links for 3D pathfinding). In that way it isn't really a different system than anything else, its more a way of generating a normal pathfinding network directly from high-poly (well, relatively speaking) environment or terrain. For whatever reason we call them beacons here, but the idea is the same, some kind of automated process runs on each map and produces a simple set of connections that can have A\* run on them in a reasonable time-frames. If you tried pathfinding against the raw underlying data it would be too slow for a game because of the density of the mesh.
> 2 votes

# Answer
There are many ways you can do it. A\* and such is a good option, but lacks in documentation. You could do something like place nodes quasi-randomly around the map and check which nodes can see each other and build a little web of nodes. Not the most optimal but easy to understand.
> 0 votes

---
Tags: algorithm, path-finding
---


# Question
Title: Continous repeatable object/image moving horizontally unity3d
I want to move objects on the screen horizontally. And the user has to pop the object by touching it. When user touch it, it gets destroyed and new object comes randomly.

For experimenting, I used Unity's Scroll Rect to move them. What can be the best solution for this.

# Answer
Do not use scroll rect , if the objects are not ui elements. The simple solution will be to make one parent object and make all these elements as child. Then use offset to set local position for all the child elements. To move them you just need to move the parent object. And to add new elements add them to the parent with local position defined by the offset.
> 1 votes

# Answer
The best solution near me to do so is to attach a small script to every object, that will move your object and handle touch to itself.

You can create a script that'd attach to your objects like,

**Assumptions:**

I am moving object towards -ve x-axis. You can play around with this.

```
using UnityEngine;
using System.Collections;

public float _speed = 0.01f;

public class MoveObject : MonoBehaviour
{

    // Use this for initialization
    void Start ()
    {

    }

    // Update is called once per frame
    void Update ()
    {
        transform.position = Vector3.MoveTowards (transform.position, new Vector3 (transform.position.x - 0.1f, transform.position.y, transform.position.z), _speed);
    }

    void OnMouseDown ()
    {
        Destroy (gameObject);
    }

    void OnDestroy ()
    {
        // TODO: Create another object here
        Debug.Log (name + " destroyed");
    }
}

```
> 1 votes

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


# Question
Title: Problem with Input.GetKeyDown to set a counter in Unity: multiple values in only one pressing
Using Unity 5, I want to use have one keyboard key ("f") increase a counter when pressed. It means, using Input.GetKeyDown("f") function in a way that: if "f" is pressed when the counter=1, then the counter is set to be equal 2. If counter was equal 2 when "f" is pressed, then counter is set to 3.

However, it does not work properly: it seems that Unity detects the key being pressed many times, no matter if it was only pressed once. See the code that illustrates the situation:

```
using UnityEngine;
using System.Collections;

public class TestingKeyGetRecursion : MonoBehaviour {

int counter = 1;

void Update () {

    if(counter == 1 && Input.GetKeyDown("f"))
    {
        counter = 2;
        Debug.Log(counter);
    }
    if(counter == 2 && Input.GetKeyDown("f"))
    {
        counter = 3;
        Debug.Log(counter);
    }
    if(counter == 3 && Input.GetKeyDown("f"))
    {
        counter = 1;
        Debug.Log(counter);
    }
}

void OnGUI()
{
    GUI.Label(new Rect(30, 10, 250, 20),  "counter: " + counter.ToString());
}
}

```

As you can see in the console if you run the above example, the values are properly set into the counter variable and printed in the console. However, it happens several times in the same key-hit and, in the end, the counter ends up equal as it started, i.e. equal 1.

Can anyone please explain:

1) why does the Engine behave like that;

2) is there a way to solve such situation? I cannot substitute the counter with a bool variable and just do "counter != counter" when "f" is pressed.

# Answer
> 5 votes
It is due to your flow is confusing for engine as it will try to execute your every check in every frame. Try to implement with `else` or with single statement like,

```
using UnityEngine;
using System.Collections;

public class TestingKeyGetRecursion : MonoBehaviour {

    int counter = 1;

    void Update ()
    {
        if (Input.GetKeyDown(KeyCode.F))
        {
            if (++counter >= 4)
                counter = 1;
            Debug.Log(counter);
        }

        // ======== OR ======= //
        // On DMGregory's advise

        if (Input.GetKeyDown(KeyCode.F))
        {
            counter = (counter % 3) + 1;
            Debug.Log(counter);
        }
    }

    void OnGUI()
    {
        GUI.Label(new Rect(30, 10, 250, 20),  "counter: " + counter.ToString());
    }
}

```

# Answer
> 6 votes
To answer your first Question *"why does the Engine behave like this"* I would add the following:

The Engine does not actually detect the key being pressed multiple times. What you need to keep in mind here is that the "was pressed" state of the key does not reset until the next frame, and your code will be executed in a single frame. Furthermore, every *if* statement will be evaluated. So successively going through your update method what happens is

* We start with counter = 1, and we assume key was pressed in this frame
* Now we check if key was pressed (in this frame) and counter is 1 =\> yes, so we set counter to 2
* Now we check if key was pressed (in this frame) and counter is 2 =\> **yes** it is, since we just set it to 2! So it gets set to 3
* Now we check if key was pressed (in this frame) and counter is 3 =\> again, we just set it to 3, so we set it to 1 again

Your second Question *"is there a way to solve such situation"* has been answered by others already, so I won't write any code here, but for completeness sake: To solve this, you can simply make sure that not every *if* statement is being evaluated during the same frame by using *else if* on all but the first one. That way, as soon as it jumps into one of the *(else) if* statements, it will not bother checking the others in this frame anymore. See RianF2's answer for the *else if* code or Hamza Hasan's answer for a nice and short code snippet that does the same.

# Answer
> 2 votes
Try adding an "else-if" instead of a normal "if". So your update method should look like this:

```
void Update () {

    if(counter == 1 && Input.GetKeyDown("f"))
    {
        counter = 2;
        Debug.Log(counter);
    }
    else if(counter == 2 && Input.GetKeyDown("f"))
    {
        counter = 3;
        Debug.Log(counter);
    }
    else if(counter == 3 && Input.GetKeyDown("f"))
    {
        counter = 1;
        Debug.Log(counter);
    }
}

```

---
Tags: unity, keyboard, bug
---


title: What is "game logic code?"

text:
# Question
Title: What is "game logic code?"
I'm using C#/XNA and have been told quite a few times not to mix update code with draw code -- and I'm certain I'm not! But could anyone please describe what exactly is 'logic code'?

As seen here: http://blogs.msdn.com/b/shawnhar/archive/2007/07/25/understanding-gametime.aspx

> \[...\] make sure you put all your game logic inside the Update method (not in Draw!) and everything will run at a nice constant speed.

I'm asking this since my game's speed is fluctuating relative to the FPS. Slow FPS equals slow-moving objects and visa versa. And yes, I am including the expected `position += speed * (float)gt.ElapsedGameTime.TotalSeconds;` code.

This is probably a big rookie question, but I just want to be absolutely clear on the definition of this.

# Answer
> 102 votes
Does it change the state of your game world? It's logic code.

Does it display the state of the game world? It's rendering code.

# Answer
> 24 votes
Your separation is correct if:

* Calling Draw() multiple times in a row without any interspersed calls to Update() would never result in any visible changes between the calls.
* Calling Update() multiple times in a row without an interspersed call to Draw() would be like playing the game with the screen turned off: everything moves along perfectly and consistently, you just can't see it.

# Answer
> 8 votes
The point here is separation of Model things that are not the model.

The Game Logic is the Model as referred to in

These are all different, related, software architecture patterns. But in all case the Model is the same thing it's the real logic and the real state.

It is the when making business software it is sometimes called business logic, and encoded some of the businesses policies. Eg if your are coding something for a bank, to calculate credit card bills, then the functionality to cause someone to not have to pay interest if they clear their debt in less than 30 days, is part of the business logic, it lives in the model. It does not for example live on one of the displaying layers. The code for printing a bill, does not for example, edit the text based on their actions. This example perhaps highlights why you might want to organise your code that way.

Similar goes for game logic.

Imagine that at some point your game was ported to another console. It might help to imagine something really different to your current target. Eg if you are targeting somehting with a gamepad/controller, Imagine your game being ported to a touchscreen tablet. The game logic is the part of the code that does not change when you port it.

If your game were something like a military strategy game, imagine it being converted to the worlds most complex boardgame. The game logic is the sections of code, that directly correspond to lines in the rule book. (Not all the lines in the rule book, not the ones about moving pieces, but some.).

The game logic is the thing that never changes, no matter the form.

---
Tags: terminology
---


# Question
Title: Should I encrypt my multiplayer network traffic?
My plan has been to use RSA to exchange AES session-keys with a client, which is then used for all the usual in-game stuff. Clients never connect with each other, all communication is client to server only.

The question is: Would I be wasting my time by encrypting the communication? How are big AAA multiplayer games doing it? If I do do encryption, is the basic scheme I mentioned a good start?

# Answer
> **This is a community-wiki answer. When you can think of other advantages and disadvantages, feel free to edit.**

**Advantages:**

* Makes it a bit harder (but not impossible!) to reverse-engineer your protocol with a packet analyzer
* Protects your users privacy. This is especially relevant when you have passwords transfered over the same channel.
* Protects your game from any cheats based on network sniffing. This is really only applicable for LAN gameplay, though. Sniffing on the Internet is hard, unless the attacker is an internet service provider.
* Protects your game from cheats based on client impersonation through packet injection (really only applicable to UDP)
* Makes it harder for firewalls to block your game.

**Disadvantages:**

* Makes it also harder for you to debug with a packet analyzer
* Encryption and decryption costs some CPU cycles which makes the overall hardware requirements higher (but the cost is not as high as you would expect - modern CPUs often have optimized instruction-sets for common cryptographic algorithms)
* Costs time to implement (which you can and definitely should reduce by using a library)
* You need to manage the public and private keys for your servers. This isn't that difficult when you host all your servers yourself because you can then distribute their public keys with your game executable. But when you want your community to host servers, they will need a certificate authority to get their keys signed, or you lose protection from MitM attacks.
> 1 votes

---
Tags: networking, multiplayer, security
---


# Question
Title: How do I correctly make character sprite direction match player inputs?
In my top down game I can move the character around and the character will even face the direction he is moving.

However, there is some weird behavior I'm having: when you hold down one direction and then another direction the graphic updates to that direction, but if you keep holding the direction prior it does not update to the correct graphic.

Here is my function that handles the rendering of the player graphic. When that happens it looks like the character is walking sideways. I haven't added animation yet. It just tries to have the right graphic with the corresponding direction.

```
render: function() {
      var game = roguelike.game;
      var map = roguelike.map;
      var image = game.library.images[1];
      var ctx = game.library.ctx;
      var centerX = game.library.canvas.width / 2 - map.tileSize / 2;
      var centerY = game.library.canvas.height / 2 - map.tileSize / 2;
      switch(this.facing) {
        case "left":
          var cropX = 1 * map.tileSize;
          var cropY = 5 * map.tileSize;
          break;
        case "up":
          var cropX = 1 * map.tileSize;
          var cropY = 7 * map.tileSize;
          break;
        case "right":
          var cropX = 1 * map.tileSize;
          var cropY = 6 * map.tileSize;
          break;
        case "down":
          var cropX = 1 * map.tileSize;
          var cropY = 4 * map.tileSize;
          break;
      }
      ctx.drawImage(
        image,
        cropX,
        cropY,
        map.tileSize,
        map.tileSize,
        centerX,
        centerY,
        map.tileSize,
        map.tileSize
      );
    }

```

Also you might want to see how I handle my `player.facing` state. I do it this way.

```
window.onkeydown = function (event) {
  var player = roguelike.player;
  switch (event.keyCode) {
   //Left
   case 37:
    player.facing = "left";
    player.moving.left = true;
    break;
   //Up
   case 38:
    player.facing = "up";
     player.moving.up = true;
     break;
   //Right
   case 39:
    player.facing = "right";
    player.moving.right = true;
    break;
   //Down
   case 40:
    player.facing = "down";
    player.moving.down = true;
    break;
 }
};

```

# Answer
> 2 votes
Similar to RDeving's answer, here's my usual code:

```
var keys = {};
window.onkeydown = function(evt) {
     keys[evt.keyCode] = true;
}
window.onkeyup = function(evt) {
    delete keys[evt.keyCode];
}

```

Then, in your update loop:

```
if (37 in keys) {
    //keycode 39 is down
}
if (38 in keys) {
    //keycode 38 is down
}
// ... etc

```

# Answer
> 1 votes
The problem is that you set the facing variable depending on the last keypress. Set an object with

```
Var keypressed = {};

```

An then, in your keypress events handler set the keypressed as

```
Keypressed[e.keycode] = true;

```

And implement a key release event so it sets keypressed to false.

In the loop just check for the pressed keys and face depending on the keys that still pressed

# Answer
> 0 votes
As pixelmike mentioned, the problem might be that the `keydown` event executes every x milliseconds while the key is being pressed, and that is what produces the wrong `player.facing` value. Since you want the player to move in only one direction, the one of the last key pressed (and I guess that you set `player.moving.x = false` somewhere because the movement works properly, I would try doing something like this:

```
player.facing = (player.moving.left&&"left")||(player.moving.right&&"right")... ;

```

That way, the player will always face and move in the same direction.

---
Tags: javascript, movement, html-canvas, game-state
---


title: WiFi Game Controller Protocol

text:
# Question
Title: WiFi Game Controller Protocol
I'm wanting to use mobile devices to control a game. I'd like to use an industry standard protocol for wifi game controllers rather than roll my own, but have been unable to find any standard.

Does there exist any industry standard wifi game controller protocol? Is there some unofficial protocol many implement, preferably with quality Android/iPhone client implementations available?

# Answer
I would say there is no such standard, because there are no WiFi game controllers. All the wireless game controllers I checked use either Bluetooth or some proprietary wireless data transmission.

This makes sense as WiFi typically uses more power than Bluetooth and is harder to set up. A wireless network might not even be available on location.

That being said, there exist some apps for Android as well as for the iPhone just for that purpose. Maybe you could contact the authors for how they work.
> 1 votes

---
Tags: android, iphone, controllers
---