title: Box2d Fixed Timestep and Interpolation

text:
# Question
Title: Box2d Fixed Timestep and Interpolation
I am using libGDX and I have problems implementing the box2d fixed timestep with interpolation.

This is my code:

```
private void updateWorld() {

    accumulator += Gdx.graphics.getDeltaTime();

    while (accumulator>= step) { // The step is 1/10

        copyCurrentPosition();

        world.step(step, 8, 3);
        accumulator -= step;
    }

    interpolate(accumulator / step);
}

private void copyCurrentPosition() {
    prevPosition = new Vector2(player.body.getPosition().x, player.body.getPosition().y);
}

private void interpolate(float alpha) {
    player.body.setTransform(player.body.getPosition().x * alpha + prevPosition.x * (1.0f - alpha), player.body.getPosition().y * alpha + prevPosition.y * (1.0f - alpha), 0);
}

```

# Answer
That's a pretty large time step (0.1s), which almost certainly spans multiple render frames. The LibGDX docs recommend either `1/45f` or `1/300f` for that argument. I've personally been using `1/300f` and it works fine.

The docs also recommend `6` and `2` (vs your `8` and `3`) for the other arguments, but these are close enough together it's probably not *that* critical.
> 1 votes

---
Tags: libgdx, box2d, interpolation, fixed-timestep
---


# Question
Title: How do I calculate hex coordinates from a ring and index?
I am trying to implement field of view (FOV) in a hex grid. I am using the cube coordinate system from here. Then, I am using shadow casting to find FOV as from here.

I have a system like in the image, below. The numbers at the corners are coordinates. The numbers in the center are formatted as **`[Ring index],[Hex Index]`**.

I need to used both ring index and hex index to calculate angles used for shadow casting. I spent several days on it, but I still cannot find a way to make these two sets of numbers convertible.

How do I calculate hex coordinates from a ring and index?

# Answer
> 3 votes
First, let's define a standard ordering of basis vectors to use. These are the offsets to each of the six hexes in the closest ring around our center, in clockwise order from top-left.

```
int3[] spokes = {
   new int3( 0,  1, -1),
   new int3( 1,  0, -1),
   new int3( 1, -1,  0),
   new int3( 0, -1,  1),
   new int3(-1,  0,  1),
   new int3(-1,  1,  0)
};

```

These mark where the ring turns a corner. From a corner tile in each spoke direction, the ring continues clockwise along a nice predictable straight line, until it hits the corner tile in the next spoke direction.

So, we can reach any ring coordinates in just two moves:

* A straight line out from the center, along a spoke direction, to one of the corner tiles
* A straight line clockwise from a corner tile, to the tile we want.

Here's how that might look in code:

```
int3 RingIndexToCubeCoords(int3 center, int radius, int index) {

    // Handle degenerate case:
    if(radius == 0)
        return center;

    // Number of tiles in a complete ring:
    int ringSize = 6 * radius;

    // Convert to a zero-based index starting from spoke[0].
    // This makes the math simpler in the next steps.
    // The modulo at the end wraps the end of the ring back around to zero.
    int tweakedIndex = (index + ceil(radius/2) - 1) % ringSize;

    // Find the closest spoke counter-clockwise from the given index.
    // (ie. "Which sixth of the ring are we in?")
    int spokeIndex = floor(tweakedIndex/radius);

    // Compute the ring index of the corner tile at the end of this spoke:
    int cornerIndex = spokeIndex * radius;

    // Compute how much further we still need to go:
    int excess = tweakedIndex - cornerIndex;

    // Start at the center of the ring.
    int3 result = center;

    // Progress outward along the spoke to the corner tile at the given radius.
    result += radius * spoke[spokeIndex];

    // Proceed clockwise along the ring to the chosen tile:
    result += excess * spoke[(spokeIndex + 2) % 6];

    return result;
}

```

The reverse can be done too:

```
void CubeCoordsToRingIndex(int3 tile, int3 center, out int radius, out int index) {
    // Compute the difference between the tile's position and the center.
    int3 offset = tile - center;
    int3 absOffset = abs(offset); // componentwise absolute value.

    int spokeIndex = 0;

    // Find which spoke is at the counter-clockwise end of this span.
    // There are less branchy ways to do this, but they're more cryptic-looking.
    if(absOffset.y >= absOffset.x) {
        if(absOffset.z >= absOffset.y) {
            spokeIndex = offset.z > 0 ? 3 : 0;
        } else {
            spokeIndex = offset.y > 0 ? 5 : 2;
        }
    } else if (absOffset.x >= absOffset.z) {
        spokeIndex = offset.x > 0 ? 1 : 4;
    } else {
        spokeIndex = offset.z > 0 ? 3 : 0;
    }

    // Compute radius as half the Manhattan distance from the center.
    radius = (absOffset.x + absOffset.y + absOffset.z)/2;

    // Find the counter-clockwise corner tile.
    int3 corner = radius * spokes[spokeIndex];

    // Find the distance of our tile from this corner tile.
    absOffset = abs(tile - corner);
    int excess = (absOffset.x + absOffset.y + absOffset.z)/2;

    // Our tile is at the corner's index, plus this excess.
    index = radius * spokeIndex + excess;

    // Convert indexing system to one that starts near the middle of the top of the ring.
    int ringSize = 6 * radius;
    index = (index + ringSize - ceil(radius/2))) % ringSize + 1;
}

```

---
Tags: algorithm, hexagonal-grid
---


# Question
Title: How to integrate Tiled maps and collision detection with pygame?
I have been using pygame to make a simple rpg pokemon style game. To create maps I have used the Tiled map editor and then loading them into pygame using pytmx.

I have heard that you can add object layers in Tiled to your map, and then use this information for collision detection within your game engine (in this case pygame). Unfortunately, while I know how to load the tmx file into my pygame game, I have no idea how to use the object layers for collision detection.

Can anyone provide a minimal example on how to do this? The documentation that I have come across for Tiled appears to be quite minimal and still an active work in progress. As a result I have not been able to find information on using Tiled and object layers for collision detection in pygame.

# Answer
Since no other solution to this question has been posted - and I now know a solution - I figured I would answer my own question so it may be useful for others.

Consider the Tiled map that looks like this:

and here is the corresponding .tmx file:

```
<?xml version="1.0" encoding="UTF-8"?>
<map version="1.0" orientation="orthogonal" renderorder="right-down" width="25" height="25" tilewidth="32" tileheight="32" nextobjectid="2">
 <tileset firstgid="1" name="black" tilewidth="32" tileheight="32" tilecount="1">
  <image source="filename1.png" trans="ff00ff" width="32" height="32"/>
 </tileset>
 <tileset firstgid="2" name="blue" tilewidth="32" tileheight="32" tilecount="1">
  <image source="filename2.png" trans="ff00ff" width="32" height="32"/>
 </tileset>
 <layer name="background" width="25" height="25">
  <data encoding="base64" compression="zlib">
   eJxjZGBgYBzFo3gUj2IkzATFQ92OUTyKR/EoHs4YABD8AnY=
  </data>
 </layer>
 <objectgroup name="hit block">
  <object id="1" x="384" y="318" width="63" height="64"/>
 </objectgroup>
</map>

```

The following small pygame program shows how collision detection between a red sprite and the blue box can be implemented. You move the red square using the arrow keys and when it intersects with the blue box we get a print statement to the screen. Here is the Python code:

```
import pygame
import pytmx
from pytmx.util_pygame import load_pygame

# initialize pygame
pygame.init()
clock = pygame.time.Clock()

# create game display
game_display = pygame.display.set_mode((800, 800))
pygame.display.set_caption("Collision detection with Tiled and pytmx")
red = pygame.Color(153,0,0)
pytmx_map = load_pygame("test.tmx")

class Block(pygame.sprite.Sprite):
    def __init__(self, color, width, height):
       pygame.sprite.Sprite.__init__(self)

       self.image = pygame.Surface([width, height])
       self.image.fill(color)
       self.rect = self.image.get_rect()

       self.movement_dict = {'left': (-2,0), 'right': (2,0), 'down': (0,2), 'up': (0,-2), 'rest': (0,0)}
       self.movement = 'rest'

    def update(self, event):
        if event != None:
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    quit()
                elif event.key == pygame.K_LEFT:
                    self.movement = 'left'
                elif event.key == pygame.K_RIGHT:
                    self.movement = 'right'
                elif event.key == pygame.K_DOWN:
                    self.movement = 'down'
                elif event.key == pygame.K_UP:
                    self.movement = 'up'
            elif event.type == pygame.KEYUP:
                self.movement = 'rest'

        self.rect.x += self.movement_dict[self.movement][0]
        self.rect.y += self.movement_dict[self.movement][1]

    def draw(self, display):
        display.blit(self.image, self.rect)

block = Block(red, 32, 32)
background = pygame.Surface((25*32, 25*32))
loop = True
event = None
while(loop):
    for event in pygame.event.get():
        pass

    layer_index = 0
    for layer in pytmx_map.visible_layers:
        if isinstance(layer, pytmx.TiledTileLayer):
            for x in range(0, 25):
                for y in range(0, 25):
                    image = pytmx_map.get_tile_image(x, y, layer_index)
                    if image != None:
                        background.blit(image, (32*x, 32*y))
        layer_index += 1
        if isinstance(layer, pytmx.TiledObjectGroup):
            if layer.name == "hit block":
                for obj in layer:
                    if pygame.Rect(obj.x, obj.y, obj.width, obj.height).colliderect(block.rect) == True:
                        print "YOU HIT THE RED BLOCK!!"
                        break

    block.update(event)
    game_display.blit(background, (0,0))
    block.draw(game_display)
    clock.tick(60)
    pygame.display.update()

```
> 2 votes

---
Tags: collision-detection, pygame, tiled
---


title: GL uniform variables

text:
# Question
Title: GL uniform variables
I have been studying on glsl lately, starting from very simple vertex and fragment shaders creation for Blender3d, I was quickly drawn to writing the OpenGL context in C++. I find it difficult to understand the process of drawing on screen from matrices data, especially the way I am supposed to work with uniform variables: here in this code I created an uniform mat4 in my vertex shader, which index is retrieved with `glGetUniformLocation()` in `DoShader()` and filled with data with `glUniformMatrix4fv()` in the `IdleFunc` This way I can use my projection matrix in the shader program, shouldn't it be enough for displaying a perspective ? I am obliviously missing something because my square is not appearing at all. Thanks for your help.

```
#include <GL/glew.h>
#include <GL/glu.h>
#include <GL/freeglut.h>
#include <string.h>
#include "math_3d.h"

static GLuint vbo;
GLint gWorldLocation;

class Pipeline
{
    public:
        Pipeline(){};
        void InitPersProjTrans(Matrix4f& m);
        Matrix4f* GetTrans();
        void setPerspectiveProj(float fov, float width, float height, float znear, float zfar);
    private:
        Matrix4f m_transformation;
        struct {
    float FOV;
    float Width;
    float Height;
    float zNear;
    float zFar;
        } m_persProj;
};

void Pipeline::setPerspectiveProj(float fov, float width, float height, float znear, float zfar)
{
    m_persProj.FOV = fov;
    m_persProj.Width = width;
    m_persProj.Height = height;
    m_persProj.zNear = znear;
    m_persProj.zFar = zfar;
}

void Pipeline::InitPersProjTrans(Matrix4f& m)
{
    const float ar = m_persProj.Width / m_persProj.Height;
    const float zNear = m_persProj.zNear;
    const float zFar = m_persProj.zFar;
    float zRange = zNear - zFar;
    const float tanHalfFOV = tanf(ToRadian(m_persProj.FOV / 2.0));
    m.m[0][0] = 1.0f / (tanHalfFOV * ar);
    m.m[0][1] = 0.0f;
    m.m[0][2] = 0.0f;
    m.m[0][3] = 0.0f;

    m.m[1][0] = 0.0f;
    m.m[1][1] = 1.0f / tanHalfFOV;
    m.m[1][2] = 0.0f;
    m.m[1][3] = 0.0f;

    m.m[2][0] = 0.0f;
    m.m[2][1] = 0.0f;
    m.m[2][2] = (zNear - zFar) / zRange;
    m.m[2][3] = 2.0f * zFar * zNear / zRange;

    m.m[3][0] = 0.0f;
    m.m[3][1] = 0.0f;
    m.m[3][2] = 1.0f;
    m.m[3][3] = 0.0f;
}

Matrix4f* Pipeline::GetTrans()
{
    Matrix4f PersProjTrans;

    InitPersProjTrans(PersProjTrans);
    m_transformation = PersProjTrans;
    return &m_transformation;
}

static void createShader(GLuint program, const char *shader, GLenum type){
    GLuint obj = glCreateShader(type);
    if (!obj){
        fprintf(stderr, "fail during shader creation: %d", type);
        exit(1);
    }
    const GLchar *p[1];
    p[0] = shader;
    GLint len[1];
    len[0] = strlen(shader);
    glShaderSource(obj, 1, &shader, NULL);
    glCompileShader(obj);

    GLint test;
    glGetShaderiv(obj, GL_COMPILE_STATUS, &test);
    if (!test){
        GLchar log[1024];
        glGetShaderInfoLog(obj, 1024, NULL, log);
        fprintf(stderr, "fail during shader compilation:\n%s", log);
        exit(1);
    }
    glAttachShader(program, obj);
}

#define RAW(X) "#version 330\n" #X
static const char *vertex_shader = RAW(
    layout (location = 0) in vec3 Position;

    uniform mat4 World;

    void main(void)
    {
        gl_Position = World * vec4(Position.x, Position.y, Position.z, 1.0);
    }
);

static const char *fragment_shader = RAW(
    out vec4 fragColor;
    void main(void)
    {
        fragColor = vec4(0.5, 0.15, 1.0, 1.0);
    }
);

static void DoShaders(){
    GLuint prog = glCreateProgram();
    if (!prog){
        fprintf(stderr, "fail while creating shader program\n");
        exit(1);
    }

    createShader(prog, vertex_shader, GL_VERTEX_SHADER);
    createShader(prog, fragment_shader, GL_FRAGMENT_SHADER);

    glLinkProgram(prog);

    gWorldLocation = glGetUniformLocation(prog, "World");
    GLint test = 0;
    GLchar log[1024] = { 0 };
    glGetProgramiv(prog, GL_LINK_STATUS, &test);
    if (!test){
        glGetProgramInfoLog(prog, sizeof(log), NULL, log);
        fprintf(stderr,"error link%s\n", log);
        exit(1);
    }
    glValidateProgram(prog);
    glGetProgramiv(prog, GL_VALIDATE_STATUS, &test);
    if (!test){
        glGetProgramInfoLog(prog, sizeof(log), NULL, log);
        fprintf(stderr,"error validate%s\n", log);
        exit(1);
    }
    glUseProgram(prog);
}

static void ObjectRenderInfo(){

    Vector3f verts[4];
    verts[0] = Vector3f(-1.0f, -0.1f, -1.0f);
    verts[1] = Vector3f(-1.0f, -0.1f, 1.0f);
    verts[2] = Vector3f(1.0f, -0.1f, -1.0f);
    verts[3] = Vector3f(1.0f, -0.1f, 1.0f);

    glGenBuffers(1, &vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(verts), verts, GL_STATIC_DRAW);
}

static void IdleFunc(){
    glClear(GL_COLOR_BUFFER_BIT);
    glEnableVertexAttribArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);

    Pipeline p;

    p.setPerspectiveProj(50, 1024, 768, 1, 1000);

    glUniformMatrix4fv(gWorldLocation, 1, GL_TRUE, (const GLfloat*)p.GetTrans());
    glDrawArrays(GL_QUADS, 0, 4);
    glDisableVertexAttribArray(0);
    glutSwapBuffers();
}

int main (int argc, char **argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA);
    glutInitWindowSize(1024, 768);
    glutInitWindowPosition(100, 100);

    glutCreateWindow("MyProject");

    GLenum test = glewInit();
    if (test != GLEW_OK){
        fprintf(stderr, "failed to start glew%s\n", glewGetErrorString(test));
        return 1;
    }

    glutIdleFunc(&IdleFunc);

    ObjectRenderInfo();

    DoShaders();

    glClearColor(0.0f,0.0f,0.0f,0.0f);

    glutMainLoop();
}

```

get the header file

# Answer
> 1 votes
I believe your problem can be solved by simply creating a Vertex Array Object for OpenGL to utilize before you create your Vertex Buffer Object.

You're required to use VAOs past OpenGL 3.1 core.

```
// In ObjectRenderInfo create your VAO
GLuint vertexArrayId;
glGenVertexArrays(1, &vertexArrayId);

glGenBuffers(1, &vbo);
...

```

It may help you avoid issues like this in the future, when getting started with OpenGL, frequently test to make sure your assumptions about what is functioning are correct by testing frequently. If you can't get a single white point or triangle to display on screen first, there's no point in writing all the code to roll your own version of a perspective projection (especially when you could use a simple one-liner like `glm::perspective`).

# Answer
> 1 votes
These are what I can think of and cause the object to not appear on screen:

1.) Your near variable is set to too low and it can't render

2.) Your object is at (0;0;0) and thus gets clipped in the depth test phase.

3.) Your projection matrix is in column major order and not in row major, as OpenGL requires it. Try changing every `m.m[x][y]` to `m.m[y][x]`

---
Tags: opengl, glsl, glut
---


# Question
Title: What exactly is a lobby in technical terms?
I've searched afar in google but it seems to have different technical meaning for different games and game engines.

what I know is a lobby is a space where people come together and then when certain requirements are met they start playing.

now that is just the theory, I want to know the functional design or architecture so this will be a few small questions:

1. Where is the lobby hosted? (A dedicated lobby server or client machine?)
2. Is there's a host who owns the lobby?
3. Do you need multiple free running servers to serve the lobbies? Ex. lobby A is ready,server 1 is free so assign it server1 , lobby B becomes ready search a free server for it and assign it to it.

Am I even understanding the concept of lobby correctly?

# Answer
> 4 votes
> seems to have different technical meaning for different games and game engines.

Different games implement their own way to represent lobbies, but is like "simulation race games": they are all the same concept with different vision from developers.

> 1. Where is the lobby hosted? (A dedicated lobby server or client machine?)

Prefer hosting the lobby **in server**, because:

**Latency**: if a client machine needs to send some signal to lobby, the packet need to pass to client to server to client and.. returns to server to client to get a "ok" response.

**Security**: if lobby resides on a client machine, a malicous code can be easily sent to others clients.

**Persistence**: if a client closes/drop/loose the connection, the lobby is expected to be "destroyed" by others clients (more client errors), with server you guarante that lobby "exists" to others clients. Less errors occours and need be handled if you store the lobby representation in server side.

Depending of architecture, there is no need for a dedicated lobby server, the server can be the same that is used to make login, share messages, view friends or see profile because the resources are closer, example: you can use 2 servers, one for login/messages/friends/lobbies/profile and other for "real time gaming".

from comment update: Some games have a option to "be the host". This is useful to play in LAN with friends without Internet access or reduce connection latency.

> 2: Is there's a host who owns the lobby?

Yes and no: For MMO's, RPG's is expected that a someone be the "lobby owner", but the lobby owner is referenced by the server that stores the lobby representation. This is needed for player experience: "I'm creating a lobby and I want **only** this players that are my friends playing with me". Some games will have more control of lobby owner, the lobby owner can pass permission to others players to invite, etc.

Some other games create random lobbies without a owner to group random players and dispatch more fast like first person shooters: "I just want to play, enter on a exsiting game and shoots". In this way, there is no reason to have a owner because the "existence" of game can extend the players "presence" on it.

> 3. Do you need multiple free running servers to serve the lobbies? Ex. lobby A is ready,server 1 is free so assign it server1 , lobby B becomes ready search a free server for it and assign it to it.

Depends of the server load and architecture, you can start with a one server for various operations and by the load split the micro services and each micro service multiple in multiple servers and beyond.

For client machine view, is better to communicate to server thinking that exists only one server, this reduces bandwidth usage and client code abstraction. If you have more servers, one of them communicate with others to query free lobby servers.

> Am I even understanding the concept of lobby correctly?

Yes, lobbies are lobbies, the difference on games is how you represent them based on a better player experience and client/server resource and connection management.

---
Tags: multiplayer, mmo, matchmaking
---


title: Rendering without VAO's & VBO's?

text:
# Question
Title: Rendering without VAO's & VBO's?
I am trying to port a demo I found on PositionBasedDynamics . It has a generic function which does the rendering and on their example works but they don't generate/bind any Vertex Array Object or Vertex Buffer Object even though they use Core OpenGL and shaders.

The function is this:

```
template<class PositionData>
void Visualization::drawTexturedMesh(const PositionData &pd, const IndexedFaceMesh &mesh, const unsigned int offset, const float * const color, GLuint text)
{
    // draw mesh
    const unsigned int *faces = mesh.getFaces().data();
    const unsigned int nFaces = mesh.numFaces();
    const Vector3r *vertexNormals = mesh.getVertexNormals().data();
    const Vector2r *uvs = mesh.getUVs().data();

    std::cout << nFaces << std::endl;

    glBindTexture(GL_TEXTURE_2D, text);

    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_REAL, GL_FALSE, 0, &pd.getPosition(offset)[0]);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 2, GL_REAL, GL_FALSE, 0, &uvs[0][0]);
    glEnableVertexAttribArray(2);
    glVertexAttribPointer(2, 3, GL_REAL, GL_FALSE, 0, &vertexNormals[0][0]);

    glDrawElements(GL_TRIANGLES, (GLsizei)3 * mesh.numFaces(), GL_UNSIGNED_INT, mesh.getFaces().data());

    glDisableVertexAttribArray(0);
    glDisableVertexAttribArray(1);
    glDisableVertexAttribArray(2);

    glBindTexture(GL_TEXTURE_2D, 0);
}

```

I did the same thing and it render's a white screen . I used RenderDoc to check what's going on and it show's these: https://puu.sh/rM1wB/80620ade8d.png .

How can they get it to work while i can't?

# Answer
> 1 votes
The debugger's messages are pretty clear : "clean" core OpenGL should use VAO's and VBO's, not access client-side (i.e. RAM) data. That it works on their end is likely a consequence of their graphics drivers being too lenient.

---
Tags: opengl, c++, vbo, vao
---


# Question
Title: TextAsset thinks file is ~6856 bytes when it is 120123 bytes
So I've created a text asset in Unity of a binary file which i'm attempting to read in as a byte array.

The result I'm getting is a byte array tht is almost half the size it's supposed to be.

The file is a serialized mesh file from here: http://wiki.unity3d.com/index.php?title=MeshSerializer2

What I do then is find the file unity created, move it to the assets folder and drag it into a component as a TextAsset. For smaller files it works but larger ones appear to fail to load completely.

If I load the same file separately from a C# console application using filestream it loads correctly.

# Answer
When you want Unity to load a non-text file as a text asset properly, you need to give it the file extension `.bytes`. Otherwise it is possible that Unity interprets certain bit sequences as the end of the file and truncates it. It is also required to allow you to access the `bytes` property of the text asset, which you will likely need for your use-case.
> 2 votes

---
Tags: unity, c#, assets, resource-management, filestream
---


# Question
Title: Inconsistent speed when using Vector2.Lerp
I have tried to build a point and click mechanism in unity using

`Vector2.Lerp(current_position,new_position,Time.deltatime)`

But what I observed that the game object is moving at varying speeds depending on the distance between current position and new position.If the distance is too much, the acceleration is also increased and if the distances are low, the acceleration is low. But I want to acheive it in constant velocity. where do I alter ?

# Answer
> 3 votes
Lerp (Linear intERPolation) will move the vector by a *fixed fraction* of the distance towards the target. This implies two things:

* The further the target is, the fastest the movement will be;
* The overall movement between two points is not linear, but asymptotic: for example, with a fraction of 0.5 the moving point will cover half the distance in the first frame, then half the rest in the second frame, and so on.

Lerping is not the right tool for the job if you want a constant speed. Here's some code (C++-ish, but easily portable) that achieves constant speed:

```
// Moves from `pos` to `target` by `step` units, and returns that position.
// If `target` is within `step` units, returns `target`.
vec2 moveTowards(vec2 const pos, vec2 const target, float const step) {
    vec2 const delta = target - pos;      // Gap vector
    float const len2 = dot(delta, delta); // Squared length of the gap

    if(len2 < step * step)
        // We're close enough to close the gap in one step
        return target;

    // Unit vector that points from `pos` to `target`
    vec2 const direction = delta / sqrt(len2);

    // Perform the step
    return pos + step * direction;
}

```

# Answer
> 1 votes
If you divide 1 by distance between the 2 points you get always the same velocity.

Vector2.Lerp(current\_position,new\_position,(1/Vector3.distance(current\_position, new\_position)) * Time.deltatime)

Btw: You can replace the 1 with a speed variable.

---
Tags: unity, 2d, movement, vector
---


# Question
Title: Verlet collision with impulse preservation
I came across this article, recently, that presented a technique for impulse preservation with position-based verlet integration. What was interesting was that the integration steps are seemingly done differently from typical position-based verlet schemes, as well as the ordering of the integration step and collision resolutions.

---

Specifically, the typical verlet position integrator is:

```
newPosition = 2 * position - oldPosition + acceleration * timeStepSquared
oldPosition = position
position = newPosition
DoConstraints()

```

Where the article has:

```
position += acceleration * timeStepSquared
DoConstraints()
newPosition = position * 2 - oldPosition
oldPosition = position
position = newPosition

```

Which ignoring constraints for a moment works out to be:

```
newPosition = 2*position - oldPosition + 2*acceleration*timeStepSquared
oldPosition = position + acceleration*timeStepSquared
position = newPosition

```

Which is different in a term of `acceleration * timeStepSquared`. I haven't quite convinced myself that those terms cancel out through the iteration, as the prior `acceleration * timeStepSquared` term may not be the same as the current one.

---

Could someone explain the reasoning for this, and if indeed it makes sense?

# Answer
The best place to start understanding what is actually happening in that code is to.. reverse engineer it. (see this source file http://codeflow.org/entries/2010/nov/29/verlet-collision-with-impulse-preservation/final2.js).

The main loop simply call this function

```
 var step = function(){
        var steps = 2;
        var delta = 1/steps;
        for(var i=0; i<steps; i++){
            gravity();
            accelerate(delta);
            collide(false);
            border_collide();
            inertia(delta);
            collide(true);
            border_collide_preserve_impulse();
        }
        draw();
    }

```

Without actually going into any of the *collision handling logic*, let's see what happens mathematically in that code, assuming we have a single body to simulate. This way we can check, as you pointed out, if the integrator is a position-Verlet or not, and what it actually does.

Let `x` be the position vector at the future time instance and `px` the position vector at the previous time instance. Further let's assume only 1 integration step is performed. This is what happens to `x` and `px` as a consequence of calling the `step()` function:

1. `x += a * Dt*Dt`
2. `alter(x,px)` as a result of the collision handling code (may be omitted!)
3. `xx = 2*x - px`. If we omit collisions, `xx = 2*x + 2*a*Dt^2 - px`
4. `px = x`
5. `x = xx`
6. `alter(x,px)` as a result of the collision handling code

We can indeed omit steps 2 and 6. If we do this, the integrator does the following

1. x = px
2. repeat:

a. `x = x + a*Dt^2` b. `xx = 2*x - px = px + 2*a*Dt^2` c. `px = x` d. `x = xx`

The original Verlet integrator requires estimating the state at three consecutive instances, `x[n+1], x[n]` and `x[n-1]` knowing that

* `x[n+1] = x[n] + v[n]*Dt + 1/2a[n]*Dt`
* `v[n] = (x[n+1] - x[n-1])/(2*Dt)`

hence `x[n+1] = 2*x[n] - x[n-1] + a[n]*Dt^2`, `x[n-1] = x[n]`, `x[n] = x[n+1]`.

The code inside the `step()` procedure is doing `x[n+1] = 2*(x[n] + a[n]*Dt^2) - x[n-1]`, `x[n-1] = x[n]`, `x[n] = x[n+1]`.

**Conclusion:** the integration is performed through position-Verlet, *but* there is an error since the acceleration at instance `[n]` is twice what the Physics world reports. Nevertheless, the author of that code only considered gravity, which, as far as we are concerned, is simply double the input supplied in the `accelerate` method.
> 0 votes

---
Tags: physics
---


# Question
Title: Problem understanding finite state machine
I want to use the finite state machine for the ennemies AI in my game. I implemented the pattern and it work fine for my first enemy (enemy A):

* Enemy is in IdleState by default
* When enemy see the player, it move to AttackState

But I want to implement an AI for a new enemy (enemy B) which is the same as enemy A, except that when he see the player, it move to DefenseState (instead of AttackState). The problem is that I see no other way than create a second IdleStateB class which inherit from the IdleState class (`IdleStateB: IdleState`). It bother me because I don't want to have as much Idle class as I have enemy behavior.

In fine, I want a way to control the next state which will be launched after some conditions are met. Thank you for your help!

Here is some code I use:

**FSM.cs**

```
public class FSM : MonoBehaviour {

    private Enemy enemy;
    public IEnemyState currentState;

    public FSM(Enemy enemy)
    {
        this.enemy = enemy;
    }

    public void Update()
    {
        if (currentState != null)
        {
            currentState.Execute(enemy);
        }
    }

    public void ChangeState(IEnemyState newState)
    {
        if (currentState != null)
        {
            currentState.Exit(enemy);
        }
        currentState = newState;
        currentState.Enter(enemy);
        currentState.Execute(enemy);
    }
}

```

**IEnemyState.cs**

```
public interface IEnemyState
{
    void Execute(Enemy enemy);
    void Enter(Enemy enemy);
    void Exit(Enemy enemy);
    void OnTriggerEnter(Collider2D other);

}

```

**IdleState.cs**

```
public class IdleState : IEnemyState
{

    public void Enter(Enemy enemy)
    {

    }

    public void Execute(Enemy enemy)
    {
        //Debug.Log("Idle State");
        Idle(enemy);
    }

    public void Exit(Enemy enemy)
    {

    }

    public void OnTriggerEnter(Collider2D other)
    {
        Debug.Log("OnTriggerEnter");
    }

    private void Idle(Enemy enemy)
    {
        enemy.GetComponent<EnemyMove>().Move(false);

        //  Si le joueur est dans la ligne de vue de l'ennemi, celui-ci change d'état
        if (enemy.CheckForPlayerInSight())
        {
            enemy.fsm.ChangeState(new MovingState());
        }
    }
}

```

**Enemy.cs**

```
public class Enemy : MonoBehaviour
{

    public Transform player;        // Reference to the player's transform.

    public float idlingDistance = 15f;
    public float attackingDistance = 1.5f;

    // finite state machine
    public FSM fsm;

    // Use this for initialization
    public virtual void Start()
    {
        fsm = new FSM(this);
        fsm.ChangeState(new IdleState());
    }

    // Update is called once per frame
    public virtual void Update()
    {
        fsm.Update();
    }

    void OnTriggerEnter2D(Collider2D collider)
    {
       // currentState.OnTriggerEnter(collider);
    }

    // Vérifie si le joueur est en ligne de mire ou non
    public bool CheckForPlayerInSight()
    {
        RaycastHit2D? sightTest = RaycastToPlayer(idlingDistance, Color.red);

        if (sightTest != null)
        {
            return true;
        }

        return false;
    }

    public bool CheckForPlayerInAttackRange()
    {
        RaycastHit2D? sightTest = RaycastToPlayer(attackingDistance, Color.blue);

        if (sightTest != null)
        {
            return true;
        }

        return false;
    }

    public bool IsPlayerAtLeft()
    {
        RaycastHit2D? sightTest = RaycastToPlayer(1000f, Color.green);

        if (sightTest != null)
        {
            if (sightTest.Value.point.x < transform.position.x)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        return false;
    }

    public virtual void Loot()
    {
        // Loot de l'expérience
        Instantiate(Resources.Load("Prefabs/Loots/exp_orb"), transform.position, transform.rotation);
    }

    #region utility

    private RaycastHit2D? RaycastToPlayer(float distance, Color raycastColor)
    {
        // Si le joueur n'existe plus, retourne null
        if (player == null)
        {
            return null;
        }

        //precompute our ray settings
        Vector3 start = transform.position;
        Vector3 direction = (player.GetComponent<Renderer>().bounds.center - transform.position).normalized;

        //draw the ray in the editor
        Debug.DrawRay(start, direction * distance, raycastColor);

        //do the ray test
        RaycastHit2D[] sightTests = Physics2D.RaycastAll(start, direction, distance);
        //now iterate over all results to work out what has happened
        for (int i = 0; i < sightTests.Length; i++)
        {
            RaycastHit2D sightTest = sightTests[i];
            if (sightTest.collider != null)
            {
                if (sightTest.collider.gameObject.transform == player)
                {
                    return sightTest;
                } else if (sightTest.collider.tag == Tags.SIGH_BLOCKING)
                {
                    return null;
                }
            }
        }

        return null;
    }

    #endregion
}

```

# Answer
> 3 votes
Add a method `public IEnemyState CreatePlayerReactState()` to the Enemy class. For one enemy, have it return a `DefenseState`, for the other enemy, return an `AttackState`. You can implement that by creating two subclasses of `Enemy` with different implementations of that method, or by adding a private variable to `Enemy` which says how it reacts to the player.

Then, in your method which detects the player, do `enemy.fsm.ChangeState(enemy.CreatePlayerReactState())`.

---
Tags: game-design, ai, design-patterns, state, fsm
---


# Question
Title: Google Play Services Save Game to store single long?
I want to implement a Google Leaderboard in my game. The score I will send to the leaderboard is a single long number.

Now I want to make sure that the user's progress won't get lost when reinstalling the app, buying a new mobile, etc.. So I can't store that single long in the Shared Preferences. And I also can't get the user's score back from the leaderboard, since it only supports sending scores (right?).

So I was thinking of implementing a Google SaveGame for that.

What would be the app flow for that?

Thanks in advance!

# Answer
> 0 votes
You can get the score back from the leaderboard.

Using the `loadCurrentPlayerLeaderboardScore` API call you can get a `LeaderboardScore` object back that contains the `long` representation of the score.

You could call it like this;

```
private void loadScore(String leaderboardId) {
    Games.Leaderboards.loadCurrentPlayerLeaderboardScore(getApiClient(), getString(leaderboardId), LeaderboardVariant.TIME_SPAN_ALL_TIME, LeaderboardVariant.COLLECTION_PUBLIC).setResultCallback(new ResultCallback<Leaderboards.LoadPlayerScoreResult>() {
        @Override
        public void onResult(final Leaderboards.LoadPlayerScoreResult result) {
            if (result != null && result.getStatus().getStatusCode() == GamesStatusCodes.STATUS_OK) {
                if (result.getScore() != null) {
                    // At this point you have a score
                    long score = result.getScore().getRawScore();
                }
            }
        });
}

```

---
Tags: android, savegame, google-play-services
---


# Question
Title: Implementing acceleration in topdown 2d game
So I'm making this topdown game and I'm trying to implement player control movement so that it feels more natural. Right now I have an update method like this:

```
void update(float delta) {
    velocity = sf::Vector2f();

    if right:
        velocity.x = 1;
    if left:
        velocity.x = -1;
    if up:
        velocity.y = -1;
    if down:
        velocity.y = 1;

    velocity *= sf::Vector2f(delta, delta);
    position += velocity;
}

```

I want to implement acceleration, so that the player doesn't reach top speed as soon as they hit a key, as well as de-acceleration so that they slow down (but quicker than they accelerate) as they release the key.

So I remove the velocity being reset to zero, and if they go right I increment the x component of the velocity by the `speed` and then if they still hold right I increment the `speed` by `acceleration`. Then when they release the key I slow down this acceleration, but the way I've done it you move right it works, then you move left and the player goes right again but really fast.

Note that I'm only doing left + right before I move on to up and down since its the same principle, so the code is unfinished:

```
void Player::update(double delta) {
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) {
        vel.x += speed;
        speed += accel;
        if (speed > max_accel) {
            speed = max_accel;
        }
    }
    else if (vel.x > 0) {
        speed -= accel;
        if (vel.x <= 0) {
            vel.x = 0;
            speed = accel;
        }
    }

    if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) {
        vel.x -= speed;
        speed -= accel;
        if (speed < -max_accel) {
            speed = -max_accel;
        }
    }
    else if (vel.x < 0) {
        vel.x += speed;
        if (vel.x >= 0) {
            vel.x = 0;
            speed = accel;
        }
    }

    pos.x += vel.x * delta;
    pos.y += vel.y * delta;
}

```

What am I doing wrong here? I can't seem to get the logic right for when you release a key or not. I figured that if they aren't holding A, but their velocity is in the direction of A then we apply the slowdown but I can't seem to figure out how to handle when we actually reach the velocity of zero.

# Answer
> 0 votes
In this bit:

```
if ( sf::keyboatd::isKeyPressed(sf::keyboard::A))

```

You're confusing your minuses and additions to the velocity. you should += the acceleration and set to a positive max\_accel.

---
Tags: c++, 2d, physics
---


title: SDL2 not setting OpenGL version?

text:
# Question
Title: SDL2 not setting OpenGL version?
I want to use SDL2 (2.0.4) with C to create an OpenGL 3.3 (core) context. But it seems to default to whatever compatibility profile my computer supports. Works fine with LWJGL2 and Java.

Here is my C code with SDL2.

```
#include <SDL2/SDL.h>
#include <SDL2/SDL_events.h>
#include <epoxy/gl.h>
#include <epoxy/glx.h>

void main(){
    //set opengl attributes, supposed to happen before window creation
    SDL_GL_SetAttribute (SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); //OpenGL core profile
    SDL_GL_SetAttribute (SDL_GL_CONTEXT_MAJOR_VERSION, 3); //OpenGL 3+
    SDL_GL_SetAttribute (SDL_GL_CONTEXT_MINOR_VERSION, 3); //OpenGL 3.3

    if (SDL_Init (SDL_INIT_EVENTS | SDL_INIT_VIDEO) < 0){
        printf ("sdl init error: %s", SDL_GetError());
        return;
    }
    SDL_Window* window = SDL_CreateWindow (
        "SDL2 Problem",
        SDL_WINDOWPOS_UNDEFINED,
        SDL_WINDOWPOS_UNDEFINED,
        0,
        0,
        SDL_WINDOW_OPENGL | SDL_WINDOW_FULLSCREEN_DESKTOP
    );
    if (window == NULL){
        printf ("could not create window: %s\n", SDL_GetError());
        return;
    }

    //initialize OpenGL stuff
    SDL_GLContext openglContext = SDL_GL_CreateContext (window);
    printf ("glGetString (GL_VERSION) returns %s\n", glGetString (GL_VERSION));
    SDL_GL_DeleteContext (openglContext);
    SDL_DestroyWindow (window);
    SDL_Quit();
}

```

The output is

```
glGetString (GL_VERSION) returns 3.0 Mesa 11.2.0

```

So why is it not giving me an OpenGL 3.3 core profile? Here is my Java code with LWJGL2 (2.9.3)

```
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.ContextAttribs;
import org.lwjgl.opengl.PixelFormat;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL11;

public class withLWJGL2{
    public static void main (String [] args){
        try{
            PixelFormat pixelFormat = new PixelFormat();
            ContextAttribs contextAttribs = new ContextAttribs (3, 3);//opengl 3.3
            Display.create (pixelFormat, contextAttribs);
        }
        catch (LWJGLException e){
            e.printStackTrace();
            System.exit(0);
        }

        // check version string
        System.out.println ("glGetString (GL_VERSION) returns " + GL11.glGetString (GL11.GL_VERSION));

        Display.destroy();
    }
}

```

The output is

```
glGetString (GL_VERSION) returns 3.3 (Core Profile) Mesa 11.2.0

```

Works just fine! The output of

```
glxinfo | grep version

```

is

```
server glx version string: 1.4
client glx version string: 1.4
GLX version: 1.4
    Max core profile version: 3.3
    Max compat profile version: 3.0
    Max GLES1 profile version: 1.1
    Max GLES[23] profile version: 3.0
OpenGL core profile version string: 3.3 (Core Profile) Mesa 11.2.0
OpenGL core profile shading language version string: 3.30
OpenGL version string: 3.0 Mesa 11.2.0
OpenGL shading language version string: 1.30
OpenGL ES profile version string: OpenGL ES 3.0 Mesa 11.2.0
OpenGL ES profile shading language version string: OpenGL ES GLSL ES 3.00

```

My computer is running GalliumOS 2.0, which is based on Ubuntu. Just to make sure it wasn't a problem with that computer I tried it on my other computer, running Ubuntu 16.04 and using NVIDIA. The ouput of the C code with SDL2 is

```
glGetString (GL_VERSION) returns 4.5.0 NVIDIA 361.42

```

So again it is not setting the version of the OpenGL context to OpenGL 3.3. The output of the Java code with LWJGL2 on this computer is

```
glGetString (GL_VERSION) returns 3.3.0 NVIDIA 361.42

```

Works just fine! Output of

```
glxinfo | grep version

```

is

```
server glx version string: 1.4
client glx version string: 1.4
GLX version: 1.4
OpenGL core profile version string: 4.5.0 NVIDIA 361.42
OpenGL core profile shading language version string: 4.50 NVIDIA
OpenGL version string: 4.5.0 NVIDIA 361.42
OpenGL shading language version string: 4.50 NVIDIA
OpenGL ES profile version string: OpenGL ES 3.2 NVIDIA 361.42
OpenGL ES profile shading language version string: OpenGL ES GLSL ES 3.20
    GL_EXT_shader_implicit_conversions, GL_EXT_shader_integer_mix,

```

So in both cases the LWJGL2 works but the SDL2 seems to default to the highest compatibility profile that the drivers support. How can I get a 3.3 (core) profile with SDL2?

# Answer
> 4 votes
Put your `SDL_GL_SetAttribute()` calls after `SDL_Init()`.

---
Tags: opengl, sdl2
---


# Question
Title: What's the largest "relative" level I can make using float?
Just like it was demonstrated with games like dungeon siege and KSP, a large enough level will start to have glitches because of how floating point works. You can't add 1e-20 to 1e20 without losing accuracy.

If I choose to limit the size of my level, how do I calculate the minimum speed my object can move at until it begins to be choppy ?

# Answer
> 35 votes
A 32-bit float has a 23 bit mantissa.

That means each number is represented as 1.xxx xxx xxx xxx xxx xxx xxx xx times some power of 2, where each x is a binary digit, either 0 or 1. (With the exception of extremely small denormalized numbers less than \\$2^{-126}\\$ \- they start with 0. instead of 1., but I'll ignore them for what follows)

So in the range from \\$2^i\\$ and \\$2^{(i+1)}\\$, you can represent any number within an accuracy of \\$\pm 2^{(i - 24)}\\$

As an example, for \\$i = 0\\$, the smallest number in this range is \\$(2^0) \cdot 1 = 1\\$. The next smallest number is \\$(2^0) \cdot (1 + 2^{-23})\\$. If you wanted to represent \\$1 + 2^{-24}\\$, you'll have to round up or down, for an error of \\$2^{-24}\\$ either way.

```
In this range:                You get accuracy within:
-----------------------------------------------
         0.25   -     0.5    2^-26 = 1.490 116 119 384 77 E-08
         0.5    -     1      2^-25 = 2.980 232 238 769 53 E-08
         1     -      2      2^-24 = 5.960 464 477 539 06 E-08
         2     -      4      2^-23 = 1.192 092 895 507 81 E-07
         4     -      8      2^-22 = 2.384 185 791 015 62 E-07
         8     -     16      2^-21 = 4.768 371 582 031 25 E-07
        16     -     32      2^-20 = 9.536 743 164 062 5  E-07
        32     -     64      2^-19 = 1.907 348 632 812 5  E-06
        64     -    128      2^-18 = 0.000 003 814 697 265 625
       128    -     256      2^-17 = 0.000 007 629 394 531 25
       256    -     512      2^-16 = 0.000 015 258 789 062 5
       512    -   1 024      2^-15 = 0.000 030 517 578 125
     1 024    -   2 048      2^-14 = 0.000 061 035 156 25
     2 048    -   4 096      2^-13 = 0.000 122 070 312 5
     4 096    -   8 192      2^-12 = 0.000 244 140 625
     8 192   -   16 384      2^-11 = 0.000 488 281 25
    16 384   -   32 768      2^-10 = 0.000 976 562 5
    32 768   -   65 536      2^-9  = 0.001 953 125
    65 536   -  131 072      2^-8  = 0.003 906 25
   131 072   -  262 144      2^-7  = 0.007 812 5
   262 144   -  524 288      2^-6  = 0.015 625
   524 288 -  1 048 576      2^-5  = 0.031 25
 1 048 576 -  2 097 152      2^-4  = 0.062 5
 2 097 152 -  4 194 304      2^-3  = 0.125
 4 194 304 -  8 388 608      2^-2  = 0.25
 8 388 608 - 16 777 216      2^-1  = 0.5
16 777 216 - 33 554 432      2^0   = 1

```

So if your units are metres, you'll lose millimetre precision around the 16 384 - 32 768 range (about 16-33 km from the origin).

It's commonly believed you can work around this by using a different base unit, but that's not really true, since it's *relative* precision that matters.

* If we use centimetres as our unit, we lose millimetre precision at the 1 048 576-2 097 152 band (10-21 km from the origin)
* If we use hectametres as our unit, we lose millimetre precision at the 128-256 band (13-26 km from the origin)

...so changing the unit over four orders of magnitude still ends up with a loss of millimetre precision somewhere in the range of tens of kilometers. All we're shifting is where exactly in that band it hits (due to the mismatch between base-10 and base-2 numbering) not drastically extending our playable area.

Exactly how much inaccuracy your game can tolerate will depend on details of your gameplay, physics simulation, entity size/draw distances, rendering resolution, etc. so it's tricky to set an exact cutoff. It may be your rendering looks fine 50 km from the origin, but your bullets are teleporting through walls, or a sensitive gameplay script goes haywire. Or you may find the game plays fine, but everything has a barely-perceptible vibration from inaccuracies in the camera transform.

If you know the level of accuracy you need (say, a span of 0.01 units maps to about 1 px at your typical viewing/interaction distance, and any smaller offset is invisible), you can use the table above to find where you lose that accuracy, and step back a few orders of magnitude for safety in case of lossy operations.

But if you're thinking about huge distances at all, it may be better to sidestep all of this by **recentering your world** as the player moves around. You choose a conservatively small square or cube-shaped region around the origin. Whenever the player moves outside this region, translate them, and everything in the world, back by half the width of this region, keeping the player inside. Since everything moves together, your player won't see a change. Inaccuracies can still happen in distant parts of the world, but they're generally much less noticeable there than happening right under your feet, and you're guaranteed to always have high precision available near the player.

# Answer
> 3 votes
It's hard to answer as it depends on the scale of your physics: What is the acceptable minimum movement speed that needs to **NOT** be rounded off to zero?

If you need a large world and consistent physics it's better to use a fixed points class.

For example, shooting a cannon ball from anywhere in the world will give you the same result and a 64bit fixed point (32.32) gives you a huge amount of precision and more than anything perceivable in most games. If your unit is 1 meter you're still at 232 picometers precision 2147483km away from the origin.

You can still do the local physics in floating points within the local cell to save on programming work and use an off-the-shelf physics engine. It will still be reasonably consistent for all practical purposes.

As a bonus broad phase and AABB tend to be faster in fixed point due to FPU latency. It's also faster to convert a fixed point to an octree (or quadtree) index as you can do simple bit masking.

Those operations do not benefit as much from SIMD instructions and pipelining which would normally hide FPU latency.

You can convert the positions to floating point AFTER subtracting the camera's position in fixed point to render everything, avoiding floating point issues in a large world and still using a regular renderer using floating points.

# Answer
> -4 votes
You can avoid it altogether by multiplication.
Instead of working with floats, just multiply them by 10^(x), store them, and when needed multiply again by 10^(-x).
From that it depends on what type of int you want to use.

---
Tags: c++, floating-point
---


# Question
Title: Building an XNA Game Engine: How to load sprites outside of LoadContent()?
I'd like to build an engine in XNA, primarily for a 2D RPG. At first, I began abstracting out some classes and built a Sprite class which wrapped a `Vector2` and a `Texture2D`, and tried loading in content from the Sprite class' constructor. However, this didn't work. Now, it appears that I have to load *all* of the sprites within the Game class' LoadContent method. Is there anyway around this? I'd like to separate the actual Game Content from the inner workings of the engine, if possible.

# Answer
> 8 votes
The LoadContent method is simply called after the graphics device has been initialized. You can load content at any point after that, not just in the LoadContent method.

If you were, for instance, to instantiate your sprite class within the LoadContent method, or within the Draw or Update calls, you wouldn't have any problem.

Now, as far as design goes, having the sprite load the content it needs typically isn't a good idea. To keep with the single responsibility principle, and dependency inversion principle, you might want to accept a Texture2D as a parameter to the Sprite constructor. That way you'll be able to have the same "BadGuy" sprite, but be able to pass it two different textures (for say, a red bad guy and a green bad guy).

# Answer
> 3 votes
You don't need to load all content within the `LoadContent` method, you could load it in a method called by that, or at pretty much any time after that (once the `GraphicsDevice` is set up).

A very simple example might be having a list or similar structure in your game engine, then before loading the user of the engine would add the locations and types of content to load. Then you'd call your engine's `LoadContent` method from your game's `LoadContent` method. The engine would then loop through the added resources and load them for use in the engine.

This is of course a simple example, you'd probably need some kind of resource manager to manage loading/unloading/making resources available to what needs them etc.

# Answer
> 0 votes
Back in the day when I was using XNA I need to load textures at runtime.

I just spent 1hr digging around trying to find this, it uses a stream to read the file from disk and then loads the stream into a texture2d and you can then pass that of to your spritebatch or do what u need with it.

```
 Dim Texture As Texture2D
 Using FS As New FileStream(imagepath, FileMode.Open, FileAccess.Read)
 FS.Seek(0, SeekOrigin.Begin)
 Texture = Texture2D.FromStream(GraphicsDevice, FS)
 FS.Close()
 End Using

```

Hope that helps or is close to what u need.

# Answer
> -1 votes
what if you have this constructor? (i mean, is this possible?)

```
Sprite(Microsoft.Xna.Framework.Content.ContentManager content){
    Texture2D something = content.Load<Texture2D>("someImages");
}

```

---
Tags: c#, xna, architecture
---


# Question
Title: arrays last element that has color never gets accessed
I have assigned this C# script to a spot light. But the green color which is at 2nd position in array never gets accessed and spot light never gets green light. I tried debugging this code but no idea what's wrong

```
public class CSharping : MonoBehaviour {

    public Light lt;

    Color[] allColor = { Color.red, Color.blue, Color.green};

    // Use this for initialization
    void Start () {
        lt  = GetComponent<Light>();
    }

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

        if(Input.GetButtonDown("Fire1"))
        {
            int colorVariable = Random.Range(0,2);
            lt.color = allColor[colorVariable];
        }

    }
}

```

# Answer
> 1 votes
You're looking at the another overload the Range method in the docs for float variables but using integers.

From Unity docs:

> public static float Range(float min, float max);
>
> Returns a random float number between and min \[inclusive\] and max \[inclusive\] (Read Only). Note that max is inclusive, so using Random.Range( 0.0f, 1.0f ) could return 1.0 as a value.
>
> public static int Range(int min, int max);
>
> Returns a random integer number between min \[inclusive\] and max \[exclusive\] (Read Only). Note that max is exclusive, so using Random.Range( 0, 10 ) will return values between 0 and 9.

# Answer
> 5 votes
**You are using `Random.Range(int, int)`, not `Random.Range(float, float)`. In the example you give, the max value is *not* inclusive**.

Let's take a look at the Unity API:

> ## Random.Range
>
> `public static float Range(float min, float max);`
> Returns a random float number between and\[*sic*\] `min` \[inclusive\] and `max` \[inclusive\] (Read Only). Note that max is inclusive, so using `Random.Range( 0.0f, 1.0f )` could return 1.0 as a value.
> **...**
> `public static int Range(int min, int max);` Returns a random integer number between `min` \[inclusive\] and `max` \[exclusive\] (Read Only). Note that max is exclusive, so using `Random.Range( 0, 10 )` will return values between 0 and 9. If max equals min, min will be returned.
> **\- Unity API: Random.Range**

---

Given that your returning an `int`, the method `int Range(int min, int max)` will be called, where `max` is *exclusive*. To return the values `0`, `1` or `2` you should use `Random.Range(0, 3)`.

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


title: How do I create a closed beta on Steam?

text:
# Question
Title: How do I create a closed beta on Steam?
As per suggestion I'm splitting How do I create a closed beta on the App Store? up.

Can I upload the game I'm developing to Steam as a closed beta, so I could generate a couple of keys/tokens for my testers? I'm hoping to only publish the game for the public after I'm happy with the game as it's offered on Steam, as a complete user experience which includes the installation process.

If this is not the usual workflow, how should I do it?

# Answer
> 3 votes
On Steam you do it by creating a branch in SteamWorks (under SteamPipe) which you set a password for. You then upload your build and push it live in that branch (again it's under SteamPipe). Anybody who has access to that branch (you've generated a key for + has the password) can opt in to the beta and will be given that build.

---
Tags: steam, playtesting, beta
---


# Question
Title: Having trouble with constructors and the deque class
I've recently been trying to make a better version of my previous remake of the classic snake game by implementing data encapsulation and abstraction. I also decided to replace my horrible choice of a linked list for holding the snake's tail co-ordinates with the more sensible choice of a deque. Since I am a beginner and I have honestly no clue what is going on *(I'd be worried if I did know what I was doing)*, I would appreciate some assistance with helping me understand what is wrong with my usage of the deque and how I can fix it.

From what I can gather I believe it has something to do with improper usage of constructors, yet I still have not fully grasped the concept of constructors to be able to properly debug it.

# SnakePart.h

```
#ifndef SNAKEPART_H_
#define SNAKEPART_H_

#include <deque>

class SnakePart {
public:
    void advance(int x, int y, bool loose_tail = true);
};

extern std::deque<SnakePart> parts;

#endif /* SNAKEPART_H_ */

```

# SnakePart.cpp

```
#include "SnakePart.h"

void SnakePart::advance(int x, int y, bool loose_tail) {
        std::deque<SnakePart> parts;
        parts.emplace_front(x, y);

        if(loose_tail)
            parts.pop_back();
}

```

# Answer
It looks like you're not referencing the right `parts` instance. When you do `std::deque<SnakePart> parts;` in `SnakePart::advance` you're creating a new instance of the `deque`. The **export**ed `deque` you declare in the header file isn't used at all.

You might want to consider the `advance` being part of the `Snake` instead of the `SnakePart`;

**Snake.h**

```
#ifndef SNAKE_H_
#define SNAKE_H_

#include<deque>
#include"SnakePart.h"

class Snake
{
private:
    std::deque<SnakePart> parts;
public:
    Snake(int startX, int startY);
    void advance(int x, int y, bool loose_tail = true);
};

#endif SNAKE_H_

```

**Snake.cpp**

```
#include "Snake.h"

Snake::Snake(int startX, int startY) {
    advance(startX, startY, false);
}

void Snake::advance(int x, int y, bool loose_tail) {
    parts.push_front(SnakePart(x, y));
    if (loose_tail)
        parts.pop_back();
}

```

**SnakePart.h**

```
#ifndef SNAKEPART_H_
#define SNAKEPART_H_

class SnakePart
{
public:
    const int x;
    const int y;
    SnakePart(int x, int y);
};

#endif SNAKEPART_H_

```

**SnakePart.cpp**

```
#include "SnakePart.h"

SnakePart::SnakePart(int px, int py)
    : x(px), y(py) {
}

```

That way the `SnakePart` represents only a part of the snake, and there's no actions on it. The `Snake` on the other hand is a list of parts, and it can grow by calling `advance`.
> 0 votes

---
Tags: data-structure, snake
---


# Question
Title: Change the image gallery using joystick with Unity
I want to change the image using joystick controls.I have two two button(Go and Previous).How can I change the image using joystick

# Answer
> 1 votes
You can change configure your game to receive input from joystick in the InputManager in Unity editor. Expand Mousex and MouseY (for instance) and configure it to use Joystick keys. You may map each axis to two buttons on a joystick, mouse, or keyboard keys. The name of the string can be used to get input value from this axis from a script like this:

```
value1 = Input.GetAxis("MouseX"); //this can be renamed "Go"
value2 = Input.GetAxis("MouseY"); //this can be renamed "Previous"

```

An axis has a value between -1 and 1.The neutral case is 0.

Once you have the input, you can cycle between two (or as many you want) images on an image component.

```
Image img;
Texture2D[] mySprites; //an array of sprites
if(value1>0)
   i++;
else if(value2>0)
   i--;
img.sprite=mySprites[i];

```

I hope this will do :)

# Answer
> 0 votes
Within your MonoBehaviour:

```

float delay = 1f;
bool enableInput = true;

void Update() {
    if(Input.GetAxis("Horizontal")  0) {
        ShowNextPicture();
        enableInput = false;
        Invoke("EnableInput", delay);
    }
}

void EnableInput() {
    enableInput = true;
}

```

For some reason the code is not shown properly.

---

If you provide more detail for your questions you will get better answers. In case of Unity3D it may is helpfull which version you use and in what language (C#, Javascript) you are coding.

Showing some of your existing code is always useful.

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


# Question
Title: Separation of game logic - extending game state to include location information?
I'm currently making a conversion of a board game I have - I don't intend to release it, it's merely to sharpen up skills. I'm currently refactoring it to completely separate game logic from everything such as rendering, getting user input, etc. The game logic is now in a library independent of the project that is actually run.

However, I've come across the problem that, if I don't store piece positions in the game state (as the game logic does not need to know about these), I'm struggling to think of how to store this information in the project that deals with rendering/user input stuff, so that it may render pieces.

## Game State

The game state looks like this within the game logic - each district used to have a Vector2 indicating where the trouble marker would be displayed, and each piece would also have a Vector2 indicating their position on the board. They do not at the moment, as I wish to only have such things in the *game* project, as opposed to the *logic* project

```
Environment
    City
        District
        District
            Trouble
            Piece(s)

```

I have thought of creating a clone of this structure but adding position information, or of trying to use inheritance. But both of these methods seem extremely painful to do in the situation, and I'd really prefer to keep the game logic completely unknowing of things like this.

How would I go about doing this cleanly? Is it possible, or do I need to do a complete rethink of things?

# Answer
It depends on if the game logic *needs* to know what the physical position of a gamepiece is. If that is not the case you can separate the render logic entirely from the gamelogic.

Suppose the game is Monopoly. You need to consider how to represent the board based on the information. For it to render it only needs to know the type (station, street, chance), if there are gamepieces on the square, any houses or hotels. This is all gamedata.

There is no need to include the exact positions of all pieces as they are relative to their parent container. So calculate the number of houses on that tile and draw them relative to that tile. Alternatively a tile with houses in them could also be represented as a circle with dots on the edges where each dot represents a house. For this you also do not need to know any Vector2 information in the game logic, as the circles are based on the number of houses and relative to the position of the tile (which in turn is relative to the previous tile and so on). This way, the board could be represented as a circle or a long winding strip or exactly as the 'real' board. As the presentation is just a matter of how you plan to represent pieces on the gameboard.

It becomes a different story if your game is like a tabletop wargame, where real positions become key (for example, distances within a district influence the odds a gamepiece can 'hit' an other gamepiece. In that event, you will need an exact representation of the gameboard in your logic as well.
> 0 votes

---
Tags: c#, architecture, mono
---


title: Random generated text not working

text:
# Question
Title: Random generated text not working
I'm trying to make a game which requires a random generation of sentence upon pressing spacebar. I've never done anything like this and wanted to give it a shot with whatever knowledge I had.

Whenever spacebar is pressed, "Be something in something." appears. I want the somethings to be randomized.

This what I wrote in the Create event -

```
global.profession = irandom(2);
global.situation = irandom(2);

```

And this in the Space event -

```
draw_set_colour($777777);
draw_set_font(fnt_rpl);

if global.profession = 0{
  global.profession = "a nurse"
}

if global.profession = 1{
  global.profession = "a driver"
}

if global.profession = 2{
  global.profession = "a police officer"
}

if global.situation = 0{
  global.situation = "in a hospital."
}

if global.situation = 1{
  global.situation = "in a car."
}

if global.situation = 2{
  global.situation = "in a police station."
}

draw_text_ext_transformed(200, 500, "Be" + global.profession + global.situation, 20, 800, 1, 1, image_angle);

```

Room is set to be `1920x1080` and I've added the object in the room. I'm getting no result, not even an error, when I press space.

# Answer
Thanks to a comment by @Dmi7ry, I was able to figure out my mistake. I was wrong at not putting the draw\_text inside a Draw event. I changed the press Space event to Draw event while making changes as per advised by @Dmi7ry. Then I made another press Space event and copy pasted the code that was in the Create event. Thanks to @Dmi7ry again.
> 1 votes

---
Tags: game-maker
---


title: Copy Protection / Incentive to buy

text:
# Question
Title: Copy Protection / Incentive to buy
I'm the lead of a small independant team working on a game slated for release next year. Most of the design is collaborative and we are currently investigating copy protection, on which neither of us has previous expertise.

* Our artist does not believes in any protection. While the easiest thing to do, I'm not really happy about it since it means that it will be readily available in pirate form (which will get us potential customers according to artist).
* Our scripter is the complete opposite and wants us to contract a commercial DRM. This is a major no-go for me, on two aspects : it will be a hassle to our clients (as a player, I personally experienced a false positive with a game using DRM) and it will decrease performance.
* My opinion is more nuanced. I've developed a serial key generation algortihm, with verification at the start of the game (only once, if a valid key is entered, it is stored then verified at launch, asked again in case of invalid or banned key). Key verification is only effectued locally (no "phoning home"), as I want to keep client hassle minimal.

As our game is mainly geared towards cooperative LAN play, I proposed that a same key would be able to used several times. Both argued that it will be the same as having no protection. I think it offers the best ratio (incentive to buy)/(customer hassle)

I know that no perfect solution exists and any protection can easily be circumvented. I want to know if any of the community has experience in these matters and share with me his experience or advice : is the described shared serial key **economically** viable (at least, more than no protection at all) ?

# Answer
Serial keys with purely client-sided validation have really fallen out of favor in the past years. The reason is that without online verification the pirates only need a single valid key which they can place conveniently in the file description for copy&pasting.

That makes the life of the non-paying players just as difficult as for your paying players to unlock their copy. If you want to offer an incentive to buy, you need to make sure that your paying players need to jump through *less* hoops than the non-paying ones.

Any form of DRM is no solution either. Any software which runs on the users computer is under the users control. It's not a question *if* the DRM will get cracked, it's a question of *when*. All you can hope for is that it will take at least a few days between your official release and the unofficial release on piratebay. The cost is usually only justifiable for projects with AAA budgets. It is also only useful when you have an AAA marketing strategy which uses aggressive (and expensive) advertising focused around the launch date to obtain most sales in the first few days. Independent games usually rely more on viral campaigns which result in purchases distributed over a far longer timespan.

**The best copy protection is to offer your paying players some benefit which the pirates can not.**

One killer-feature is any form of online interaction which requires a personalized account tied to the purchase. When you have a multiplayer mode, consider hosting the game server and don't let anyone connect without a paid account. When that's too expensive, you could host at least a server list / matchmaking service, so the pirates will have a hard time finding someone to play against. When your game is single-player, you could host public scoreboards. Even requiring a purchase to access the official forum can be an incentive to buy.

But not every game is suitable for shoehorning in some form of online interaction just to justify online registration. When it isn't essential to the gameplay, the pirates won't care about it anyway. And when you require a login just to play single-player, they will just build a crack to dummy it out.

Another killer-feature are frequent automatic updates. When you release regular updates after release, your paying players get them automatically through your distribution platform. They get them the moment they are released without them having to do anything. But your non-paying players will have to wait until the pirates have released the update and then again go through the same hassle of finding a working download. After going through this a few times in a row, the non-paying players might consider to become paying players just so they get the updates easily and on time.

But in the end you will have to accept that there will always be freeloaders who will play your game without paying. If you *could* make it impossible to pirate your game, then most of them would not buy it anyway. They would simply not play it at all.
> 8 votes

---
Tags: commercial
---


# Question
Title: How do I create a closed beta on the App Store?
After months of hard work, much to my surprise I'm about to unlock the "feature complete" and "production ready" achievements with the game I'm working on, so it's time to ask my colleagues and Facebook acquaintances if they'd like to help me by playtesting the game.

This is going to be my first game, and I'm wondering if I can somehow upload it as a "closed beta" to the App Store and generate a couple of keys/tokens, so I could hand these to my playtesters? This way they wouldn't have to install unsigned developer versions, so they'd also be testing the real installation process, and of course paying customers wouldn't even be seeing the product until I make it public.

Is this how a closed-beta testing goes at all?

# Answer
> 1 votes
For the (iOS) App Store, you can leverage Apple's TestFlight beta testing program.

This involves preparing a build and uploading it to your account via iTunes Connect (so you'll need a record created for the app). You can distribute the beta of the app to private, internal testers or external testers, although the latter does involve going through a miniature app-review style process.

Internal testers must be members of your account's organization and you're limited to about 30 or so. External testers don't need to be, they just need to be invited via an e-mail address, and you have a much higher limit of a few thousand.

TestFlight is available for iOS, tvOS, and watchOS (as of this writing).

---
Tags: appstore, playtesting, beta
---


# Question
Title: How to give player the ability to toggle visibility of the wall?
When keyboard 'H' is pressed i want the platformer (wall, roof, floor) become invisible when its visible and become visible when its invisible. Like giving the player ability to control visibility of certain wall so he can pass through it.

This is what i do so far but the wall become blink when i press 'H'. Sometimes the wall become invisible but sometimes it just blink.

```
public class HideWall : MonoBehaviour {

    public SpriteRenderer wall;
    public Collider2D wallCollider;
    public Effector2D wallEffector;
    private bool visible;

    // Use this for initialization
    void Start () {
        wall = GetComponent<SpriteRenderer> ();
        wallCollider = GetComponent<Collider2D> ();
        wallEffector = GetComponent<Effector2D> ();
        visible = true;
    }

    // Update is called once per frame
    void Update () {
        if (Input.GetKey(KeyCode.H)) {
            wall.enabled = !wall.enabled;
            wallCollider.enabled = !wallCollider.enabled;
            wallEffector.enabled = !wallEffector.enabled;
        }
    }
}

```

# Answer
> 7 votes
Using GetKeyDown() will trigger it only once when the key is actually pressed, removing any blinking that you see. `GetKey()` will return true for every frame the key is held down which isn't what you want.

Using the code from @Droppy's answer, you just need to simply store the state of hidden walls on the class instance itself (`wantToHide`).

If you're still stuck, here's the code to do it:

```
bool wantToHide = false;

void Update () {
    if(Input.GetKeyDown(KeyCode.H)) {
        wantToHide = !wantToHide;
        wall.enabled = !wantToHide;
        wallCollider.enabled = !wantToHide;
        wallEffector.enabled = !wantToHide;
    }
}

```

# Answer
> 3 votes
Only make the change if it's not already in the state you want:

```
void Update () {
    bool wantToHide = Input.GetKeyDown(KeyCode.H);
    bool alreadyHidden = !wall.enabled;
    if (wantToHide != alreadyHidden) {
        wall.enabled = !wantToHide;
        wallCollider.enabled = !wantToHide;
        wallEffector.enabled = !wantToHide;
    }
}

```

Also processing input within non-player-oriented script is kinda crappy; so create a player controller object and attach it to scene and get that to call the above script when the state changes.

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


# Question
Title: Correct jumping cycle logic in Unity with 3 jump animations
I have 3 jump animations; jumping up, jumping down, and the loop in between. I want to play them in an order, using logic.

When the player presses space, I should play the "jumping up" animation, followed by the "jump loop" while player is in air, and the "jumping down" animation just before touching the ground. If the player falls from a height, I should play the "jump loop" animation while in air, followed by the "jumping down" animation just before touching the ground.

This is what I have so far, to provide the animation:

```
void Update ()
{
    if (!animator)
    {
        return;
    }

    float vSpeed = Input.GetAxis ("Vertical");
    animator.SetFloat ("VSpeed", vSpeed);

    if (Input.GetButtonDown ("Jump"))
    {
        animator.SetBool ("Jumping", true);
        Invoke ("StopJumping", 0.1f);
    }

    if (!charController.isGrounded)
    {
        animator.SetBool ("Grounded", false);
        RaycastHit hit;
        Ray downRay = new Ray (transform.position, Vector3.down);

        if (Physics.Raycast (downRay, out hit))
        {
            animator.SetFloat ("Distfromground", hit.distance);
        }
    }
}

void StopJumping()
{
    animator.SetBool ("Jumping", false);
}

```

Am I doing anything wrong, or is there a better way to do this? As it is, it is not giving me the desired effects.

# Answer
Based off the information given, here is my answer(which makes plenty of assumptions).

```
const int landingDistance = 0.2f;
void Update ()
{
    if (!animator)
    {
        return;
    }

    animator.SetFloat ("VSpeed", Input.GetAxis ("Vertical"));

    if (Input.GetButtonDown ("Jump"))
    {
        //transition into `Jump` animation state
        animator.SetTrigger("Jump");
    }

    if (!charController.isGrounded)
    {
        //transition from `Jump` to `!Grounded` animation state
        animator.SetBool ("Grounded", false);

        if (Physics.Raycast (transform.position, Vector3.down, landingDistance))
        {
            //transition from `!Grounded` to `Landing` animation state
            animator.SetTrigger("Landing");
        }
    }
}

```

Here is what I did to simplify things:

* You should be using a Trigger instead of manually setting booleans.
* Removed un-needed Raycast information.

Here is what I did to achieve the goal:

* Define three animation states: Jump -\> !Grounded -\> Landing.

In your animation tree, it will be as simply as a linear progression through the states:

`Idle` -(`Jump Trigger`)\> `Jump` -(`Grounded is false`)\> `!Grounded` -(`Landing Trigger`)\> `Landing`

In the transition between `Jump` and `!Grounded`, you can tweak the transition to provide a nice effect.
> 0 votes

---
Tags: unity, jumping
---


# Question
Title: The meaning of colours in other cultures
According to http://www.color-wheel-pro.com/color-meaning.html and many other western websites certain colours have meanings.

To summarise the meaning of colours in the context of a typical RTS game:

* red = danger or enemy
* gold = wealth or high quality
* yellow = energy
* green = healing
* aqua = protection
* blue = power
* pink = romance
* white/grey = neutral territory
* black = mystery

(There are many more meanings that I deliberately left out as it is not applicable to games)

However this information was collected from western websites.

If I have to design a game that needs to be played internationally, would it make sense to go with the above "colour rules" or could I expect that other cultures like the Eastern or African cultures could have a significant different association with colours than the Western cultures?

If so, would it make sense to not only translate the text of a game for a foreign culture, but also translate the colours too?

# Answer
> 3 votes
Color symbolism in non-Western cultures (and even among Western cultures) is definitely incongruent. However, with regards to video games, typical Western and Japanese color symbolism is pretty universal; in other words even if a culture uses different colors for a given mood or theme, in a video game, it won't seem jarring to follow Western or Japanese norms for these simply because it's so pervasive.

For text coloring, yes - it can't hurt to vary color based on region context if you know that it might be more immersive that way.

A pretty good site is: http://www.empower-yourself-with-color-psychology.com/cultural-color.html

# Answer
> -2 votes
Those colors are universal, mane, they apeal to our primal selves. Red is the color of blood = danger black = color of night, space, darkness = mystery pink = color of skin when we blush/get excited (even if you're coal black you get a pinkish hue) green = color of plants, growth.

Don't worry too much about these kind of questions, if you're asking it from an strictly academical viewpoint I can understand you, but you should worry about internationalization issues when you have something to internationalize.

---
Tags: game-design, color, localization
---


# Question
Title: What was game development on the Apple II like?
I've asked a similar question about DOS development a while ago and got an excellent answer: What was the typical toolchain for DOS game development?

Now I'm wondering what game development was like on the Apple II in the late 70s/early 80s. I'm mainly interested in the early ones: II and II+, but I'd like answers about IIe etc. as well.

So here are my questions:

**What languages were used?**

I presume 6502 assembler, but BASIC was bundled and probably used a lot, too. Can you think of popular games written in BASIC? How about C?

**What was 6502 assembler development like?**

I've noticed that you can enter op codes directly if you start the system monitor, and you can even execute assembler directly with the mini assembler. But I cannot imagine that games were written like that, were there editors/IDEs? How were programs stored on disks/tapes?

**What was BASIC development like?**

The Apple II BASIC interpreter is not half bad, I guess you can write full programs in there. It also allows you to SAVE/LOAD programs, I presume to disk/tape. But was there no visual editor?

**Were there any APIs or Middleware?**

Or was it necessary to talk directly to the hardware all the time if you wanted to draw something or play a sound? Were there any libraries at all?

**Anything else that's different from today?**

I'd be happy to hear any other differences, like what image/audio formats were used. Given that there wasn't really a concept of files if I understand it correctly, I'm wondering how that worked. Did you have to type your graphics and sounds in assembler? How did that work in BASIC?

# Answer
> 6 votes
I did a lot of programming on the Apple (not professionally, but it's what I learned on) and Applesoft BASIC and assembler where about where it was at for hobbyists. Other languages were available -- Logo was common, Pascal was written about everywhere but I know no one who used it, I wasn't really aware of C being used on any Apple platform until Orca C for the Apple IIGS, there was a Forth interpreter with turtle-style (or call it Logo-style) graphics floating around too.

I'll address some of your questions, and then basic ideas:

> Can you think of popular games written in BASIC? How about C?

A lot of shareware was written in BASIC, not only Applesoft BASIC but also Integer BASIC (which as the name implies, did not have floating point numbers). The Eamon series comes to mind, but I can't really think of many others. Also, a lot of the software written by the Beagle Bros. was done in BASIC (mostly utilities, not games).

I believe most commercial software was written in assembler, though.

> But I cannot imagine that games were written like that, were there editors/IDEs? How were programs stored on disks/tapes?

I used Merlin Assembler, to call it an IDE might be stretching it, but it worked just fine. As you said you could drop to the system monitor and enter opcodes and run from there. Merlin had a way you could return to it from the system monitor (which I don't remember how now).

> But was there no visual editor?

There was a third-party tool that made the Applesoft environment a bit better, and would allow you to use your arrows to scroll about the screen and make edits like a visual editor (you still had to hit return at the end of a line or the changes wouldn't stick). I can't remember what that was, I used it quite a bit.

> Or was it necessary to talk directly to the hardware all the time if you wanted to draw something or play a sound? Were there any libraries at all?

On the Apple II+/IIe/IIc you pretty much were just talking to the hardware. There were a couple of programs in ROM you could use but they were very limited and usually you would PEEK and POKE various memory locations to change registers to do what you wanted, for example to change graphics modes, poke 49152 to trigger the speaker, etc.

On the Apple IIGS, the ROM came with a suite of libraries similar to what the Macintosh came with, for doing fancy GUIs and what-not. The ROMs were updated over time, and if you loaded a system disk that used newer libraries, they would read from disk rather than ROM, causing boot time to go REALLY SLOW. There was ROM 01, 02, and 03, and 02 -\> 03 was a free upgrade, and there was a release before 01 which they would do a free upgrade to 01 as well.

> I'd be happy to hear any other differences, like what image/audio formats were used. Given that there wasn't really a concept of files if I understand it correctly, I'm wondering how that worked. Did you have to type your graphics and sounds in assembler? How did that work in BASIC?

There were files, I am not sure what you mean by that, and ProDOS supported directories no less (the earlier DOS did not but still had a concept of a file you would recognize). I used bitmaps and .pcx's. I don't remember any audio files on the II+/IIe/IIc series, but that was because it was hard to make any noises fancier than video game blips and bloops. There were some hacks out there that did make fancy sounds (in particular, I had a disk that played Gun N' Roses), but it almost always was done grammatically.

Compared to modern environments, it was downright primitive. But remember, there was no support to run multiple programs at the same time, so your compiler effectively had to be your editor as well -- you couldn't really argue the benefits of vi vs. emacs, so whatever your compiler gave you, you learned to use. I do think it was a lot easier than using libraries piled upon libraries, and there are a lot of tricks if you are working for the hardware and know what it is. For example, a common implementation of "pause for a moment" was "for (int i=0; i\<1000; i++)" (it's different in BASIC), which is never used now, because hardware is so fast that you'd need a huge number, and even if it wasn't, it would be run on different kinds of machines so it would be a different pause for different people (the II+, IIe, and IIc ran at 1MHz, and the IIGS had a setting to slow down to that from its native 2.7MHz for better running of older software).

This is all from memory, I did not look at any references while writing this, so I apologize if my memory is faulty and I told you wrong stuff. But I hope this gives you a bit of a taste and answers a few of your questions.

# Answer
> 5 votes
**What languages were used?**

6502 for most, rarely C (Aztek), lots of BASIC, some Pascal (Apple Pascal).

**What was 6502 assembler development like?**

There were some pretty neat assemblers and tools for 6502: Orca/M, Merlin, plus in the later days it was possible to develop on a PC and serial link to the Apple to remote debug. Let's not forget the Beagle Bros. utilities. Edit + compile + run, the world never changes ;-)

**What was BASIC development like?**

No visual editor, just a console that let you interact with the BASIC buffer in the beginning. However, Beagle Bros. had a couple magical utilities that made most of the pain go away. And later there were shells that would at least act like a line-based editor for your writing. There was a tool (Expediter 2) that could crunch your BASIC down to an assembly binary that ran much faster (a one way trip).

**Were there any APIs or Middleware?**

There were some, but mostly of a very tight scope, nothing like what you'd call an SDK today. Let's be honest, in 48K you can't afford a general purpose API. In the later days there were two or three specific purpose SDKs that emerged for clicky adventure games, tile based games,

**Anything else that's different from today?**

Everything and nothing. Practices remain the same, tools got better.

# Answer
> 0 votes
Native Basic Interpreter: When you write a program you should number each line, enter your code and hit enter. A basic program looks like: 10: HOME 20: PRINT "HELLO WORLD"

In this example HOME clear the screen, if you need you should enter an intermediary line, fe.:

15: PRINT "GREETINGS"

As output it should clear the screen, show GREETINGS HELLO WORLD

command LIST show your code (whitout pause!) No capslock in some modes (just uppercases), no special characters. No pro games was written in BASIC, because of performance, you actually could see your program drawing the lines.

Just sound effects, it was hard to play music we have just a speaker with ONE bit (no kidding) peek 49152 change it's state, yes, you should control even the frequency and it was square wave form.

to go to assembly CALL -151

you should have to code by hand on monitor no IDE enter the address and your code (HEXA)

---
Tags: editors, ide
---


title: Try to connect to Game Maker server

text:
# Question
Title: Try to connect to Game Maker server
I'm trying to make a simple multiplayer experience with Game Maker, using a local network, and the basic idea is to use Game Maker's built-in networking functions.

Using a simple client-server pattern, I want to create a server only if there is no active server in my local network. My idea is to scan all the IPs from 192.168.0.0 to 192.168.255.255 (inelegant, I know, I'll figure out a way to determine "192.168.x.x" after solving this problem, maybe looking at the subnet mask). Here is the code:

```
var n1 = 192;
var n2 = 168;
var n3 = 0;
var n4 = 0;
var server = -1;
var ip = "";

while(n3 <= 255 && server < 0){

    ip = string(n1) + "." +
         string(n2) + "." +
         string(n3) + "." +
         string(n4);
    show_debug_message("Trying " + ip);
    server = network_connect(global.socket , ip, port );

    n4 += 1;
    if(n4 > 255) {
        n4 = 1;
        n3 += 1;
    }
}
if(server >= 0)
    show_debug_message("Found! Here you are: " + ip);
else
    show_debug_message("No IP found, man!");

```

And that's the problem: the first IP doesn't work, the game freezes for a minute and then all the others tries will fail, even the right one, with this error:

> trying 192.168.255.254
>
> ioctlsocket failed with error: -1
>
> Error (0x 2736): Could not set socket option

My tries:

1. I tried starting with the right IP and it works, so, the connection works.
2. I tried lowering the timeout to one second and the effect is what I expected: after one second the first attempt fails and all the latter fail as well

Any idea to check the connection before actually try it? Thanks in advance!

# Answer
Before answering, I tested your code in order to get your error, but it took too much time because of networking functions inside the loop - from `192.168.0.0` to `192.168.0.98` it took 25 minutes. This is an unacceptable waste of time, in my own opinion.

I have a solution to your issue though, which involves a slight deeper knowledge of networking: **broadcasting**.

Since you want to know if there are any servers in the local network, you can just send broadcast packets by using the GML function `network_send_broadcast()`. A broadcast packet is a special packet whose destination is a range of IP addresses; if the server address is `192.168.10.207`, it will broadcast to addresses `192.168.10.*`, so any device in the same subnet and using the right port will receive the incoming broadcast packet.

What is this for? You can use it for multiple purposes, for example getting the list of all servers currently running in the local network (*many* games let this for LAN games). For your purposes, I can think of two solutions.

### Servers send beacons to clients

Your server uses a socket to send periodical broadcast packets, which can be received from clients when players are looking for running servers. Then, clients can connect to the current server, otherwise (e.g. a timer runs out) there are no running servers so they start a new game as server themselves. If you allow multiple servers in the same network, broadcast packets will have different sender IP addresses, and you'll have to implement sort of server list on your own.

### Clients look for servers

On the other hand, we have clients sending broadcast messages looking for servers. When a server receives such packet, replies back with its IP address, allowing a client to connect to it. As well as before, after the client fires a "Hello, is anybody here?" packet(s) without getting any response within a certain amount of time, it can decide to set up and start a new game as server itself.

Both cases allow clients to be aware of multiple servers presence, if needed. In my own opinion, the latter solution is nicer because unnecessary network traffic is avoided.
> 1 votes

---
Tags: client-server, game-maker, socket
---


# Question
Title: How do I draw a high-performanced scatter plot
I am new to DirectX and currently I'm trying to use it for data visualization, to be specific, a 3D scatter plot. There are very limited resources on the internet, and I have read part of Frank D Luna's book as suggested by many. I studied some samples provided by Microsoft and finally have a grasp on how the loops work inside programs.

However, since I need to manipulate a huge amount of data and require performance as much as possible, I run into something that I hardly find reference with current material.

1. **Buffer Usage** I expect the points I plot to be constant after they are created, but the creation of points happens all the time, should I set the **D3D11\_USAGE** to Default or Dynamic, and which method to call when I need to update the buffer? I have noticed How to use UpdateSubresource and Map/Unmap?, and the presentation https://developer.nvidia.com/sites/default/files/akamai/gamedev/files/gdc12/Efficient\_Buffer\_Management\_McDonald.pdf by NVIDIA. But what should I do if I do need frequent updates of buffer, while no update for each data in the buffer needed?
2. I noticed in the example "Simple Direct3D game" by Microsoft, it seem to rewrite the entire buffer each time it is updated.

```
        auto objects = m_game->RenderObjects();
    for (auto object = objects.begin(); object != objects.end(); object++)
    {
        (*object)->Render(d3dContext, m_constantBufferChangesEveryPrim.Get());
    }

```

Is it really so? And How should I only **add new vertices** into the buffer every time updating it?
3. Since the program is expected to run very fast, the buffer is expected to be updated **much faster than once per frame**. Can I write a method to update the buffer and add a new point into the buffer every time I call it? If I could, can I put it in another thread or is there any better method to realize it?
4. In the example the main loop of the game seems to be in GameMain::StartRenderLoop(), is this loop running once per frame? And what determines the frequency of the loop?

I might have many misconception on frame and rendering, so thank you very much for the patience and answers.

# Answer
This is called 'dynamic' submission in which you generate vertices on-the-fly and draw them. The more efficient approach is to use 'static' submission where you upload the vertex data to the video card and draw it many times, but most real-world graphics programs are a mix of both.

> If you are doing 2D rendering, you should look at Direct2D if that's an option for you.

How to: Use dynamic resources

> You could also use the PrimitiveBatch class in the DirectX Tool Kit
> 2 votes

---
Tags: rendering, directx11, game-loop, vertex-buffer
---