# Question
Title: Not able to connect to Photon(PUN).photon unity networking error
I'm new to photon Networking. My game was working great suddenly this is appearing

Cannot send messages when not connected. Either connect to Photon OR use offline mode! UnityEngine.Debug:LogError(Object)

# Answer
Remove the player already in the scene and try to connect again. The PUN is trying to connect the player with the server.. Hope this will solve your problem.

All The Best
> 0 votes

# Answer
This is mine part of code, which is used to connect to the room by client

```
void OnConnectedToMaster() {
    RoomOptions roomOptions = new RoomOptions () { isVisible = false, maxPlayers = 5 };
    PhotonNetwork.JoinOrCreateRoom ("TestRoom", roomOptions, TypedLobby.Default);
}

void OnJoinedRoom() {
    PhotonNetwork.Instantiate ("Player", spawnPoint.position, spawnPoint.rotation, 0);
}

```

I guess they've changed something in API (using PUN only for the first day), but this is the code snippet which helped me to get it up and running (others were outdated and using `OnJoinedLobby` method.

I hope it will help you to solve your problem.
> 0 votes

---
Tags: unity, photon
---


# Question
Title: What's the purpose to divide constant buffer into groups?
In hlsl, we always see this

```
cbuffer cbPerFrame
{
    float2 gRasterSize;
    float4x4 gView;
    int gVoxelDim;
    float3 gVoxelSize;
};

cbuffer cbPerObject
{
    float gObjectID;
    float4x4 gWorld;
};

```

I know that the group **cbPerFrame** is to update variables every frame.
The other group **cbPerObject** is to update variables per object per frame, for example 2 times per frame in this case.
But how can hlsl know that? **cbPerFrame** and **cbPerObject** are just names but not semantics.
When we define different groups, does hlsl really know how many times this group should update every frame?

# Answer
> 1 votes
HLSL does not know about this, the naming is just for the programmer. But the separation in multiple buffers achieves an important thing:

**It saves memory bandwidth**

If you put all constant data into a single constant buffer you have to transfer the complete data every time you want to update a part of the data. In this case this means you'd have to send your per-Frame data again everytime you update your per-object data. This is a waste of memory bandwidth, which is a very limited ressource.

As you are updating the constant buffers manually via Direct3D (ID3D11DeviceContext::Map, ID3D11DeviceContext::Unmap) you have complete control over when (and why) constant buffers are updated. **HLSL has now way to know when constant buffers are updated, nor does it need to**. Your should use your control over constant buffers to optimize your memory bandwidth usage as much as possible.

---
Tags: directx, hlsl
---


# Question
Title: Simple 2D vehicle physics - maintaining vehicle length
I'm learning OpenGL and trying to make a simple simulation, which involves **vehicles (drawn just as a rectangles) moving along predefined path.** I've already read a few tutorials about designing a simple 2d car physics and tried to code something from a scratch.

Basically, **I want to use a simplification so called a bicycle model - we assume that the car has just two wheels - one at the front in the middle to steer, and one at the back in the middle that cannot steer.**

Moreover, the 'front wheel' is also a vehicle's current position. (possition is at front, not in the middle as usual).

It looks like this:

`mainAxis[0]` is the front wheel, `mainAxis[1]` is the back wheel

In most cases like described here or here, wheel movement is based on steer angle, which is fine when dealing with vehicle controlled by user input, but in my case I think I already have the direction of current front wheel movement - next node on the path.

---

This is how my movement function looks like for now: *(I rewrote it in pseudo-code to simplify)*

**I know it does not involve factors like steering forces, friction or speed reduction before turning. I'd like to make vehicle position to update properly first.**

```
// _deltaTime - time between frames
// velocity - vehicle speed (scalar value)

void updatePosition(double _deltaTime)
{
    //Front wheel is moving in direction of current target, while back wheel is moving along the 'previous' vehicle direction

    Vector2 oldPosition = currentPosition;

    Vector2 newPosition = currentPosition + normalize(currentTarget - currentPosition) * velocity * _deltaTime);

    currentPosition = newPosition;
    mainAxis[0] = currentPosition;

    mainAxis[1] += normalize(oldPosition - mainAxis[1]) * _deltaTime * velocity;

}

```

The vehicle turns fine, front wheel position is correct, however **it doesn't maintain the baseline (vehicle length), that is, the distance between the front and rear wheel.**

Turning looks more less like this:

*(red rectangle is a vehicle, with `mainAxis` marked as black line and current velocity to target as white line)*

I struggle to find a correct way to calculate wheels movement in a realistic way, i.e with preserving the car length (which is predefined).

Perhaps I should calculate back wheel movement reduction or move front wheel further...

---

*Thank you in advance for any assistance*

# Answer
> 1 votes
I think the culprit lies in this line:

```
mainAxis[1] += normalize(oldPosition - mainAxis[1]) * _deltaTime * velocity;

```

I'm not sure if this achieves the kind of turning you envision, but try something like this:

```
mainAxis[1] = newPosition-normalize(newPosition-mainAxis[1])*length(oldPosition-mainAxis[1])

```

which is basically:

```
mainAxis[1] = newPosition-AXISLENGTH*normalize(newPosition-mainAxis[1])

```

This way the Axis length will definitely stay the same. This should be physically correct (to a certain extent), considering most real life cars are front-driven and the back wheels are "dragged".

In your existing code you are trying to move the back wheels with the same velocity along your old main axis, which results in the shortening of said axis.

---
Tags: physics, mathematics, movement, car, vehicle
---


# Question
Title: Scrolling background tiles in an isometric environment?
I'm working on my first game and I've run across an issue, when the character moves around, the "camera" is supposed to follow but I don't know how to make the computer draw only the necessary tiles.

Here is what I currently have

```
    public void drawBack(Graphics2D g2d) {
    int x = mvmt.getX(),
        y = mvmt.getY();

    int charOffX = mvmt.getCharCamX(),     //the difference between the top
        charOffY = mvmt.getCharCamY();     //left corner and where the
                                           //character is drawn

    for(
        int startCoordX = ????,
            startCoordY = ????,
            startTileMapX = ????,
            startTileMapY = ????;
        startTileMapX < width && startCoordX <= 3 * screenWidth;
        startCoordX += startXadd, startTileMapX++, startTileMapY--
    ) {
        for(
            int drawCoordX = startCoordX,
                drawCoordY = startCoordY,
                tileMapX = startTileMapX,
                tileMapY = startTileMapY;
            tileMapY < height && drawCoordY <= screenHeight;
            drawCoordX -= xadd, drawCoordY += yadd, tileMapY++
        ) {
            if(tile.getTileMap(tileMapX, tileMapY, 1) == 1) {
                g2d.drawImage(tile.getTile(tileMapX, tileMapY), drawCoordX, drawCoordY, 32, 32, null);

            }

        }

    }

```

I need the tile map to line up with where the character is. Thanks so much in advance, this one really has me scratching my head!

# Answer
What I would do is to have a number stored for both width and height of the display in pixel space (which is what j2d works with, makes it easy). You can go about this using the JFrame's getWidth() call. Then, you'll need the player position, which I assume you already have. Then, create a value (let's call it cameraPos) that shows where the top right of the screen is by doing player.getX() - (frame.getWidth() / 2) and the same for the y axis. This is assuming your player is centered on screen. Then, we can finally figure out what to render.

```
cameraPos.x = player.getX() - (frame.getWidth() / 2);
cameraPos.y = player.getY() - (frame.getHeight() / 2);

```

Then, you can say something like

```
if(tile.getX() * tile.getWidth > cameraPos.getX() - tile.getWidth &&
      cameraPos.getX + frame.getWidth() < tile.getWidth * tile.getX() + tile.getWidth())
//Do the same for y axis
{

   render();

}

```

If you're asking on how to offset the tiles, just subtract the cameraPos from whatever tile you're drawing.
> 1 votes

---
Tags: java, 2d, isometric
---


# Question
Title: GLFW window freezes on title bar hold/drag
I am making a C++ program with Opengl and GLFW for window and input handling.
The program is updated with the main loop by delta time which is calculated by subtracting new frame start time with old frame start time.
My problem is that when title bar is hold the whole program stops, but when it is released the delta time is as big as hold time.
I am also using chrono library for calculating passed time.

My code:

```
unsigned long second = std::chrono::seconds( 1 ) / precision;
frameStartTime = std::chrono::system_clock::now().time_since_epoch() / precision;
while ( running && !glfwWindowShouldClose( glfwWindow ) && !input::keyboard::isDown( GLFW_KEY_ESCAPE ) ) {
    lastFrameTime = frameStartTime;
    frameStartTime = std::chrono::system_clock::now().time_since_epoch() / precision;
    deltaTime = float( frameStartTime - lastFrameTime ) / second;

    glfwPollEvents();
    mainScene->update( deltaTime );
    input::clear();

    mainScene->draw();
    glfwSwapBuffers( glfwWindow );

    countFps( deltaTime );
}

```

What am I doing wrong and how can I fix this issue?
Thanks.

# Answer
Balint said pretty much all there is.

This is Windows behavior, and there's not much you can do to fix it on the surface.

You could move your main logic to a background thread, though that is sometimes easier said than done. It won't be able to fix the visible pause, though - you'll be able to keep rendering and updating but you won't be able to see the results (hearing them will be fine, and networking will keep functioning as expected, though).

Most games just ignore it, and treat it as they would any other long frame pause that can happen from unexpected system strain. To deal with the big frame times, just cap the maximum amount of elapsed time; that avoids some of the problems that can happen with big frame times.
> 0 votes

---
Tags: opengl, c++, glfw
---


# Question
Title: What would happen if a 3D game used Bitmaps to render, instead of vertices and textures?
What would happen if a 3D game used Bitmaps to render, instead of vertices and textures?

# Answer
> 7 votes
It is possible to use a 2D API to get a 3D effect. I have done so in past by implementing my own code for 3D to 2D projection (using transformation matrices) and a 2D API capable of rendering polygons. Yet, I was projecting the points of the polygon point by point, and I did have 3D coordinates for the points... so weren’t they vertex?

This is the technique used by StarFox for SNES:

Remember that SNES didn't have native support for 3D.

---

My initial guess was you did mean voxels because you could bitmaps to define a 3D voxel model... this is often used when dealing with 3D scan or 3D printing, for example:

You can represent a voxel model as a 3D array, that could be stored as a bitmap. For example, multiple layers of an FMRI scan...

...can be composed to create a 3D model:

---

Another thing you can do is create sprites from a pre-rendered 3D model or even photos of physical objects, that was common in old games. For example the following image is from ClayFighter:

In the image, the monsters are 2D sprites.

There are also example that use 2D (camera facing) sprites in 3D environments:

Hexen (look at the monsters)

Mario 64 (look at the trees)

Populous: The Beginning (look at the people)

---

Finally, when loading 3D models to the graphic card, you are loading a large array of numbers. You will either hard code those numbers, compute them on the fly, or more likely load them from a 3D model file... nothing is preventing you from taking them from an image file, reading the colors of the pixels as the coordinates in the model. That's certainly something you can do.

One particular example of this is using an image as height map, in that case the X and Y coordinates of the pixels are the X and Y in the terrain, and the luminosity of the pixels is used as height (Z) for the terrain, for example:

---

Will any of these replace vertex? Pff, no. These are tools, tricks if you like, that you may combine to get the results you one with the restrictions you have.

# Answer
> 2 votes
You must use vertices, because the GPU only draws triangles, and you need to define those somehow.

The closest to bitmap based rendering are billboards. Some 3d games use 2d planes always oriented towards the camera to give the illusion if a 3d model (for example every sphere in super mario 64). But those still require a plane model to be present.

You need to define a 3d model somehow, and bitmaps aren't sufficient for this.

---
Tags: opengl, 3d, graphics, rendering
---


title: Shortcut for empty with collider

text:
# Question
Title: Shortcut for empty with collider
How to add shortcut key to add new empty already with a box/circle collider ?

If possible, it would be nice that empties are enumerated.

# Answer
> 3 votes
You will have to create a script and specify the shortcuts with the MenuItem attribute :

> To create a hotkey you can use the following special characters: % (ctrl on Windows, cmd on macOS), # (shift), & (alt). A hotkey text must be preceded with a space character ("MyMenu/Do\_g" won't be interpreted as hotkey, while "MyMenu/Do \_g" will).

```
using UnityEditor;
using UnityEngine;
public class MenuTest : MonoBehaviour {

    [MenuItem ("MyMenu/Create Box Collider %#x")]
    static void CreateBoxCollider () {
        GameObject g = new GameObject("Box Collider") ;
        g.AddComponent<BoxCollider>();
    }

    [MenuItem ("MyMenu/Create Sphere Collider %#h")]
    static void CreateSphereCollider () {
        GameObject g = new GameObject("Sphere Collider") ;
        g.AddComponent<SphereCollider>();
    }

    [MenuItem ("MyMenu/Create Capsule Collider %#c")]
    static void CreateCapsuleCollider () {
        GameObject g = new GameObject("Capsule Collider") ;
        g.AddComponent<CapsuleCollider>();
    }
}

```

Be careful to not use a shortcut already used by Unity itself.

**Important note** : Since it's an editor script. You must place it in a folder named "Editor" at the root of your project

---
Tags: unity
---


# Question
Title: Moving sprite using the accelerometer in LibGDX?
I don't know how to use accelerometer in LibGDX; how could I use the the motion sensor? I'm working for a top down game with the motion sensor. I'm new to this framework. My sprite image is already working and I want to control it using the accelerometer.

All comments are much appreciated, thanks in advance :)

Here is my code:

```
public class IngameDayOne extends ApplicationAdapter implements Screen {

// Constant rows and columns of the sprite sheet
private static final int FRAME_COLS = 5, FRAME_ROWS = 1;
// Objects used
Animation<TextureRegion> walkAnimation; // Must declare frame type (TextureRegion)
private Texture cat ;
SpriteBatch spriteBatch;
Texture Background;
// A variable for tracking elapsed time for the animation
float stateTime;

@Override
public void create() {
    // Load the sprite sheet as a texture
    cat = new Texture(Gdx.files.internal("cat2.png"));

    //Accelerometer
    float accelX = Gdx.input.getAccelerometerX();
    float accelY = Gdx.input.getAccelerometerY();

    if (accelX < -1){
        //go up
    }
    if (accelY < -1 ){
        //go left
    }
    if (accelY > +1){
        //go right
    }

    // Use the split utility method to create a 2D array of TextureRegions. This is
    // possible because this sprite sheet contains frames of equal size and they are
    // all aligned.
    TextureRegion[][] tmp = TextureRegion.split(cat, cat.getWidth() / FRAME_COLS, cat.getHeight()/ FRAME_ROWS);

    // Place the regions into a 1D array in the correct order, starting from the top
    // left, going across first. The Animation constructor requires a 1D array.

    TextureRegion[] walkFrames = new TextureRegion[FRAME_COLS * FRAME_ROWS];
    int index = 0;
    for (int i = 0; i < FRAME_ROWS; i++) {
        for (int j = 0; j < FRAME_COLS; j++) {
            walkFrames[index++] = tmp[i][j];
        }
    }
    // Initialize the Animation with the frame interval and array of frames
    walkAnimation = new Animation<TextureRegion>(0.090f, walkFrames);

    // Instantiate a SpriteBatch for drawing and reset the elapsed animation
    // time to 0
    spriteBatch = new SpriteBatch();
    stateTime = 0f;
    Background = new Texture(Gdx.files.internal("floor.png")); //File from assets folder
}

@Override
public void show() {
}

@Override
public void render(float delta) {

}

@Override
public void resize(int width, int height) {

}
@Override
public void render() {
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // Clear screen
    stateTime += Gdx.graphics.getDeltaTime(); // Accumulate elapsed animation time
    // Get current frame of animation for the current stateTime
    TextureRegion currentFrame = walkAnimation.getKeyFrame(stateTime, true);
    spriteBatch.begin();
    spriteBatch.draw(Background,0,0);
    spriteBatch.draw(currentFrame, 50, 50); // Draw current frame at (50, 50)
    spriteBatch.end();

}
@Override
public void pause() {

}

@Override
public void resume() {

}

@Override
public void hide() {

}

@Override
public void dispose() { // SpriteBatches and Textures must always be disposed
    spriteBatch.dispose();
    cat.dispose();
    Background.dispose();
}
}

```

# Answer
The accelerometer (obviously) measures acceleration. This includes gravity too.

If you want to make the object move around when the user moves the phone around, then you must subtract the gravity out of it. This can be done by getting the device's orientation (try the rotation vector sensor), creating a vector that points downwards according to it, multiplying it with 9.81 (The gravity is on average 9.81 m/s²), and subtracting it from the acceleration vector. If you want to apply gravity to the object, then you can simply use the output of the sensor.

Next you need to add this vector to the player's velocity vector and then add the velocity vector the the played's position vector.

However, I advise you not to do this, because there are multiple problems with this:

* You can't remove gravity from it easily. It will almost always have small error in it, which will make the player always move around, and you must introduce a system like in joysticks.
* It is not very exact. If the velocity doesn't go back to 0, then the character will again move around, but now constantly in the same direction. If there's a very fast stop, then you'll encounter this issue.
> 0 votes

---
Tags: java, libgdx, accelerometer
---


# Question
Title: Find X,Y Spiral positions by given ID. Hard formula.
I need to spawn new villages in my grid-based game map. But i am weak in advanced math.. I need to fetch coordinates by id. These 2 constants can be other numbers. Please help with the function in javascript :)

```
const DISTANCE = 3;
const FIRST_VILLAGE = [0,0];

function get_coordinates_by_id (id) {
  ..
}

get_coordinates_by_id(6) // returns [0, -3]
get_coordinates_by_id(11) // returns [0, 6]
get_coordinates_by_id(2) // returns [0, 3]

```

And in addition - i want it to return the coordinates without iteration of all the previous positions. I need a formula which just simply does many calculations and without iterations. If i have billion villages, i don't want it to iterate billion times until it finds the position.

# Answer
> 3 votes
Sorry for the Python implementation, but according to this answer the code can be implemented like this:

```
from math import ceil, sqrt
def spiral_strange(n):
    k = ceil((sqrt(n) - 1) / 2)
    t = 2 * k + 1
    m = t**2
    t = t - 1
    if n >= m - t:
        return 3*(-k),  3*(k-(m-n))
    else:
        m=m-t
    if n >= m - t:
        return 3*(-k+(m-n)), 3*(-k)
    else:
        m=m-t
    if n >= m - t:
        return 3*(k), 3*(-k+(m-n))
    else:
        return 3*(k-(m-n-t)), 3*(k)

```

# Answer
> 1 votes
Here's a solution that doesn't involve a very tricky formula: You just iterate and calculate coordinates until you find one. The solution is in Python and could probably use some improving, but it does get the job done.

The spiral iteration code is directly ripped from this SO answer.

```
DISTANCE = 3
FIRST_VILLAGE = (0, 0)

def get_coordinate(id):
    if id == 1:
        return FIRST_VILLAGE
    count = 0
    for coords in spiral(id, id):
        count += 1
        if count == id:
            return (coords[0] * DISTANCE, coords[1] * DISTANCE)

    return (0, 0)

def spiral(X, Y):
    x = y = 0
    dx = 0
    dy = -1
    for i in range(max(X, Y)**2):
        if (-X/2 < x <= X/2) and (-Y/2 < y <= Y/2):
            yield(x, y)
        if x == y or (x < 0 and x == -y) or (x > 0 and x == 1-y):
            dx, dy = -dy, dx
        x, y = x+dx, y+dy

print(get_coordinate(6))
print(get_coordinate(11))
print(get_coordinate(2))

```

EDIT: Another alternative, which is messy but potentially faster would be based on this answer:

```
import math

SIZE = 3

def coordinate(n):
    coord = get_coordinate(n - 1)
    return (coord[0] * SIZE, coord[1] * SIZE)

def get_coordinate(n):
    m = math.floor(math.sqrt(n))
    if m % 2 == 1:
        k = 0.5 * (m - 1)
    else:
        if n >= m * (m + 1):
            k = m / 2
        else:
            k = m / 2 - 1

    if 2 * k * (2 * k + 1) < n <= pow(2 * k + 1, 2):
        return (n - 4*k**2-3*k, k)
    elif pow(2 * k + 1, 2) < n <= 2 * (k + 1) * (2*k + 1):
        return (k+1, 4*k**2+5*k+1-n)
    elif 2 * (k + 1) * (2*k + 1) <= n <= 4 * pow(k+1, 2):
        return(4*k**2+7*k+3-n, -k + 1)
    elif 4 * pow(k+1, 2) < n <= 2*(k + 1)*(2*k+3):
        return (-k-1, n - 4*k**2-9*k-5)

print(coordinate(6))
print(coordinate(11))
print(coordinate(2))

```

---
Tags: mathematics, javascript, geometry
---


title: How can I avoid giant player classes?

text:
# Question
Title: How can I avoid giant player classes?
There is almost always a player class in a game. The player can generally do a lot in the game which means for me this class ends up being huge with a ton of variables to support each piece of functionality the player can do. Each piece is fairly small on its own but combined I end up with thousands of lines of code and it becomes a pain to find what you need and scary to make changes. With something that is basically a general control for the entire game how do you avoid this issue?

# Answer
You'd usually use an entity component system (An entity component system is a component based architecture). This also makes creating other entities way easier, and can also make the enemies/NPCs have the same components as the player.

This approach goes in the exact opposite direction as an object oriented approach. Everything in the game is an entity. The entity is just a case without any game mechanics built into it. It has a list of components and a way to manipulate them.

For example, the player has a position component, an animation component and an input component and when user presses space, you want the player to jump.

You can achieve this by giving the player entity a jump component, which when called makes the animatiom component change to the jumping animation and you make the player have a positive y velocity in the position component. In the input component you listen for the space key and you call the jump component. (This is just an example, you should have a controller component for movement).

This helps breaking up the code into smaller, reusable modules, and can result in a more organized project.
> 67 votes

# Answer
Games aren't unique in this; god-classes are an anti-pattern everywhere.

A common solution is to break down the big class in a tree of smaller classes. If the player has an inventory, don't make inventory management part of `class Player`. Instead, create a `class Inventory`. This is one member for `class Player`, but internally `class Inventory` can wrap a lot of code.

Another example: a player character may have relations with NPC's, so you may have a `class Relation` referencing both the `Player` object and the `NPC` object, but belonging to neither.
> 20 votes

# Answer
1) Player: State-machine + component based architecture.

Usual components for Player: HealthSystem, MovementSystem, InventorySystem, ActionSystem. Those are all classes like `class HealthSystem`.

I do not recommend using `Update()` there **(It makes no sense in usual cases to have update in health system unless you need it for some actions there every frame, these rarely occur. One case you may also think of - player gets poisoned and you need him to lose health from time to time - here I suggest using coroutines. Another one constantly regenerate health or running power, you just take current health or power and call coroutine to fill to that level when time comes. Break coroutine when the health is full or he was damaged or he started running again and so on. OK that was a little bit offtopic but I hope it was useful)**.

States: LootState, RunState, WalkState, AttackState, IDLEState.

Every state inherits from `interface IState`. `IState` has in our case has 4 methods just for an example. `Loot() Run() Walk() Attack()`

Also, we have `class InputController` where we check for every Input of the user.

Now to real example: in `InputController` we check if player presses any of the `WASD or arrows` and then if he also presses the `Shift`. If he pressed only `WASD` then we call `_currentPlayerState.Walk();` when this happends and we have `currentPlayerState` to be equal to `WalkState` then in `WalkState.Walk()` we have all components needed for this state - in this case `MovementSystem`, so we make the player move `public void Walk() { _playerMovementSystem.Walk(); }` \- you see what we have here? We have second layer of behavior and that is very good for code maintainance and debuging.

Now to the second case: what if we have `WASD` \+ `Shift` pressed? But our previous state was `WalkState`. In this case `Run()` will be called in `InputController` (don't mix this up, `Run()` is called because we have `WASD` \+ `Shift` check in `InputController` not because of the `WalkState`). When we call `_currentPlayerState.Run();` in `WalkState` \- we know that we have to switch `_currentPlayerState` to `RunState` and we do so in `Run()`of `WalkState` and call it again inside this method but now with a different state because we don't want to lose action this frame. And now of course we call `_playerMovementSystem.Run();`.

But what for `LootState` when player can't walk or run untill he releases the button? Well in this case when we started looting, for example when button `E` was pressed we call `_currentPlayerState.Loot();` we switch to `LootState` and now call its called from there. There we for example call collsion method to get if there is something to loot in range. And we call coroutine where we have an animation or where we start it and also check if the player still holds the button, if not coroutine breaks, if yes we give him loot in the end of the coroutine. But what if player presses `WASD`? - `_currentPlayerState.Walk();` is called, but here is the pretty thing about state-machine, in `LootState.Walk()` we have an empty method that does nothing or as I would do as a feature - players says: "Hey man, I haven't looted this yet, can you wait?". When he ends looting, we change to `IDLEState`.

Also, you could do another script that is called `class BaseState : IState` that has all these default methods behavior implemented, but has them `virtual` so you can `override` them in `class LootState : BaseState` type of classes.

---

The component based system is great, the only thing that bothers me about it are Instances, many of them. And it takes more memory and work for garbage collector. For example, if you have 1000 instances of enemy. All of them having 4 components. 4000 objects instead of 1000. Mb it's not so big deal (I haven't run performance tests) if we consider all components that unity gameobject has.

---

2) Inheritance based architecture. Though you will notice that we can't completely get rid of components - it's actually impossible if we want to have clean and working code. Also, if we want to use Design Patterns that are highly recommended to use in proper cases (don't overuse them too, it's called overengeneering).

Imagine we have a Player class that has all the properties it needs to exits in a game. It has health, mana or energy, can move, run and use abilities, has an inventory, can craft items, loot items, even can build some barricades or turrets.

First of all I'm going to say that Inventory, Crafting, Movement, Building should be component based because it's not player responsibility to have methods like `AddItemToInventoryArray()` \- though player can have a method like `PutItemToInventory()` that will call previous described method (2 layers - we can add some conditions depending on different layers).

Another example with building. Player can call something like `OpenBuildingWindow()`, but `Building` would take care of all the rest, and when user decides to build some specific building, he passes all needed information to player to `Build(BuildingInfo someBuildingInfo)` and player starts to build it with all animations needed.

SOLID - OOP principles. S - single responsibility: that what we have seen in previous examples. Yeah ok, but where is the Inheritance?

Here: should health and other characteristics of player be handled by another entity? I think not. There can't be a player without health, if there is one, we just don't inherit. For example, we have `IDamagable`, `LivingEntity`, `IGameActor`, `GameActor`. `IDamagable` of course has `TakeDamage()`.

```
class LivinEntity : IDamagable {

   private float _health; // For fields that are the same between Instances I would use Flyweight Pattern.

   public void TakeDamage() {
       ....
   }
}

class GameActor : LivingEntity, IGameActor {
    // Here goes state machine and other attached components needed.
}

class Player : GameActor {
   // Inventory, Building, Crafting.... components.
}

```

So here I could not actually divide components from inheritance, but we can mix them as you see. We can also make some base classes for Building system for example if we have different types of it and we don't want to write any more code than needed. Indeed we also can have different types of buildings and there is actually no good way to do it component based!

`OrganicBuilding : Building`, `TechBuilding : Building`. You don't need to create 2 components and write code there twice for common operations or properties of building. And then add them differently, you can use power of inheritance and later of polymorphism and incapsulation.

---

I would suggest using something in between. And not overuse components.

---

I highly recommend reading this book about Game Programming Patterns \- it's free on WEB.
> 11 votes

# Answer
There's no silver bullet to this problem, but there are various different approaches, almost all of which revolve around the principle of 'separation of concerns'. Other answers have already discussed the popular component-based approach, but there are other approaches that can be used instead of or along with the component-based solution. I'm going to be discussing the entity-controller approach as it's one of my preferred solutions to this problem.

Firstly, the very idea of a `Player` class is misleading in the first place. Many people tend to think of a player character, npc characters and monsters/enemies as being different classes, when in actual fact all of those have quite a lot in common: they are all drawn on the screen, they all move around, they might all have inventories etc.

This way of thinking leads to an approach where player characters, non player characters and monsters/enemies are all treated as '`Entity`s' rather than being treated differently. Naturally though, they do have to behave differently - the player character has to be controlled via input and npcs need ai.

The solution to this is to have `Controller` classes which are used to control `Entity`s. By doing this, all the heavy logic ends up in the controller and all the data and commonality is stored in the entity.

In addition, by subclassing `Controller` into `InputController` and `AIController`, it allows the player to effectively control any `Entity` in the room. This approach also helps with multiplayer by having a `RemoteController` or `NetworkController` class that operates via commands from a network stream.

This can result in a lot of the logic being shoehorned into one `Controller` if you aren't careful. The way to avoid that is to have `Controller`s that are composed of other `Controller`s, or making the `Controller` functionality depend on various properties of the `Controller`. For example, the `AIController` would have a `DecisionTree` attached to it, and the `PlayerCharacterController` could be composed of various other `Controller`s such as a `MovementController`, a `JumpController` (containing a state machine with the states OnGround, Ascending and Descending), an `InventoryUIController`. An added benefit of this is that new `Controller`s can be added as new features are added - if a game starts without an inventory system and one is added, a controller for it can be tacked on later.
> 4 votes

---
Tags: architecture
---


# Question
Title: Must I display Health and Mana to the player?
I'm thinking of doing one or more of the following:

* hiding the player's Health
* hiding the player's Mana
* hiding the player's Health from other players
* hiding the player's Mana from other players

I don't know of any game that has done such things before so I'm wondering if this will have a positive effect on the players and why no game has done so before.

# Answer
Hiding the player-character's (PCs) health actually got quite common in the FPS genre. Instead of showing a health number on the bottom of the screen, they represent the health state of the PC with a meta-interface. When the player is hurt, the screen gets a red tint or gets splattered with blood. This represent the pain the PC is experiencing.

The idea behind this is to make the game more immersive. Numbers on the user interface are often considered immersion-breaking because they are inherently non-diegetic. This is why some game designers try to minimize them as much as possible.

But hiding the exact health value is usually combined with quickly auto-regenerating health. The player doesn't *need* to know the PCs exact health, because it recovers so quickly anyway. But without quick health generation, health becomes a resource the player needs to manage. In order to manage a resource properly, the player must be able to check the exact number at any time.

Also, you must not forget to give *some* visual cue about the health state of the PC. When the player is completely unaware of it, they might not realize that their PC is almost dead, make a risky decisions and be surprised why they died so easily. This will be very frustrating for the player and might cause them to wonder if your damage calculation mechanics are buggy.

The same can be applied to mana. Provide some visual cue for the player how much mana their PC approximately has at the moment. Also, just like health, you should only do this when mana regenerates extremely fast. When mana is a resource the player needs to manage strategically, hiding it will be quite annoying for them.

Regarding hiding the opponent's health and/or mana: This is really just a question of how much information you want to hide. It is not uncommon for games to completely hide the enemy condition until they are defeated, but there are plenty of other examples of games which make the enemy condition transparent. Showing this information makes the game a bit more tactical (because the players have more information about who is currently winning a fight), while hiding that information makes the game more psychological (you have to guess the other character's status from the player behavior).
> 6 votes

---
Tags: game-design, ui-design
---


title: Problem with 2d rotation in OpenGL

text:
# Question
Title: Problem with 2d rotation in OpenGL
I have a function to perform sprite rotation :

```
void Sprite::rotateSprite(float angle){
    //Making an array of vertices - 6 for 2 triangles

    Vector2<gamePos> halfDims(_rect.w / 2, _rect.h /2);

    Vector2<gamePos> bl(-halfDims.x,-halfDims.y);
    Vector2<gamePos> tl(-halfDims.x,halfDims.y);
    Vector2<gamePos> br(halfDims.x,-halfDims.y);
    Vector2<gamePos> tr(halfDims.x,halfDims.y);

    bl = rotatePoint(bl,angle) + halfDims;
    br = rotatePoint(br,angle) + halfDims;
    tl = rotatePoint(tl,angle) + halfDims;
    tr = rotatePoint(tr,angle) + halfDims;

    /**
        1st triangle
    **/

    //Top right
    _dataPointer.vertices[0].setPosition(_rect.x+tr.x,_rect.y+tr.y);

    //Top left
    _dataPointer.vertices[1].setPosition(_rect.x+tl.x,_rect.y+tl.y);

    //Bottom left
    _dataPointer.vertices[2].setPosition(_rect.x+bl.x,_rect.y+bl.y);

    /**
        2nd triangle
    **/

    //Bottom left
    _dataPointer.vertices[3].setPosition(_rect.x+bl.x,_rect.y+bl.y);

    //Bottom right
    _dataPointer.vertices[4].setPosition(_rect.x+br.x,_rect.y+br.y);

    //Top right
    _dataPointer.vertices[5].setPosition(_rect.x+tr.x,_rect.y+tr.y);
}

Vector2<gamePos> Sprite::rotatePoint(Vector2<gamePos> pos, float& angle){

    Vector2<gamePos> newv;

    newv.x = pos.x * cos(angle) - pos.y * sin(angle);
    newv.y = pos.y * cos(angle) + pos.x * sin(angle);

    return newv;
}

```

And the result is

Am i doing something wrong ? It happens also when i put small angle (even if i put here angle 1 )

Thanks for help.

# Answer
Try

```
angle = angle *(3.14159/180.0)
newv.x = pos.x * cos(angle) - pos.y * sin(angle);
newv.y = pos.y * cos(angle) + pos.x * sin(angle);

```

Trig functions works with radians so you will have to do the conversion to radians as above. as stated in the comments, It is recommended you convert the `(3.14159/180.0)` to a constant and use the built in PI constant instead of 3.14159.
> 3 votes

---
Tags: opengl, rotation
---


# Question
Title: Unity - separate shapes on a map into individual objects?
Okay, I asked this question yesterday anonymously thus I couldn't edit it so I'm remaking it.

**Short version**: I have a transparent map with black borders (Colored map) and I want those shapes formed by these borders to become individual objects in Unity. Is it even possible and if it is, how?

**Long version**: I want to make a Grand Strategy type game with provinces and countries. However, I'm not really an experienced graphics nor Unity programmer.

I already have a map drawn with the desired black borders with each province being defined by these very borders and each has an unique color (sort of an identifier). Having just this seems plain and complicated to use so I'd like for each province to emit a color corresponding with a selected map type (diplomacy, terrain, domains, etc.). Obviously, this would be hard to do with just a single plain texture therefore I need to make objects and this is where my inexperience blocks me from continuing.

Is there anything I can do (in Unity and/or Photoshop) that could make the provinces be objects without manually isolating, importing and matching (as a puzzle) each single one?

I've already looked at countless questions and answers but still none fit my problem. I'm at my wits' end with this to the point where I'm actually thinking about scrapping the project.

# Answer
> 1 votes
This could be done with some custom code. You could write this as part of your game code and then disable it after it runs once, or make some kind of Unity extension to run it when needed.

Here's how I'd structure it:

* Get the map pixels into an array, and make a second array of the same size.
* Clear the second array to 0,0,0,0.
* Walk through the map array; when a non-black pixel comes up, run a flood-fill algorithm starting from there. Fill the map pixels with black, and track the filled pixels by writing them to the same positions in the second array. Also keep track of the min and max X and Y that the flood reaches.
* Create a texture, sized to (max X - min X, max Y - min Y), and copy those pixels from your second array into this new texture. Save this image to disk, and also save the min and max X and Y somewhere.
* Clear the second array again, and continue walking the map array.

You'll need to keep track of which images go with which min and max positions from the original map so you can position the sprites or quads or images and apply the images to them.

You could also do this all at load time and immediately create whatever geometry you want.

One way to use the generated images in your game would be to create a prefab that has a SpriteRenderer component on it, instantiate one instance of the prefab for each region, and set the SpriteRenderer's "sprite" to the region image. You can use the min and max X and Y values to figure out where to position these prefabs so they reconstruct the original map. You can then use the color property of the sprite renderer to represent whatever information you want.

---
Tags: unity, c#, maps, strategy
---


# Question
Title: Pairing algorithm for the Elo rating system
Imagine a 1 on 1 (not teams) competition between AI bots, like the Google AI Challenge. The various bots are assigned an ELO rating based on the outcome of the various versus matches. The reason I specify AI bots as they can compete 24/7 without regard for player fatigue, geolocation, etc.

Given limited server resources only so many bouts can be run per day. I'm looking for a heuristic (or an optimal algorithm) to choose which two bots should compete next.

All the past competitions have been tracked. By this I mean that the algorithm has more to work with than just the ELO ratings.

The use cases I'm partitularly interested in:

* The competition has been pairing randomly for while and now I want to make intelligent pairing decision.
* The Elo rating have stabilized and a bot is updated.
* The Elo ratings have stabilized and new bot is introduced to the competition.

**Update:**
I need to clarify. I'm not looking for an algorithm that will provide fair matches. I'm looking for an algorithm that will find matches most likely to update the Elo ratings of the bots to their *"true"* ratings with the least number of matches.

# Answer
> 3 votes
Given a normal Elo system, such a thing probably doesn't exist. It varies the scores based on the difference between an expected score and the actual score, so you can see that if you pair up people of equal skill, they're likely to draw (or have a 50% chance of winning) so the scores won't change, and if you pair up complete opposites, the veteran will almost always beat the novice (as expected) so the scores won't change there either.

The only thing that is likely to make one Elo score less accurate than another is having played fewer bouts. This means you will want them to play more. You don't have any information yet as to their actual skill level so the important thing is to get them to enter bouts and start to establish that level.

So, under these conditions, I'd just opt for ensuring that bots play as many different bots as possible, picking any bot they haven't competed against before, and favouring the selection of bots who haven't played much. New bots joining the system should be favoured in order to quickly establish their approximate levels.

# Answer
> 1 votes
I know you already marked an answer, but to be honest it's over-simplified and doesn't really address any of the core issues of an ELO system whether you're dealing with bots or real players. For example, the core considerations when creating a fair/accurate ELO system would be: number of players, number of matches, relative impact of skill (ie: chance) on outcome, matchmaking efficiency, and how much variance there is in rating per win/loss.

In an ideal world you'd be able to match people of equal skill, and in a game of skill they would achieve a 50% win-rate. However, that assumes you know everyone's skill and that the impact of chance is relatively small. Since you don't know the former (and you didn't specify the latter) there are a number of things you need to do in order to accurately determine skill in an efficient manner and it isn't as simple as having bots play as many different bots as possible:

1) You need to set up a baseline of skill for "new" players on a scale such that they can move up or down and that the baseline represents the expected average on a normal bell curve. IE: 1250 on a scale of 1-2500.

2) New players need to play a certain number of "placement" games in order to establish their initial rating, which is typically done in 10-20 games that are rated more heavily than subsequent games. IE: rating gain/loss is double during placements what it would be later in order to encourage quick separation of players.

3) You need to account for other factors in your matchmaking such as win-rate relative to total matches so that players on extreme ends of the skill curve are moved at a faster speed to their "true" skill by facing people more above or below their current rating. IE: a player with a 80% win rate over a decent sample size should face people further above their rating and climb the ladder faster than someone with a 55% win-rate that is closer to their true skill.

4) You need to have a good understanding of how chance impacts outcome and you need to account for matchmaking speed (queue times) when determining who to match in order to keep skill variance reasonable. Using the previous scale you shouldn't have a 1250 player facing a 2000 player under any circumstances (other than when both are unrated). It isn't a fair match-up and it doesn't allow you to accurately add/remove points from their ELO.

The way I would set a system up would be to create two modifiers to a base point gain/loss value, one using the expected outcome based on rating variance and one based on a win-rate to total matches value. IE: someone with a 1500 rating who has a 70% win rate that beats a 1600 rated player will gain more points for having a high win rate AND for beating a higher rated player.

Then you just need to ensure that players complete a reasonable sample size of games and you will have the "most efficient" system based on how much chance is involved in the "game" you're implementing the ELO system for. A game with relatively low chance could take as few as a couple dozen games to be accurate, a game with relatively high chance could take hundreds...

PS: for the record, you don't want people of drastically different skill levels playing because it just dilutes the accuracy of the system. Even if you skew it so that matches above a certain variance have very little impact it creates problems because players will either feel unrewarded or overly punished for matches with high variance.

edit: I forgot to address the "already rated" part of your question, but it's pretty straight forward. You match people based on closest skill rating available in the queue, because that's the most even match and the gain/loss of points (assuming similar win-rates) will be the static value. If the players are accurately rated they would maintain the 50% win-rate and neither climb or fall. If they *aren't* then the more skilled player will win more than lose and their rating will update.

Introducing a new player is even simpler, they start at the baseline and get matched against players of that skill (with the increased gain/loss) until their placements are completed. So let's assume the normal point gain/loss per match is 15 without any modifier, here's an example new player placements and rating (with double gain/loss):

* Initial: 0-0 (1250) - faces 1250 opponent
* Loss: 0-1 (1220) - faces 1220 opponent
* Loss: 0-2 (1190) - faces 1190 opponent
* Win: 1-2 (1220) - faces 1220 opponent
* Win: 2-2 (1250) - faces 1250 opponent
* Win: 3-2 (1280) - faces 1280 opponent
* Win: 4-2 (1310) - faces 1310 opponent
* Loss: 4-3 (1280) - faces 1280 opponent
* Win: 5-3 (1310) - faces 1310 opponent
* Win: 6-3 (1340) - faces 1340 opponent
* Win: 7-3 (1370)
* final rating: 1370

---
Tags: game-design
---


title: Creating an in game experience system

text:
# Question
Title: Creating an in game experience system
This has been asks at least a quarter dozen times, I know. This has a second part the others didn't. In my question I am looking towards a math function that can be used and inverted for finding exp/ levels.

From my reading, Runescape does: `Exp for next level = (Previous Level XP + Previous Level XP * 10%)`

**What kind of math function could I look to to find your current level from a number of XP**?

# Answer
You can look at Blizzards WoW implementation. On server, they have a database table which is responsible for for holding XP values for each level, and the level player is on now. So it basically fetches the data from database and applies it to the client. Also, on wowpedia I guess, they have many formulas used for different in-game mechanics (damage multipliers, damage mitigation with armor, etc).
> 2 votes

# Answer
I don't see why you would ever want to use an algorithm to determine the level based on an experience total. For one thing - you need to be storing the player's level, not only because you're going to need it and don't want to have to calculate it but also because you may adjust your experience curve at some point and you don't want that to impact player levels.

Secondly, you're making a pretty big assumption here that the experience per level needs to scale. Personally, I think having absurd amounts of experience/level to be absurd and pointless because it either gets too grind-heavy or you need to ramp up experience gains to compensate.

IE: why should killing an equal level mob at level 50 give more experience than killing an equal level mob at level 1? In my opinion... it probably shouldn't. What a lot of games do is simply adjust exp gains based on relative level so that it encourages progression but allows for a static exp/level number.

If you want a scaling experience system then I would suggest what you said above: simply create a table and store the exp per level values. You shouldn't have so many levels that it becomes a burden and should be relatively easy to set up.
> 1 votes

---
Tags: game-design
---


# Question
Title: Saving an array in GameMaker with DS Maps
I have the following issue. I'm creating a game with different levels. When the level is generated, an array of random number is generated for later use.

If the player leaves the game and come back later, I would like the array to be the same. So I'm trying to save the array when the level is generated. I was thinking about using the function `ds_map_add_list(id, key, value)`.

I'm digging through the documentation, but I'm a bit lost and I have a few questions:

* How do I create a list from a GML array?
* If I create a DS Map with the following function `inventory = ds_map_create();`, what's the scope of the DS Map? Can I use it only in the object holding the code where it was created?

# Answer
Use `ds_grid` for store 2D array or `ds_list` for store 1D array. Then you can use `ds_..._write` function for write data to string (and write that string into file, for example).

Many other ways are possible there, but it depend on what exactly you have in array, etc.

Simple example for 1D array.

```
/// array_write_as_list(array)

var array = argument0;
var data = ds_list_create();
for (var i=0; i<array_length_1d(array); i++)
{
    ds_list_add(data, array[i]);
}

var result = ds_list_write(data);
ds_list_destroy(data);
return result;

```

And usage of it:

```
var s = array_write_as_list(your_array);
// now you can write "s" to file, etc

```

For reading need to use similar way.

> what's the scope of the DS Map? Can I use it only in the object holding the code where it was created?

Any data structures `ds_...` are global (and you need don't forget to destroy them, when it not need more), but variable, where you stored id of data structure, has own scope. For example, if you use `var data = ds_list_create()` then you can use `data` variable only inside current script (and you should destroy this data structure, otherwise there will be memory leak). If you use `data = ds_list_create()` then you can acces this data structure from any object, using `data` variable, like `ds_list_add(obj_enemy.data, 100);`, etc.
> 1 votes

# Answer
I needed something similar when I was collaborating with a friend on a simple shmup. I was doing development and he was doing design. I exposed various game constants in a plain-text .ini file. He could edit them and modify the feel of the game without having to recompile the code.

I came to the same conclusion you did: I used `ds_map`. Basically, on startup, my game would run `scr_readIni.gml`, which set a bunch of variables. Here's an example:

```
globalvar options;
options = ds_map_create();
ds_map_add( options, "acceleration", "2.5,2.5" );
ds_map_add( options, "maxspeed", "4.0,4.0" );
ds_map_add( options, "subBeatFirePoints", "0.25,0.75" );
ds_map_add( options, "xPixelOffset", "-24,-24" );
ds_map_add( options, "yPixelOffset", "-24,+24" );

```

I scoped `options` as a global variable so that the appropriate game objects had access to it. There's probably a more elegant method -- there is in most object-oriented languages -- but this was the approach I settled on.

After these variables were set, I'd check for the existence of my .ini file. If it existed, I'd overwrite the variables I had just set with the ones stored in the .ini file.

```
if( file_exists( global.configFilename )){

    ini_open(global.configFilename);

    // Read variables : OPTIONS
    // (e.g. movement, allowed firing subbeats, etc.)
    ds_map_replace( options, "acceleration", ini_read_string( "options", "acceleration", options[? "acceleration"]));
    ds_map_replace( options, "maxspeed", ini_read_string( "options", "maxspeed", options[? "maxspeed"]));
    ds_map_replace( options, "subBeatFirePoints", ini_read_string( "options", "subBeatFirePoints", options[? "subBeatFirePoints"]));
    ds_map_replace( options, "xPixelOffset", ini_read_string( "options", "xPixelOffset", options[? "xPixelOffset"]));
    ds_map_replace( options, "yPixelOffset", ini_read_string( "options", "yPixelOffset", options[? "yPixelOffset"]));

    ini_close();

    return true;

// If .ini file doesn't exist, just return (default settings set above)
} else {

    return false;

}

```

Note that I ended up storing my arrays of reals as a string. When I needed to use them again, I split the string by commas and cast them to reals via a function:

```
// ds_list_to_reals( input ds_list )
//
// Goes through each item and casts it to a real

inDsList = argument[0];

var i;
for( i = 0; i < ds_list_size( inDsList ); i++ ){
    ds_list_replace( inDsList, i, real( ds_list_find_value(inDsList, i) ) );
}

return inDsList;

```

If I had occasion to revisit this project, I'd probably try to update my code to match the approach taken by Dmi7ry in the other answer.

One last note: if you're interested in saving space, you could simply save the number you're seeding the random number generator with. Then, if you reseed the random number generator with the same number on the next startup, it'll generate the same sequence. Here's a snippet from the official docs:

```
ini_open("Save.ini")
ini_write_real("Levels", string(level), random_get_seed());
ini_close();

```

The methods to research are `random_get_seed` and `random_set_seed`.
> 1 votes

---
Tags: game-maker
---


# Question
Title: How do I determine my games minimum hardware/software requirements?
With me going it alone in development I only have limited resources at my disposal i.e one pc with which I develop and test the game. so I only know for certain my game works with that setup.

What options have I got in testing the game on the many different hardware/operating system combinations? Its a windows desktop game.

# Answer
> 31 votes
Off the top of my head I'd suggest trying to run the game on a few other PCs from friends or relatives. After that you might want to consider some form of beta test, i.e. publishing a demo or something so you can get community feedback.

# Answer
> 26 votes
One of my favorite ways to find this info is by using virtual machines.

Seeing as how you can configure the hardware and memory that the VM is allowed you can test a wide range of setups on your own PC. This also allows you to test across multiple operating systems.

# Answer
> 18 votes
You should have some rough idea of the minspec just by developing your game -- for example if you made an explicit choice to use D3D10+, you obviously are culling out XP machines. So that's a place to start.

Find a way to test on as many machines as possible, ideally after implementing some way to gather performance metrics automatically (as users can be unreliable) as well as non-identifiable information about the machine the game is running on (processor(s), core count, GPU type, RAM, OS, et cetera -- take a look at the kind of data the Steam Hardware & Software Survey collects). One of the best ways to do this is to give your game to friends and family, as has been suggested many times already. Another way might be to approach a community of hobby game developers and see if they are interested in testing your game. I'm not sure such a thing would be an appropriate *question* here on GDSE, but you could probably find a few people in the 'chat' area and you could also look around/post on websites like:

All of those websites have forums or sub-forums dedicated in some way to showing off games, and so you might be able to get a reasonably good response out of them. I would make sure to disclose up front whatever statistics your game collects and/or sends you though, and why you are collecting them. People can get annoyed by that if they discover it after the fact.

N.B. that the Steam survey is also a useful tool in itself for gauges what a minspec should be -- it can help you see what the cost/benefit ratio of supporting a particular feature or class of hardware might be for you.

# Answer
> 13 votes
Check:
\- How much RAM it uses
\- How much texture + GPGPU memory it uses
\- Minimum frame rate / Current frame rate * CPU speed * SpeedUpFactorOf(minimal number of cores you can use)
\- Similar equation for GPU calculation units
\- what level of opengl/directx/cuda your game engine requires from the graphics adaptor
\- how much disk space the installation + user info takes...

Also test on various hardware configurations.

# Answer
> 8 votes
Basically you want to test on as many other machines as you can - from your friend's hard-core gaming rig to your gran's email-and-internet-only machine. Especially your gran's email-and-internet-only machine, because it's probably loaded with cruftware and other stuff that will interfere and slow your game to a crawl.

PC compatibility testing is a big nasty can of worms, and there's a reason why professional testing is expensive. So you want as many different odd scenarios tested as you can.

Beta testing is the way to go I think, both with friends and family and a wider circle in your fan community. Key thing - don't rely on anecdotal reports. Your friends might be relied on to actually reply, but the wider community will not, unless you make it easy for them.

Build logging into your app to give you hard facts on FPS, startup time, etc. Give the user an easy questionnaire, ideally built into the game, where they can report whether or not they though it played okay. And have those statistics and logging easily emailable / transmittable back to you, for you to pore over later. The more stats you get back, the better a sense you can have of whether your title is a) working at all on other systems, and b) working well on other systems.

# Answer
> 6 votes
Test on as many PCs as you can (that will also help you to catch all specific bugs). As developer you should know your main bottlenecks - focus on stressing them. You may ask your friends, colleagues at work, girlfriend, parents, lots of people in forums.

P.S. Just for reference:

* CPU requirement = run game in minimum resolution or with no GPU rendering at all (I hope the render code utilizes minimum of CPU)
* GPU requirement = run the game on powerful CPU with default resolution and see which GPU is sufficient of doing the task, also mention minimum Direct3D/OpenGL version
* RAM requirement = how much RAM does the game takes (e.g. via TaskManager, with VM size column, to see all allocated RAM, not only active)
* Sound = almost anything fits, just mention 2 / 5.1 channels support
* Display = specify minimum playable resolution where game controls fit
* Network = some massive load tests and see which bandwidth allows it (56k modem, DSL, T1, LAN)
* Keyboard/Mouse/Tablet/Joystick, etc..

# Answer
> 2 votes
For requirements, I would assume minimum things required to run you game. It will depend on what technologies you use to develop your games.

For example, if you use specific APIs, such as D3D9 or OpenGL 3.0, you will need to specific that, because certain APIs are not downward compatible.

If you build with windows with .net framework, you will also need to specific that as well.

For performance requirements, trying on different machines are pretty much the best way to go, though you may be able to measure the related performance by calculation.

for example, if your current video card runs at 60 fps, and another computer with the similar configuration, except the video card is half speed of yours, should run about the half speed of your machine. Again, this is just an estimate, many others properties will hit the performance differently, but you can use that base info to test your game on targeted devices.

Hope that helps, and anyone is welcome to correct me for any reasons.

# Answer
> 1 votes
Depending on your target market (I assume it isn't cutting edge 3d ie. expensive graphics cards needed), I'd look at picking up a selection of older graphics cards from somewhere like EBay so that you can test on both NVidia and ATi cards.

# Answer
> 1 votes
It is always perfect get comunity feedback as mentioned. But where to get community and people who will try to test it? Posting it on some indie games forums will help, but problem will be to get actual feedback.

Only few percent of people who will test a game it will write you their exact configuration and problems that ocured. People just dont do that. Much better way is enable some kind of benchmark with reading users system configuration. Ask user to run some one button benchmark. Offer some numbers and times(yeah people like it :-)) and let him compare with other users (with sending data) ... It will help.

And then you have database full of configurations, screen resolutionn, render times and failed features...

If you are on windows calling DXdiag will help you read the users configuration. But there are some programs you can use on other systems.

# Answer
> 1 votes
As mentioned by others, the best way is to get the a beta out there and gather community feedback to get reliable results.

I'd also like to suggest the use of ESXi. It's a Virtual Machine solution from VMWare. Don't be put off because it's a VM solution. ESX is a lot more low level.

This would probably be ideal to you since you have one machine. You can test different operating systems, hardware setups (bar the graphics hardware, ESXi would use whatever you have installed on your machine).

It's basically its own very slimmed down operating system that you can install other operating systems on top of. We use it at work for compatibility among a great deal of OS's. It's very fast and reliable, almost as responsive as a vanilla machine.

I know hardware requirements is what you're looking for and ESXi has a very nice feature where you can limit the amount of RAM, CPU or disk space usage by the operating system and could potentially emulate how your game would run on anything from a low end CPU or low memory, to top-end CPU or memory use (limited by your actual hardware).

So if you had quite a high spec PC you could install ESXi on it, install whatever operating systems you wanted to and play around with the CPU and Memory usage (I believe you can even modify the number of cores the OS uses as well!)

Here's a link to it: http://www.vmware.com/products/vsphere-hypervisor/index.html

Best thing about it? It's 100% free!

# Answer
> 0 votes
Running some kind of profiling tool would be one way. For Java programs you could use VisualVM (https://visualvm.github.io/). Wikipedia lists some other ones. See: https://en.wikipedia.org/wiki/List\_of\_performance\_analysis\_tools. The same goes for debugging memory. See: https://en.wikipedia.org/wiki/Memory\_debugger

Basically this amounts to checking your memory and CPU usage at some regular interval while running the program/playing the game. Then you calculate some average range and that's what it needs most of the time. Ideally this would be automated (for consistency and accuracy) and you'd want to exclude the amounts of those resources consumed, shared, or used by other processes. There *might* be some priority issues hiding the fact that your program might use more memory if it was available. I.e. if the OS was super busy your program might founder a bit from having not quite enough memory.

Ultimately you have to test/benchmark/profile and then analyse those tests. It's good to have a pre-defined performance metric to compare to. E.g. in an FPS you might want 30+ FPS for playable/enjoyable gaming. Based on that you would set the minimum bar at/above the hardware specs needed to meet that 30+ FPS some percentage of the time (it's always possible for the user to run too much at once and cause crashes and hangs).

As others have said, you really need other people to test it on a range of different hardware. In an ideal world you'd have a bunch of groups with similar hardware within a group and conduct some kind of control vs. experiment testing to see if more/less memory, cpu, gpu mattered when the other factors were held constant.

---
Tags: hardware, requirements, testing
---


# Question
Title: How do I inverse level progression and make new stats?
I'm trying to make something like Vampire: Dark Ages in RPG Maker MV, but the problem is that I need new stats and a reverse level progression, as long as you start at 12nd generation (like the "level 1" in the rest of the games) and the next "level" is 11st generation.

It should have this stats:

* Strenght
* Dexterity
* Resistance
* Charisma
* Manipulation
* Appearence
* Perception
* Intelligence
* Wits

This would only change by "buying abilities" with Job Points, and they determinate most of actions in the game. The only that would change would be the "Vitae Points", that act as Magic Points or Mana Points. When you have higher generation (low level), you have less Vitae/Blood points than if you have lower generation (high level).

How can I make this work? There's some plugin for this?

# Answer
> 1 votes
## **I was investigating and I've come to somekind of answer:**

> Is there some plugin for this?

Yes, there are plugins that can achieve this, more or less. I've used three: Yanfly's Base Parameter Control, this one is useful to set custom parameter calculations, Yanlfy's Class Base Parameters, this makes it easier to set your own way of developing your characters, and Himeworks Parameter Tables allows you to create your own parameters.

> How can I make this work?

Well, in this case, there are two ways to make it work. The easiest is using the plugins mentioned earlier, and the other is using common events and Yanfly's Actor Variables. Using common events you can make a dice roller that executes every time you use some ability and define your own level up event. For example, I've made an event called "Diablere" and an ability to use it. It would check first if the ability has effect, and then it would check the effects of leveling up.

---
Tags: rpg, progression, rpg-maker-mv
---


title: Multiplayer game server sync

text:
# Question
Title: Multiplayer game server sync
I am building a 2d multiplayer game with no physics and my own authoritative server. Already have all players getting synced each with other but their movement isn't so smooth yet.

Here is the mechanics:
\- player clicks on the screen to move towards the mouse pointer. Client sends action + angle to server
\- server calculate new position based on a certain speed and sends it back
\- player then moves through interpolation

After reading a lot of articles and play around with few samples code, I still have my doubts about how to get the clock right on both sides.

Would the approach below be suitable for my type of game?
\- Run the server at 1000/10
\- Run the Client network loop at 1000/60 and the game loop at 1000/60

Also do I need a game loop running in the server at 1000/60?

# Answer
The clock speed matters less, as long as you make sure the server and the client game steps are kept in sync. This article by Gary Weiss discusses this issue. Essentially either the game loop on the client or the server be late/early and you need to take care of these discrepancies.

Here's a proposed piece of code he wrote to implement these syncs (in JS):

```
// the game loop runs with an adjusting setTimeout call
let nextExecTime = null;
let gameLoop = () => {
    let stepStartTime = (new Date()).getTime();
    this.step();

    // delay/hurry the execution of next step if requested.
    // this could happen because of client-server step drift.
    nextExecTime = stepStartTime + this.options.stepPeriod;
    if (this.delayNextStep) {
        nextExecTime += STEP_DELAY_MSEC;
        this.delayNextStep = false;
    } else if (this.hurryNextStep) {
        nextExecTime -= STEP_DELAY_MSEC;
        this.hurryNextStep = false;
    }

    setTimeout(gameLoop, nextExecTime - (new Date()).getTime());
};

// in same cases, setTimeout is ignored by the browser,
// this is known to happen during the first 100ms of a touch event
// on android chrome.  Double-check the game loop using requestAnimationFrame
let gameLoopChecker = () => {
    let currentTime = (new Date()).getTime();
    if (currentTime > nextExecTime) {
        this.step();
        nextExecTime = currentTime + this.options.stepPeriod;
    }
    window.requestAnimationFrame(gameLoopChecker);
};

```

Note for the sake of transparency: me and Gary are co-developers of an open-source library for multiplayer games in Javascript: Lance
> 3 votes

---
Tags: javascript, multiplayer, client-server, interpolation, movement-prediction
---


# Question
Title: Given a point on the surface of an OBB, return normal of the face
So I have this class `OBB` which implements a `test` function that determines whether a ray hits it. If it does, a passed in struct is assigned a bunch of variables:

```
struct HitData
{
    float   t;
    Color   color;
    Shape* lastShape = nullptr;
    Vec lastNormal;
}

```

The last member, `Vec lastNormal;` is supposed to get its value from the class'

`normal(Vec& point)` function.

Here's where I'm drawing a complete blank. I.e. I cant seem to find any obvious (or non-obvious) solutions to how to determine the normal. Essentially what I want to do is identify which of the 6 planes the point lies on. In theory I could brute-force it and just do an intersection test against all the planes but that just seems unnecessarily expensive. The OBB is defined by a center, three basis vectors and their half-lengths.

Any idea how I could approach this problem?

# Answer
> 1 votes
It sounds conceptually simple to me, but I don't know how it could be optimized. The idea would be:

* Calculate **v = point - center**;
* Project **v** into your OBB's basis, obtaining **v'**;
* Find the coordinate of **v'** that has the largest absolute value;
* Zero the other coordinates out, obtaining **d**;
* Project **d** back into the world basis, obtaining **d'**;
* Normalize **d'**. That's your normal! :)

This works because the OBB is a unit cube in its own basis. We subdivide space into six unbounded pyramids that each correspond to a face. Determining which face the point is on is the same as determining which pyramid it is in. And that is pretty simple: just find its predominant coordinate.

---
Tags: c++, mathematics, bounding-boxes, raytracing
---


title: Problem with C# script in 2D game

text:
# Question
Title: Problem with C# script in 2D game
I'm busy following this YouTube tutorial for a 2D game in Unity by inScope: https://www.youtube.com/watch?v=-gC1u7qHMY4&list=PLX-uZVK\_0K\_6VXcSajfFbXDXndb6AdBLO&index=6

I decided to not finish the attacking episode and skipped to the next episode. But things were not working out so I deleted all my new work so everything will be back to how it was before.

But low-and-behold my attack stopped working. What should happen is whenever I press Left Shift my character should play his attack animation.

I've rechecked the videos again and again but I can't find whats wrong with my script! The script is in C#, and there are no errors in the script. I don't know whats wrong PLEASE HELP!

```
public class Player : MonoBehaviour
{
  private Rigidbody2D myRigidbody;

  private Animator myAnimator;

  [SerializeField]
  private float movementSpeed;

  private bool attack;

  private bool facingRight;

  // Use this for initialization
  void Start ()
  {
    facingRight = true;
    myRigidbody = GetComponent<Rigidbody2D> ();
    myAnimator = GetComponent<Animator> ();
  }

  void Update()
  {
    HandleInput ();
  }

  // Update is called once per frame
  void FixedUpdate ()
  {
    float horizontal = Input.GetAxis ("Horizontal");

    HandleMovement (horizontal);

    Flip (horizontal);

    HandleAttack ();

    ResetValues ();
  }

  private void HandleMovement(float horizontal)
  {
    myRigidbody.velocity = new Vector2 (horizontal * movementSpeed, myRigidbody.velocity.y);  // vector2 = x-axis - 1, y-axis = 0
    myAnimator.SetFloat ("speed", Mathf.Abs (horizontal));
  }

  private void HandleAttack()
  {
    if (attack)
    {
      myAnimator.SetTrigger ("Attack");
    }
  }

  private void HandleInput()
  {
    if (Input.GetKeyDown (KeyCode.LeftShift))
    {
      attack = true;
    }
  }

  private void Flip(float horizontal)
  {
    if (horizontal > 0 && !facingRight || horizontal < 0 && facingRight)
    {
      facingRight = !facingRight;

      Vector3 theScale = transform.localScale;

      theScale.x *= -1;

      transform.localScale = theScale;
    }
  }

  private void ResetValues()
  {
    attack = false;
  }
}

```

# Answer
As mentioned before "stopped working" does very little to show what is wrong. Maybe check if the attack value is true by putting this code in void update : `Debug.Log(attack);` and look closely at you console. It will print the value although a lot it will print it and if it remains false well look at editing this part:

```
private void HandleInput()
{
  if (Input.GetKeyDown (KeyCode.LeftShift))
  {
    attack = true;
  }
}

```

If it does not work I tried but I am also noob. :P
> 0 votes

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


# Question
Title: How do I calculate player retention (and other industry accepted stats) for a single-player RTS game?
Suppose there is a typical desktop RTS game **without online multiplayer** on a Windows platform, like the original Warcraft: Orcs & Humans. It still connects to a server to log basic anonymous info about the player's sessions. Now it would be interesting to see customer (player) retention (and other stats) in an industry-accepted way.

What are some typical retention (and other stats) available to game developers, relevant to offline desktop games in general?

Unlike other games, RTS implies longer gameplay sessions (40min+). How does it affect retention calculation? What are some useful retention metrics (and other stats) in this case?

How to calculate above retention parameters, what statistics values are needed to do it?

# Answer
In a studio where I worked we use to track different type of retention: Day 1, Day 3, Day 5. This metric was calculated saving a UID of the user that started a game session for the first time. Each new log-in in the game, with that UID we could see after the first day how much UID were back. Then again after 3 day and again. This was the retention.

You can tweak you time span according to what do you think your critique part will be.

You can also record the mission that a player starts, in order to find some "holes" in your missions.

Another very useful metrics is the play session length that can help you to tweak your game experience around the session.

Metrics on the object of your game, to understand which are more used and which are not.
> 2 votes

# Answer
If the game is truly offline (no hidden connection to a server) then there aren't really any good "retention" statistics you can reliably track that aren't simply being estimated based on sales data and by monitoring community activity (forums, support, etc).

However, if you assume some kind of online account or client (IE: Steam) then getting retention metrics becomes trivial because Steam stores all that handy information for you in order to display it to the player.

The important information as a developer/company would be:

* Weekly, monthly and quarterly sales
* Daily, weekly and monthly logins
* Average session length
* Number of support requests
* Average time to resolution of support requests

Those would be what I'd be interested in for mostly obvious reasons... sales tells you how well your game is doing in concrete numbers, logins tells you how popular your game is, session length tells you how engaging the game is, support tickets tell you about the health of the game, and resolution reflects the quality of your support.

Keep in mind that watching those numbers relative to patches, competition within (and outside) of your genre, and other factors over time will help you assess the direction you need to take the game or future releases.

For example, if you are selling 10k games per week and have 100k average logins with an average playtime of 45min per session and suddenly that doubles (or cuts in half) after a new patch then that gives you critical data moving forward about how the player-base feels in a way that community and feedback can't measure.
> 2 votes

---
Tags: analytics, retention
---


title: Third Person Camera Splines

text:
# Question
Title: Third Person Camera Splines
I'm having trouble coming up with a formula/method of creating third person camera with a variable distance from the player given a specific camera pitch.

This image shows something close to my desired result:

I basically only have two requirements. The camera has to be directly calculated from a pitch. The camera should roughly follow a smooth curve between the minimum and maximum camera distance and the halfway point is around 50% of the distance (as seen by the graph in the top right of the image).

**So, Option A:**

I create a function online to convert a pitch directly to a camera distance and use that. http://www.timotheegroleau.com/Flash/experiments/easing\_function\_generator.htm

I have this working and it ends up looking close but has two distinct problems. It is rigid and doesn't allow me to edit any of the offsets or distances without having to create a whole new function and the camera at 0 degrees pitch ends up being around 15-30% of the maximum distance which doesn't feel as good as if it were closer to 50%.

**Option B:**

Come up with a spline, perhaps a cubic bezier, between the min and max distances and somehow project the camera on to that spline given a specific pitch. I'm not sure how I would be able to do this. The disadvantages would be that the camera distance curve would not be as smooth without some tweaking and again it would require more work if any of the distances or offsets change.

**Option C:**

Come up with a specific formula which I have no idea how to find. Given the min and max camera distances, the offsets, and the camera pitch, return a distance that follows a smooth camera distance curve and a mid point of roughly 50% of the max distance.

So my question is can/how do I accomplish Option B or C? Is there a better way?

# Answer
> 1 votes
I would look into using an AnimationCurve for this. Add a curve to the script that controls your camera, then use the inspector to plot camera distance vs. pitch angle. (If the pitch has to go negative, I believe you'll have to offset it. No big deal!)

Now you can evaluate this curve (passing in pitch + offset) to get your camera distance out.

This will be quick to edit, and you should be able to fine-tune the curve while the game is running.

# Answer
> 0 votes
To make sure that I understand, what you're saying is that for option A: when you have the camera "flat" (pitch 0) it feels like it's too close to the player? If so... welcome to every third person game ever!

In all seriousness though, I think that you're maybe overthinking it. Why not take option A and then put a check in place for under/over certain pitch values and modify the distance slightly? What you'd essentially get is the typical 3rd person "bounce" when you go too high or low with the pitch.

I would also say that in the end most players prefer to manually set and adjust the camera distance themselves, making the auto-distance floating camera kind of a moot point. Obviously it needs to be functional, but I wouldn't worry about it being absolutely perfect because a lot of people won't use it.

---
Tags: unity, c#, camera, curves, third-person-view
---


title: How do I load an asset bundle?

text:
# Question
Title: How do I load an asset bundle?
I am trying to load a bunch of prefabs from an asset bundle. I am building the asset bundles for `StandaloneWindows64`:

```
BuildPipeline.BuildAssetBundles(BuildPath, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows64);

```

I load my asset bundle using Unity's new web request system:

```
var www = UnityWebRequest.GetAssetBundle(Url);
yield return www.Send();
if (www.isError)
{
    Debug.LogError(www.error);
    yield break;
}
var bundle = ((DownloadHandlerAssetBundle)www.downloadHandler).assetBundle;

```

However, my bundle does not have my asset bundle in it. It only has the manifest:

```
//Output:  "1 asset: bundlemanifest"
Debug.Log(bundle.GetAllAssetNames().Length + " asset: " + bundle.GetAllAssetNames()[0]);

```

If I look at my manifest, I can see my asset bundle names `"structures"` does exist:

```
ManifestFileVersion: 0
CRC: 3317959940
AssetBundleManifest:
  AssetBundleInfos:
    Info_0:
      Name: structures
      Dependencies: {}

```

I tried retrieving it from my AssetBundleManifest:

```
var manifest = bundle.LoadAsset<AssetBundleManifest>("assetbundlemanifest");

```

But the AssetBundleManifest only has functions which return `string`s and `Hash128`s.

How can I instantiate the prefabs in my asset bundle named "structures"?

# Answer
My URL required the name of the asset bundle at the end of it. I had the parent folder as my asset bundle's name, which loaded the Asset Bundle Manifest for some reason.
> 0 votes

---
Tags: unity, assets, streaming-assets
---


# Question
Title: Battle Simulation for Singleplayer/Online Hybrid Game
So I was playing Clash of Clans, and just wondered on how they authenticate the result of the battle.

This isn't exactly specific to Clash of Clans though. In my observation, while CoC is an online game. Their battle is just a singleplayer, but still I feel like the battle is verified somewhere in their server?

This would apply to games that are :

1. Singleplayer (no 2nd player to sync to).
2. Doesn't need constant communication to server during battle.
3. But the result still important and must be authenticated/verified.

My current guess is during/after a battle, the client app will send the inputs/actions of the player to the server. Then in server, the battle will be re-simulated again using the input/actions at a much faster time/pace.

For this to work, the battle has to be deterministic (unsure if that's the right word) so that same inputs/actions will produce the same result.

But if this is the "proper" way, then it would be really heavy on the server CPU's side isn't? even with scaling, I think.

I am leaning on this solution, but something doesn't feel right... there might be a better way...

That's why I came here today to consult for ideas/suggestions..

I'm thinking if there is a safe way to do the simulation/result on the client side? like encrypt the sensitive stuffs? is this even possible?

Thank you!

# Answer
> 0 votes
The general method would be to have the battles take place server side and simply have the clients relay the commands. Since CoC and similar types of games aren't like a competitive FPS that requires extremely low latency a little bit of delay to keep the clients synced would be no problem. Honestly, this is the only good way to do a real-time PvP game where the players aren't on a LAN.

The only other viable method (sort of) would be to use a deterministic battle system and a predetermined seed to simulate the battles. So when players join a battle the server would send a seed to each player so that they would each resolves actions the same way. The major flaw with that design is that each client would either have to wait for actions from the other player (slower than the server model) or they would run the risk of different outcomes based on the timing of commands.

edit: You could also use one of the clients as the "host" in place of the server, but you would still have to allow a delay for the commands from the opponent to be received with a time-stamp in order to resolve them properly (read: fairly) for both players.

---
Tags: client-server, authentication
---