# Question
Title: Is it a legal thing to do to sell fabricated accounts of your game?
For example, say I create an online mass multiplayer game with in-game purchasing system and with randomness factors as well (the point is that game accounts have actual value and there is a somehow proportional relationship with playing time plus the luck of the player and the account's value) and the game appears to become popular.

Is it legal to, for example, insert cheated accounts into the database (without even spend a second of legitimate playing) and sell those accounts with extremely high price?

# Answer
> 4 votes
Yes, there's nothing preventing you from selling anything you make in your own game (within reason). This is known as a pay-to-win scenario, which many players often complain about.

---
Tags: mmo, legal
---


# Question
Title: How to properly scale Image components to screen percentages?
Let's take a `Sprite`. I have two methods for retrieving an orthographic size of the screen:

```
public static float Width(){
    Camera cam = Camera.main;
    float height = 2f * cam.orthographicSize;
    float width = height * cam.aspect;
    return width;
}

public static float Height(){
    Camera cam = Camera.main;
    float height = 2f * cam.orthographicSize;
    return height;
}

```

Now, for the `Sprite`, I have an extension method:

```
public static void ScreenPercentWidth(this SpriteRenderer renderer, float percent){
    renderer.transform.localScale = new Vector3(
        Screen.Width() / 100f * percent / renderer.sprite.bounds.size.x,
        renderer.transform.localScale.y,
        renderer.transform.localScale.z
    );

}

```

Which I can use like `sprite.ScreenPercentWidth(50f)` and it works.

What about a `RectTransform`/`Image`? Is there any way that I could create similar methods, so I can scale the `Image` like in the above example?

# Answer
`Canvas` and `RectTransform` should do all the heavy lifting for you (more accurately, `CanvasScaler`). Usually, I set the UI Scale Mode on the canvas to Scale With Screen Size. You can define a "reference resolution" which is the screen size the UI layout and images are designed for.

To have a RectTransform take up half of the canvas's width, (assuming it is a direct child of the canvas) you would set the x value of the anchor properties in the inspector. To align it to the left edge of the canvas, set min x anchor to 0 and max to 0.5. To center it, set min to 0.25 and max to 0.75. After these are set, zero out the horizontal elements in the position section (x,width). Their names may have changed at this point though.
> 1 votes

---
Tags: unity, gui, transformation
---


# Question
Title: How to disable an object after it goes outside camera's viewport?
I have a gameobject at a certain position in the game. I want the gameobject to be disabled once it is outside the camera's viewport, and it should become visible only when the camera focuses at that position.

# Answer
Attach a script to the gameobject and implement the `OnBecameVisible` and `OnBecameInvisible`:

```
public class ExampleClass : MonoBehaviour
{
    void OnBecameInvisible()
    {
        Debug.Log("I'm not visible anymore");
    }

    void OnBecameVisible()
    {
        Debug.Log("Hey! I'm visible!");
    }
}

```

Keep in mind that, if you **disable** the gameobject, the renderers will be disabled too, and `OnBecameVisible` won't be called.
> 2 votes

# Answer
Camera.WorldToViewportPoint or WorldToScreenPoint is probably what you want. Disable the object if any coordinate if outside the "allowed" range (0-1 for viewport, 0-Screen.Width/Height for screen points). If the object is large, add a tolerance depending on size and distance.

Also, if you're just looking to improve performance, please note that frustum culling is handled by the engine by default.
> 1 votes

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


# Question
Title: Calculating the correct roll from a bone transform matrix
Read this forum topic for more info: http://blenderartists.org/forum/showthread.php?260602-transform-matrix-to-bone-%28head-tail-roll%29-bug

I'm trying to get my Blender3d modeller importer to create correct bones from my file's transform matrices.

The Blender Python API doesn't have a way to do this (anymore!), so people had to dig the Blender C source to find out how Blender does it and port that. Here's a Python port of the needed functions, not by me (I don't know C):

```
def vec_roll_to_mat3(vec, roll):
    target = mathutils.Vector((0,1,0))
    nor = vec.normalized()
    axis = target.cross(nor)
    if axis.dot(axis) > 0.0000000001: # this seems to be the problem for some bones, no idea how to fix
        axis.normalize()
        theta = target.angle(nor)
        bMatrix = mathutils.Matrix.Rotation(theta, 3, axis)
    else:
        updown = 1 if target.dot(nor) > 0 else -1
        bMatrix = mathutils.Matrix.Scale(updown, 3)
    rMatrix = mathutils.Matrix.Rotation(roll, 3, nor)
    mat = rMatrix * bMatrix
    return mat

def mat3_to_vec_roll(mat):
    vec = mat.col[1]
    vecmat = vec_roll_to_mat3(mat.col[1], 0)
    vecmatinv = vecmat.inverted()
    rollmat = vecmatinv * mat
    roll = math.atan2(rollmat[0][2], rollmat[2][2])
    return vec, roll

```

How to use them:

```
pos = mymatrix.to_translation()
axis, roll = mat3_to_vec_roll(mymatrix.to_3x3())

bone = armature.edit_bones.new('name')
bone.head = pos
bone.tail = pos + axis
bone.roll = roll

```

Sadly, it seems even the Blender C code is buggy and doesn't take into account cases when the bone is parallel to (0,1,0). So such bones can get assigned wrong (by 180 degrees) rolls and mess up animations.

Does anyone have better code for generating roll which takes into account such cases?

The old Blender 2.4 API generated correct ones. Its C code can be found here: http://svn.blender.org/svnroot/bf-blender/branches/blender-2.47/source/blender/blenkernel/intern/armature.c I'm no C coder myself, again.

# Answer
> 1 votes
For anyone looking for a solution to this problem, I'm posting this wherever I found it referred to. I have ported this newer upated internal C code of blender into python. I have not extensively tested it, but it seems correct, produces good results and it was super easy to port. It is used in the exact same way as before (see the above question), should be more accurate and get all (?) bone orientations right!

```
def vec_roll_to_mat3(vec, roll):
    #port of the updated C function from armature.c
    #https://developer.blender.org/T39470
    #note that C accesses columns first, so all matrix indices are swapped compared to the C version

    nor = vec.normalized()
    THETA_THRESHOLD_NEGY = 1.0e-9
    THETA_THRESHOLD_NEGY_CLOSE = 1.0e-5

    #create a 3x3 matrix
    bMatrix = mathutils.Matrix().to_3x3()

    theta = 1.0 + nor[1];

    if (theta > THETA_THRESHOLD_NEGY_CLOSE) or ((nor[0] or nor[2]) and theta > THETA_THRESHOLD_NEGY):

        bMatrix[1][0] = -nor[0];
        bMatrix[0][1] = nor[0];
        bMatrix[1][1] = nor[1];
        bMatrix[2][1] = nor[2];
        bMatrix[1][2] = -nor[2];
        if theta > THETA_THRESHOLD_NEGY_CLOSE:
            #If nor is far enough from -Y, apply the general case.
            bMatrix[0][0] = 1 - nor[0] * nor[0] / theta;
            bMatrix[2][2] = 1 - nor[2] * nor[2] / theta;
            bMatrix[0][2] = bMatrix[2][0] = -nor[0] * nor[2] / theta;

        else:
            #If nor is too close to -Y, apply the special case.
            theta = nor[0] * nor[0] + nor[2] * nor[2];
            bMatrix[0][0] = (nor[0] + nor[2]) * (nor[0] - nor[2]) / -theta;
            bMatrix[2][2] = -bMatrix[0][0];
            bMatrix[0][2] = bMatrix[2][0] = 2.0 * nor[0] * nor[2] / theta;

    else:
        #If nor is -Y, simple symmetry by Z axis.
        bMatrix = mathutils.Matrix().to_3x3()
        bMatrix[0][0] = bMatrix[1][1] = -1.0;

    #Make Roll matrix
    rMatrix = mathutils.Matrix.Rotation(roll, 3, nor)

    #Combine and output result
    mat = rMatrix * bMatrix
    return mat

def mat3_to_vec_roll(mat):
    #this hasn't changed
    vec = mat.col[1]
    vecmat = vec_roll_to_mat3(mat.col[1], 0)
    vecmatinv = vecmat.inverted()
    rollmat = vecmatinv * mat
    roll = math.atan2(rollmat[0][2], rollmat[2][2])
    return vec, roll

```

---
Tags: animation, matrix, python, blender, skeletal-animation
---


# Question
Title: libgdx - Image artifacts when downscaling image
Why does this border appear around the edges when I downscale a bitmap and how do I avoid it? I tried every filter I know, the results go from bad to worse.

Here's the original bitmap:

# Answer
> 1 votes
I don't know libgdx, but **the problem is with your image**. There are low opacity, white-ish pixels all around the edges of the Moon (ARGB is around `(1, 255, 255, 255)`)

It's important to be aware of the fact that all pixels in an image have R, G and B values, even the ones where alpha is zero, and they might cause artifacts during sampling. There is a detailed article on this here: article.

---
Tags: textures, libgdx, sprites, scale
---


# Question
Title: Does Unity's Microphone functionality support stereo input?
The documentation for the Microphone class in Unity does not indicate whether Unity supports stereo recording. Does Unity support recording stereo audio from a compatible microphone? It looks like several people have asked this on Unity's Q&A website, but no one has ever answered.

*I understand that most microphones are mono and gaming headsets never have stereo microphones, but stereo microphones do exist. It's just not clear whether Unity supports stereo input.*

# Answer
> 3 votes
Now that I've had a chance to hook up a stereo mic and try this out, I've found that `Microphone.Start()` always returns a single-channel AudioClip, even if the selected microphone is capable of stereo (at least on Windows).

---
Tags: unity
---


# Question
Title: How to make snake movement smooth not grid based like slither.io snake?
I try to find the right formula to mimic the smooth non-grid movement of the slither.io snake.

I can do it manually to save each point the "head" movement went and do some interpolation in between its body parts but it is very error prone.

Also I find this: http://www.emanueleferonato.com/2014/06/10/html5-string-avoider-game-made-with-phaser/

Which is not working in my case but do show something similar

Here is a picture to express what I want to do:

Any idea how to do it right?

# Answer
> 1 votes
Well... I actually don't know what you're calling "grid based" movement but to reproduce the slither.io's movement you might need to:

Save the current snake moving angle

make a vector that is equal to (cursor position - snake position) and calculate its angle

Calcuate the difference beetween the two angles and increment the snake's moving angle by a little portion of it every tick.

Done ;)

\[EDIT\]Here's an exemple:

your snake spawns looking to the top, at position x=100, y=100, his moving angle is currently pi/2

the player mouse cursor is at x=150, y=250

the angle formed is : angleFormed = atan2((150 - 100)/ (250 - 100)) in radians

you move the snake angle depending on the difference with the other angle :

snakeAngle += (angleFormed - snakeAngle) / timeStep

# Answer
> 0 votes
This might be useful for you!

ok, so let positions\[\] be a vector array with the current positions of the snake.

to move the snake (or the snake's head) to a new position, this is what i did for my game

```
moveTo (x, y) {
  // positions[0] is the head of the snake
  this.positions[0].x = x;
  this.positions[0].y = y;

  this.join();
}

join () {
  // loop through each position
  for (let i = 1; i < this.positions.length; i++) {
    // get last and current position
    const last = this.positions[i - 1];
    const curr = this.positions[i];

    // get difference in x and y of each position
    const dx = curr.x - last.x;
    const dy = curr.y - last.y;

    // calculate the angle between the two parts of the snake
    let angle = Math.atan2(dy, dx);

    // get the new x and new y using polar coordinates
    const nx = 2 * this.radius * Math.cos(angle);
    const ny = 2 * this.radius * Math.sin(angle);

    // add the new x and new y to the last snake's position to "join" the two together without a gap
    curr.x = nx + last.x;
    curr.y = ny + last.y;
  }
}

```

Basically, this the moveTo() function just moves the head to the new position, and the join() function joins all of the parts together smoothly with a *wiggly* animation

a jsfiddle is here: https://jsfiddle.net/rzx9hmro/1/

---
Tags: 2d, movement, snake
---


# Question
Title: interchanging the positions within 5 objects coordinate in opengl
I have drawn 5 squares with different coordinates in opengl...and now what I want to do is to interchange the positions of those 5 square coordinates within itself ...for example: if I click the blue square it should move on to red position (blue to red) similarly red to pink, pink to white, white to blue. can anyone help me please!!! THANKS IN ADVANCE

can you help us with any formula to be used to interchange the above explained positions....or with any source code to do such operation.

# Answer
Ok, so first of all, you'll have to write some kind of collision detection with cursor that can identify what square you are clicking on.

I'm not sure if I understand, do you want one square to be moved on top of the stack when drawn, or move in position?

Now, there are a couple ways to determine which object gets drawn on top of another. You could, when giving each object coordinates, have them drawn based on their z value by enabling the depth testing.

If you want to move the object, the simplest way, is also kinda complex. You need to deal with matrices. https://learnopengl.com/#!Getting-started/Transformations gives a pretty good example of them, and the following tutorial gives a bunch of example code. It's ok, if you don't fully grasp the math, as there are plenty of math libraries that will do the hard work for you.
> 1 votes

---
Tags: opengl
---


# Question
Title: Getting Components to their respective System in Entity-Component Engine
I asked this question in stackoverflow, but I didn't get any responses. I think it's better suited in this exchange.

I'm building a game engine of sorts (purely educational) and am not sure the best way to keep a large system decoupled when using objects the are shared by systems.

My engine is making use of an entity-component design where components contain only state. Systems are the driving force of making these components run so I need to be able to register components with their respective system. I am just unsure on how to pass the components through the hierarchy which looks like this:

I can think of a few ways of dealing with this.

**Option 1: Singleton.** If I make my Engine object a singleton I can use static methods directly in my input component to bind to the input system.

```
class InputComponent: public Component
{
    InputComponent()
    {
        Engine::getEngine()->getInputSystem()->bindInputComponent( this );
    }

    virtual ~InputComponent()
    {
        Engine::getEngine()->getInputSystem()->unbindInputComponent( this );
    }
}

```

This has the benefit of components automatically binding and unbinding themselves to their system which is convenient. It has the downfall of being a singleton (not necessarily bad, but it can possibly make my engine inflexible in the future) and my InputComponent "knows" about the InputSystem which might be bad design.

**Option 2: Work down from scene system.** I can make my scene system responsible for binding and unbinding components.

```
class SceneSystem: public System
{
    void setActiveScene( Scene* scene )
    {
        // Deactivate (and unset components) for the current scene.
        unsetActiveScene();

        for( auto i : scene->getEntities() )
        {
            for( auto j : i->getAllComponents<InputComponent>() )
            {
                // Send message through mediator to bind the component
                DataMessage<InputComponent*> bindMessage( MESSAGE_BIND_INPUT_COMPONENT, j );
                Message response;
                sendMessage( &bindMessage, &response, SYSTEM_INPUT );
            }
        }
    }
}

```

In this way the input component isn't worried about looking up the hierarchy. But now my scene system has to "know" about input components (and all other components that need to be registered). This is coupling my system.

Also if I need to add/delete components I'll need to do it through the scene system.

**Option 3: Working up from input component.** The last thing I can imagine is to instead work my way up the hierarchy from the input component. I think in this scenario I would also add a general `bindComponent` to the scene system so not too much complexity about the mediator messaging creeps into my components.

```
class SceneSystem: public System
{
    template <typename T>
    void bindComponent( T* component, int system )
    {
        DataMessage<T*> bindMessage( MESSAGE_BIND_COMPONENT, component );
        Message response;
        sendMessage( &bindMessage, &response, system);
    }
}

class InputComponent: public Component
{
public:
    InputComponent( Entity* parentEntity ) : m_parentEntity( parentEntity )
    {
        m_parentEntity->getParentScene()->getSceneSystem()->bindComponent<InputComponent>( this, SYSTEM_INPUT );
    }

    virtual ~InputComponent()
    {
        m_parentEntity->getParentScene()->getSceneSystem()->unbindComponent<InputComponent>( this, SYSTEM_INPUT );
    }

private:
    Entity* m_parentEntity;
}

```

This has the effect of my hierarchy being bidirectional (not sure if this is a bad thing)

Of these options, which is better for keeping such a system flexible and reasonably decoupled. Also point out other options especially if there are flaws with my current design and/or understanding of the problem.

# Answer
> This has the benefit of components automatically binding and unbinding themselves to their system which is convenient. It has the downfall of being a singleton (not necessarily bad, but it can possibly make my engine inflexible in the future) and my InputComponent "knows" about the InputSystem which might be bad design.

Overall, there isn't a real problem with the actual base *engine* being a singleton as there is often objects and memory allocation you want to do once, regardless how many things internally you want running concurrently.

The flexibility concerns you speak can be easily resolved by a good design between the engine instance itself and its internal components. One approach to this is to use some context like object that is meant to represent the engine's global state.

```
InputComponent(Context* context)
{
    context->GetSystem<InputSystem>()->BindComponent( this );
}

```

> In this way the input component isn't worried about looking up the hierarchy. But now my scene system has to "know" about input components (and all other components that need to be registered). This is coupling my system.

There will inevitability be some coupling, but I agree I am not fond of this approach. I think I'd instead rather consider some callback mechanism if you want to work from the scene perspective.

1. Create an entity attached to a given scene.
2. Create component data classes and attach them to a given entity instance.
3. Activate entity, triggering a series of callbacks and system registrations.

The basis for the concept here is that an entity is basically non-existent from a systems perspective until it has been activated. Once an entity is activated, you would generally not be able to change its component list unless you deactivate it, modify, and reactivate it.

```
void Entity::Activate()
{
  for( System* system : GetScene()->GetSystems() )
    system->OnEntityActivated( this );
}

```

The idea is that the systems query the entity and determine based on the components that exist if the entity should be registered with that system. If not, the system does nothing. If so, the system adds that entity to some internal data structure for update-loop iteration.

Overall your design seems fine to me.

If it were me however, I tend to use my latter suggestion because it avoids tight coupling and allows for a flexible design with a minimal contract between the scene and systems.
> 1 votes

# Answer
I watched a tutorial a while back on a Game engine design around SFML on youtube that has since became my design cornerstone: https://www.youtube.com/watch?v=tgXEws1Ef8s&list=PLRtjMdoYXLf4md1jeCkdPJYpDgPkjT9Di

In it, they use a state machine to express their hierarchy. There is one struct object that gets passed around between states as they are each in turn loaded. States being treated like their own game individually... the splash screen might have a state, the main menu being one, gameplay being one, pause menu being one, etc. Each state either being paused or destroyed when another one is added. The way this works between states is that each state is responsible for calling another and in turn can pass along data as well.
> -2 votes

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


# Question
Title: How to make gameObjects in Unity move in predefined patterns easily
I am trying to make a bullet hell game. I want my 2D enemies to move in predefined, curving patterns. How should I do this?

The difficulty I have is being able to quickly produce enemy movements that are

(A) predefined, not random

(B) curved

(C) easy to make, with little coding

(D) visually able to see what is going on, maybe in the inspector?

Perhaps a 3rd party tool may be warranted?

# Answer
> 1 votes
Since you've asked for a solution that involves little coding, I'd suggest using linked prefabs. The idea is to build a "library" of simple maneuvers and then chain them.
Pseudocode below, followed by an explanation:

"Move" class to represent a single maneuver:

```
public Vector2 velocity;
public float angularVelocity;
public float duration;

void execute(float stepSize, Transform avatar) {
  //move avatar, e.g. avatar.Translate(avatar.forward * velocity * stepSize);
  //rotate avatar
}

```

"MoveSet" class to represent an enemy's course:

```
public Vector2 spawnOffset; //optional, but if you need this, best put it here
public Move[] moves;
private int currentMove = 0;
private float moveTime;

bool execute(float stepSize, Transform avatar) {
  moves[currentMove].execute(stepSize, avatar);
  moveTime += stepSize;
  if (moveTime >= moves[currentMove].duration) {
    currentMove += 1;
    moveTime = 0;
    if (currentMove >= moves.Length)
      return true; //move set finished - repeat set or despawn enemy etc.
  }
  return false;
}

```

In your enemy class, add a public MoveSet variable and call

```
myMoveSet.execute(time.fixedDeltaTime, gameObject.transform)

```

from FixedUpdate.

In your Move's and MoveSet's OnDrawGizmosSelected, call execute in a loop with a suitable step size and e.g. a Debug.DrawLine(lastPosition, transform.position) call after each step. Reset position after the loop.

How you'd use this:

1. Create empty GameObject, add "Move" script. The editor should draw an approximation of the path. Fine tune variables until you're satisfied, then save as prefab.
2. After you have a few "Move" prefabs, create a GameObject with a "MoveSet" component, drag "Move" prefabs into the array until you're satisfied with the course, then save as prefab as well.
3. Drag a "MoveSet" onto an enemy or assign at runtime. Spawn an instance of the "MoveSet" prefab before using it.

You'll probably have to expand this a little to suit your project, perhaps apply forces to a Rigidbody instead of moving directly, tweaking performance etc, but this should give you an idea of where to start.

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


# Question
Title: Calculating t value to use with Hermite interpolation
I'm developing an FPS in Unity using Photon for networking. The Photon-provided interpolation is very basic so I decided to roll out my own using the Hermite spline.

It works good and is significantly better than the provided interpolation. However, I was wondering what's the correct way to choose the t value. In a perfect world, it should be incremented by deltaTime\*timeBetweenPositionUpdates. However, that doesn't work since even if the tickRate is set to 10 for example, sometimes the client sends it at 9.5, and then at 10.2 and so on and so forth. This means that we can't have a constant increment rate for the t value since it'll either lag behind or move too fast and we'll run out of buffered frames. What I decided to do is to send the time between frame updates as well and interpolate using that. But, this also isn't perfect by any stretch of the imagination and the receiving client will soon lag very much behind.

What I'm doing now is using a multiplier on the t value such that if there is more frames in the buffer than we want to have then it'll speed the interpolation up, and if there's less than how many we want in the buffer then it'll slow the interpolation down. This works pretty well, but it's a hack I believe.

Is there a better way, or a proper way to do this?

# Answer
> 1 votes
It depends on what you want. It's always a trade-off between having to wait occasionally or having a longer lag. You can trade one against the other (by specifying your desired optimal buffer size).

In order to adapt to variable incoming frame rates you can either output variable frame rates or adapt the interpolation interval. You do the latter and if this is indeed what you want, I would not regard it as a hack but rather as a feature.

Also it makes sense to slow the interpolation down, when the buffer gets empty and speed it up when the buffer is full. You might define a correction that somehow scales with the difference of the current buffer size and the desired buffer size. This difference is what you want to keep minimal.

This is also known as a control-feedback-loop. In order to work efficiently, a feedback loop should react fast enough to changes in the control variable but not too fast or you'll get wildly oscillating buffer sizes. The general idea is to increase the reaction speed until overshooting appears, then reduce the sensitivity again. An additional integral part (sum of control variable values for a certain time interval) might even help more. See also: PID controller

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


title: Nothing gets rendered in SceneKit

text:
# Question
Title: Nothing gets rendered in SceneKit
I have this code in OpenGL:

```
Vuforia::Matrix44F modelViewProjection;

VuforiaApplicationUtils::translatePoseMatrix(0.0f, 0.0f, self.scale, &Vuforia::modelViewMatrix.data[0]);
VuforiaApplicationUtils::scalePoseMatrix(self.scale, self.scale, self.scale, &Vuforia::modelViewMatrix.data[0]);
VuforiaApplicationUtils::multiplyMatrix(&projectionMatrix.data[0], &Vuforia::modelViewMatrix.data[0], &modelViewProjection.data[0]);

```

And the `modelViewProjection` gets used like this:

```
glUniformMatrix4fv(mvpMatrixHandle, 1, GL_FALSE, (const GLfloat*)&modelViewProjection.data[0]);

```

With `mvpMatrixHandle` being a piece of code in the shader:

```
mvpMatrixHandle = glGetUniformLocation(shaderProgramID, "modelViewProjectionMatrix");

```

And in the shader itself:

```
gl_Position = modelViewProjectionMatrix * vertexPosition;

```

Now I try to convert this to SceneKit code (never used it before, so I might miss a big part of my SceneKit code)

```
// Setup
let plane = SCNNode(mdlObject: MDLAsset(url: Bundle.main.url(forResource: "Bubble", withExtension: "obj")!).object(at: 0))
scene.rootNode.addChildNode(plane)

let camera = SCNCamera()
plane.camera = camera

// Each frame
modelViewMatrix = SCNMatrix4Translate(modelViewMatrix, 0, 0, scale)
modelViewMatrix = SCNMatrix4Scale(modelViewMatrix, scale, scale, scale)
let modelViewProjection = SCNMatrix4Mult(arrayToMatrix(pose: projectionMatrix), modelViewMatrix)

//camera.projectionTransform = modelViewProjection
scene.rootNode.childNodes[0].transform = modelViewProjection

```

As you can see, I have also tried to set this as the `projectionTransform` of the camera, but that did not work either.

My result is the most annoying to debug: nothing gets rendered using the SceneKit code, while the OpenGL code works.

# Answer
I am not using Vuforia but ARToolkit and I had the same kind of issue. The main solution is to realize that SceneKit is a graph of nodes, therefore applying a modelViewProjection to a node transform may not may so much sense. The node with the camera is your view.

Instead, you should apply your projectionMatrix to the SCNCamera's projectionTransform property, and apply your modelView/view matrix to a different childNode that contains your "AR" scene.

That's for a context with an SCNCamera that you can control, not in an ARSCNView (ARKit) where the ARCamera updates as you move your device.

Hope this helps.
> 1 votes

---
Tags: opengl, scenekit
---


title: How to animate clouds in a plane?

text:
# Question
Title: How to animate clouds in a plane?
I'm building a top-down strategy 2D game, and i'm stuck animating clouds that will float above the arena, hiding other elements. The effect i want to achieve is something exactly like this:

How would i go about implementing it in Unity3D?

# Answer
> 1 votes
Most fog of war solutions, probably including the one shown, are shader based. Without knowing much about your project, this is a typical solution in a nutshell:

1. Create an opaque plane above your map that looks like shadow/fog/clouds or whatever you want to use to obscure what's below. Can be as fancy as you like.
2. Write a shader that expands the one you were using for the plane but calculates transparency from e.g. a texture passed to it.
3. Create and update the texture via script and pass it to the shader.

If that approach sounds suitable, this should be a good starting point.

If your game is, like the example, based on a hex (or other non-rectangular) grid, an easier solution might be to create the cloud cover for each cell as a separate object, with a shader using absolute instead of relative texture coordinates so the cells connect and tile seamlessly. This would reduce aliasing at the edges of the concealed area, but might create too much overhead if you have a lot of cells.

PS: Hope I understood your question correctly. If you're just looking for how to make the texture scroll, using Material.SetTextureOffset should suffice in your case. The example you posted looks like it has a semitransparent cloud texture on top of an opaque one, scrolling at different speeds.

---
Tags: unity, animation, clouds
---


# Question
Title: Flicking geometries with OpenGL in Qt app
I have a Qt (5.9.1) app that on Windows many of the geometries I'm drawing flickers. My problem description is vague because I'm at a complete loss.

Does anyone know if there's an issue with flickering on Windows with OpenGL (I think Qt uses ANGLE for OpenGL) that would be different than in Linux? My app on Linux seems to work perfectly.

Specifically, my app draws LIDAR ground points (`GL_POINTS`), and boxes around objects (`GL_LINES`), and range marker circles (`GL_LINE_LOOP`). These are all drawn to the same context. I also set up double buffering. All the rendering takes place on a render thread. This is done in the style of Scene Graph - Rendering FBOs in a thread (so, no Qt3D)

When the app starts, initially it seems fine, but after a couple seconds, different geometries, say, the boxes around objects, and/or the range marker circles, start flickering. Although they're all on the same context, all of the same geometries (say the range markers) will flicker at the same rate (independent of the other geometry types), or all the boxes.

While this is happening, my measured FPS does slow down, but the flickering still occurs even when the FPS is up at 58+. I've even inserted some `glFlush()`es and `glFinish()`es - no impact (either on FPS or flickering.) **UPDATE** I must have made a mistake when testing `glFinish()` or something changed, because now `glFinish()` removes the flicking (and kills my FPS.)

The structure of my renderers is that I have one class that sets up the viewports, calls `glClear`, and then invokes `render()` on each renderer. Those renderers have a buffer setup with vertex array buffers, I set some uniforms, and call `glDrawArrays`. I don't think I'm doing anything unconventional. e.g.

```
opengl_safety_buffer_.bind();

glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

QOpenGLVertexArrayObject::Binder vaoBinder(&safety_vao_);
render_safety_program_->bind();

glLineWidth(safety_ranges_config_["lineWidth"].value<GLfloat>());
render_safety_program_->setUniformValue("col", vcol_);

glUniformMatrix4fv(render_safety_program_->uniformLocation("mvp"), static_cast<GLsizei>(mvp_matrices_.size()), GL_TRUE, reinterpret_cast<GLfloat*>(&(mvp_matrices_[0])));
glDrawArrays(GL_LINE_LOOP, 0, opengl_safety_buffer_.CountVertices());

glDisable(GL_BLEND);

render_safety_program_->release();
opengl_safety_buffer_.release();

```

My vertex and fragment shaders are very simple.

I don't have great profiling data right now, but the little I do have shows that all my renderers combined don't take even half of the 1/60s time per frame I need.

The flickering started when I moved away from using a Scene Graph Under QML mixed with Qt3D, towards the threaded FBO example - so I figure there's nothing intrisic in my geometries that should be causing the flickering.

## UPDATE

Posting my top level render code. Basically I have a loop that calls all my individual renderers sequentially, all on the same thread and on the same context.

Top level render code:

```
// ...

render_fbo_->bind();

// Clear
context_->functions()->glClearColor(0.039f, 0.055f, 0.10f, 1.0f);
context_->functions()->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

// Render only the faces closest to you
context_->functions()->glEnable(GL_DEPTH_TEST);
context_->functions()->glDepthMask(GL_TRUE);

{
    // Configure out viewport (x,y, width, height)
    unsigned int i = 0;
    foreach (const auto v, scene_graph_->viewports())
    {
        // Make sure that the viewports cameras are updated
        v->camera()->calculatePosition();

        auto vs = v->paddedRect();
        context_->versionFunctions<QOpenGLFunctions_4_3_Core>()->glViewportIndexedf(i, vs.x(), vs.y(), vs.width(), vs.height());
        i++;
    }
}

foreach (const auto model, scene_graph_->models())
{
    if (model->isDirty())
    {
        model->renderer()->synchronize(model);
        model->dataSynced();
    }
    model->renderer()->render();
}

// Reset OpenGL state
context_->functions()->glDisable(GL_DEPTH_TEST);

// We need to flush the contents to the FBO before posting
// the texture to the other thread, otherwise, we might
// get unexpected results.
context_->functions()->glFlush();

// FPS
recalculateFPS();

render_fbo_->bindDefault();
render_fbo_.swap(display_fbo_);

emit textureReady(display_fbo_->texture(), size_);

```

When I include `glFlush` `glFinish()` after `model->renderer()->render()`, I can see that some of my renders, specially my `GroundRenderer` is taking waay too much time (the black line represents the amx time for 1 frame):

So, my goal now is to figure out why `GroundRenderer` takes so much time. It basically just writes to a large circular buffer. I'm not experienced enough yet though to know what "*large*" is, but I haven't really observed a sensitivity to the specific size of the buffer (I cut it's size by a few orders of magnitude, and didn't see any real difference.)

# Answer
The problem is that my renders are taking too long, which is "*solved*" with a `glFinish()`. My understanding however is that `glFinish()` should only be used to debug, so this is not a solution, but it does point me in a better direction to ultimately solving my problem. (and tells me that my profiling attempts wasn't working as well as I thought.)

I've left this question up in case any one else experiences similar issues to me, but I want this answer to "close" this question as the question is pretty vague and I have a new direction to pursue.
> 1 votes

---
Tags: opengl, glsl, multithreading, qt
---


# Question
Title: Changing alignment within a vertical layout group
I have a vertical layout group that has text bubbles instantiated into it. Instantiating them always aligns them to "lower middle". However, I'd like to have them on opposite sides for a message app effect.

Right now, I'm changing the anchoredPositions of each instantiated UI object in Update. Is there any better way of doing this?

# Answer
> 0 votes
Create a wrapper RectTransform around each bubble which takes up the full width, with a `HorizontalLayoutGroup` component. Set the Child Alignment on the left-side messages to Middle Left, and on the right-side messages to Middle Right. So your hierarchy looks like this

```
|-ChatMessages (VerticalLayoutGroup, Child Alignment = Lower Center)
|----LeftMessage (HorizontalLayoutGroup, Child Aligment = Middle Left)
|--------Message (Text, Image, Whatever)
|----RightMessage (HorizontalLayoutGroup, Child Aligment = Middle Right)
|--------Message (Text, Image, Whatever)
|----LeftMessage (HorizontalLayoutGroup, Child Aligment = Middle Left)
|--------Message (Text, Image, Whatever)
|----RightMessage (HorizontalLayoutGroup, Child Alignment = Middle Right)
|--------Message (Text, Image, Whatever)

```

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


title: Viewport for pixelart (WebGL)

text:
# Question
Title: Viewport for pixelart (WebGL)
I'm trying to display `16x16` pixel art textures (all textures have `16x16`), but they are not displayed how I expected (they are kind of blurry). I have seen this question before question, but this was not answering my question.

My approach:

I use the `resize` from this url webglfundamentals

Which means my `canvas` has the following properties :

* `width:100vw`
* `height:100vh`

Then I set my `viewport` to:

* `gl.viewport(0,0,gl.canvas.width, gl.canvas.height)`

For the `sprite rendering` I use a `orthographic camera`:

* `function ortho(out, 0, gl.canvas.width, 0, gl.canvas.height, 0, 1)` (from glmatrix)

The sprite I'am trying to display consists of this vertices :

* `new Float32Array([-0.5, -0.5, 0.0, 0.5, -0.5, 0.0, -0.5, 0.5, 0.0, 0.5, 0.5, 0.0]);`

which means it is very small, so I scaled them up. I understand that my original texture has only the size `16x16` and when I scale it up it gets stretched. So my question is how would you setup the `viewport` and why? **(Also an explanation would be nice, since I have the feeling I did not quite understand the connection between `viewport`, `orthographic camera` and `width and height of the canvas`)**.

# Answer
It's not a problem with the canvas. The textures get blurry because of the max filter parameter. You can set it with the texParameterf function:

```
gl.texParameterf(texture, gl.TEXTURE_MAG_FILTER, gl.NEAREST)

```

If you instead want to make the viewport smaller (the size of the display in pixels), then you need to use gl.viewport with the desired width and height of the canvas.
> 2 votes

---
Tags: textures, webgl, resolution
---


# Question
Title: LWJGL—How to Animate Sprites from a Sprite Sheet Using Certain Keys?
I'm talking here about walking animations and such for a 16-bit RPG. I have a simple sprite sheet that contains walking animations for all directions (up, left, down, and right), but I'm having trouble getting LWJGL to animate them—how would I do it?

# Answer
> 0 votes
The answer is posted here. Knowledge regarding shaders in LWJGL is required.

---
Tags: java, 2d, lwjgl, rpg
---


# Question
Title: Raycast does not detect child layer if parent layer is set to ignore
* I have a `LineRenderer` that ignores certain Layers based on a `Raycast` using `LayerMask`.
* I have a cube with a collider on a Layer which is ignored because of the `LayerMask`.
* I have a smaller object *inside* the cube that is a child object of the cube and is on a layer that is not set to be ignored. I need the Raycast to **hit the smaller object.**

When this smaller object is un-parented from the larger cube, the LineRenderer behaves like I want it to: the `hit` data informs me it is being hit by the `Raycast`, but this does not hold true if the smaller object is a *child of the cube*.

Is there a way of having this behaviour without having to un-parent the smaller object? It's like the smaller object is inheriting the parent's Layer, despite being on it's own Layer - does this sound like what is happening?

# Answer
The Raycast was actually hitting the child object but returning data for the parent object. It is possible however to return information about the child by accessing the *collider that was hit* (that of the child object).

So to access the child collider:

```
hit.collider.transform

```

instead of just:

```
hit.transform.

```

You can then access the `gameObject`, `transform` or whatever from the collider.

From the Unity docs for RaycastHit.
> 2 votes

---
Tags: unity, c#, raycasting, layers
---


# Question
Title: Algorithm to determine all hexagons within an arc from a starting hexagon
I have a game engine which handles hexagon based war games and things like LOS, etc, for both flat and tip up hexes. A particular game I'm implementing at the moment, Band of Brothers, has facing for vehicles and, optionally, for infantry.

I've searched the web and have not found any algorithm to handle determining the hexagons that fall within an arc expanding out from a hexagon. Here are some pictures to describe what I'm talking about:

I represent the hexagon locations as offset coordinates, and have the values for all the dimensions of each hexagon and the endpoints of the vertices and center in relation to the overall map stored as doubles. I also convert to cube coordinates for determining distance.

Just looking for ideas or pointers on how I might determine these hexagons.

EDIT: I do not have a rep \> 10 so I can't add a picture of offset coordinates. There is a good one here on gamedev though. Here's an ASCII art representation of it. The numbers will be a little different depending on which row is indented:

```
0,0   1,0   2,0   3,0   4,0
   0,1   1.1   2.1   3.1
0,2   1,2   2,2   3,2   4,2

```

# Answer
> 1 votes
If your range is limited, you can enumerate all the hexagons in each category, assuming the unit is facing north and is located at 0,0. Then use hex rotation (in cube coordinates) to match the direction. And use hex addition to move the coordinates to the unit's location.

By explicitly enumerating the hexes, you can have arbitrary shapes, such as being able to fire on side positions only when 2 ≤ distance ≤ 4, or having the range depend on the angle. I put a demo here.

If you have unlimited range, I think atan2 is probably the simplest thing. Use hex subtraction (in cube/axial coordinates) and then convert that to x,y and use atan2.

---
Tags: hexagonal-grid
---


# Question
Title: Combinations for tiling two textures together
Hi I need to create seamless ground with grass and dirt. I can make two textures connect seamlessly one to another. My question is how to figure out all the combinations, like (left, top, bottom, left-bottom, right-botton-left and so on)? Is there some kind of guide? Thank you in advance.

# Answer
> 36 votes
There's a solid overview of different popular tile combination patterns put together by Boris the Brave, building on some earlier work by Sean Howard.

I'll briefly summarize the main categories these authors identify in case the links break in future, along with a few additions of my own. I recommend you read the original articles for the full details.

## Rug

(16 tiles)

Draws rectangular boxes of various sizes, but can't do concave shapes. Often used for UI message boxes or cliff faces in RPG tilesets.

If you use just the top-right 3x3 section, it's commonly called a "**9-Slice**" - you lose the ability to form shapes smaller than 2x2 tiles though.

## Fence

(16 tiles)

Draws ribbons and networks of tiles connected along their shared edges.

Both Rug and Fence are examples of Wang Tiles with two edge types, they just differ in whether the corners are counted as "inside" or "outside"

## Marching Squares

or
(16 tiles, +2 optional alternate diagonal tiles)

You may also see this style called Corner Tiles \- they're the equivalent of Wang Tiles with matched corners instead of matched edges. In another answer I show how this layout can be extended to three different corner textures.

## Inside/Outside

(14 tiles)

I see this subset of Marching Squares without the diagonals fairly frequently, but I haven't found an officially accepted name for it, so I mocked up the example above using Boris's tiles. Alexandre Vaillancourt's example in the other answer is another layout of this pattern.

## The Blob

(48 tiles)

This tileset covers an exhaustive collection of corner and edge states, where a foreground corner is always bounded by two foreground edges, but a foreground edge is allowed to slip between two background corners.

Caeles and others at OpenGameArt have investigated various ways of packing tilesets similar to this one \- you can find several "blob" templates there.

## Sub-Blob

(5 tile-equivalents: 20 quarter-tile pieces that can be assembled into full tiles)

Surprisingly, you can make all 47 non-blank (all-background) tile combinations in "the Blob" with just these 20 corner pieces, assembled in different combinations.

This is used in RPG Maker VX's autotiles and other autotiling systems to cut down on the amount of unique texturing needed to flexibly cover a wide array of shapes.

Note that the quarter-tile split puts some restrictions on how much you can bevel the corners, sometimes leading to a more blocky appearance than when using full tiles, as illustrated by Felix Trapper here:

## Extended Autotile

(11 tile-equivalents: same 20 quarter-tiles as Sub-Blob, plus 4 dedicated corner tiles and some redundancy)

Here I'm borrowing the name given to this by the Rotorz tile system. It's also the style used by RPG Maker XP. The extra corner tiles can support a wider turning radius, or a diagonal split between foreground & background, which can help a map look more organic. Note that this particular layout includes some redundant sub-tiles (shown darkened above).

---

Here's a table summarizing what you get with each of the combinations:

```
                    9-Slice   Rug    Fence    M.S.   I/O    Blob   S.Blob  Ex.A
Tile equivalents        9     16      16      16      14     48       5     11
...with all-blank      +1     +1      +1     incl    incl   incl     +1     +1
Smallest foreground     2      1       1       2       2      1       1      1
Concave corners         N      N       Y       Y       Y      Y       Y      Y
Foreground diagonals    N      N       Y       Y       N      Y       Y      Y
Background diagonals    N      N       N       N       N      N       N      N

```

---
Tags: 2d, textures, tiles
---


# Question
Title: Fixed distance increments between two Vector3 positions
I have two Vector3 positions:

```
 Vector3 start = new Vector3(1f, 1f, 1f);
 Vector3 target = new Vector3(5f, 5f, 5f);

```

How do I transform gameobjects a fixed amount from start to target, say .1f?

This is easily done with percentages, because you can do:

```
var dist = target - start;
 var d = 5f; // 5 increments
 var step = dist / d;

 while (start != target) {
     start += step;
 }

```

How do you do this with Fixed, not percentage steps. Say I want to increment .1f in some direction:

```
 var dist = target - start;
 var step = new Vector3(.1f, .1f, .1f); //How do I determine the direction of the increment?

 while (start != target) {
      start += step;
  }

```

Thanks

# Answer
It's really simple: You already have the difference between target and start in the dist variable. Just normalize that vector3, multiply it by the step distance and then you can add it.

```
start += dist.normalized * stepDist

```

Note: The code will most likely loop forever. You should probably check the distance before adding the step.

```
float d = dist.magnitude;
if (d<stepDist)
    start = target;
else
    start += dist.normalized * stepDist

```
> 0 votes

---
Tags: unity, mathematics, transformation
---


# Question
Title: IOS very simple 2d engine/api rendering showdown
So after taking some time running through a course, I believe I have enough experience with referring back to the course how to make the game I wish to all apart from one thing. How to draw the game on screen, I know how the game would work behind the screen, but don't know how to draw it. I'm looking for an experienced, informed answer based upon certain factors.

To provide some context, the game in question's interface would be very simple:

* Grid of lines
* Control each cell's content: (text and colour)
* Pan and zoom

The game at the minute is based upon an excel spreadsheet as shown to show how simple it is:

My aim to keep this question open to others is to create a pros and cons of each.

I've narrowed down possibilities to this list. These are taken from the apple developer page under the section 'Graphics and Games':

* Core Animation
* Core Graphics
* GLKit
* Metal
* OpenGL ES
* cocoas 2d?
* Other Noteworthy

I'm asking for an informed opinion as to which I should choose. This is narrowed down from research, however I assume I will have missed things that may make this task much easier. My problem thus far is that most games assumed I needed sprites but in something this simple I'm assuming I don't.

If it makes any difference, my current knowledge is only swift, high school math and hopeful abundance of learning resources. I've been stuck with this problem for a long time and I would be overjoyed if I could get some experienced advice. Thanks! :)

# Answer
> 0 votes
The options provided are unsuitable to the task you've described. Apple has created a framework that works very, very well for 2-dimensional games called SpriteKit

To be precise:

Core Animation and Core Graphics are lower level than you need. These are more suitable to a single simple task that cannot be easily reproduced by sprites, like a simple painting app.

GLKit, Metal, and OpenGL are far more complex and flexible than is needed. They require much more expertise than would ever be expected or reasonable for a game/engine of this scope. These systems allow for very complex graphical feats and would be more appropriate for detailed, resource-intensive 3D games, custom shaders, and the like.

SpriteKit, however, is designed to be a high-level, simple-to-use sprite-based framework. For the engine you described, you would not even need any "sprite" resources, as the entire engine seems to be nothing more than squares and text. The entirety would be renderable (size, color, and text) with no outside resources, yet would remain extensible should you desire to add custom sprite functionality at a later point. The "camera" controls would be simple in SpriteKit, while the squares, color, and text would be trivial.

# Answer
> 0 votes
Given what you've provided, I would probably just do it with CoreGraphics. Learning OpenGL or Metal is a big task. (You should do it eventually, but learn simpler stuff first.) You can easily draw the board and update it when moves are made. You can make a view that's as large as you need and only draw what's been revealed as panning happens and it should be performant enough for your needs as described here.

If you keep the drawing separated from logic of the game you can always throw out the drawing and replace it with something better as you learn other technologies.

---
Tags: 2d, rendering, ios, opengl-es2, metal
---


# Question
Title: Pressing the jump button also makes my character fire their weapon
In my game I want my player jump without firing their weapon, but when I press the button it jumps and also fires too in same moment.

In this Update method, I used Input.GetButton so my player will fire continuously while holding the button.

```
void Start () {
    isJumped = true;
}

// Update is called once per frame
void Update(){
    if (!transform.GetChild (0).gameObject.GetComponent<PlayerHealth> ().hasDied) {

        if (Input.GetButton ("Fire1") && Time.time > firespeed && isJumped == true) {
                nextFire = myTime + firespeed;
                newProjectile = Instantiate (projectile, transform.position, transform.rotation) as GameObject;
                nextFire = nextFire - myTime;
                myTime = 0.0F;
                //  EnergyCharging ();
            }
        }
    }

void JumpButton(){
if(!transform.GetChild(0).gameObject.GetComponent<PlayerHealth>().hasDied){
        if (grounded) {
            grounded = true;
            myRigidBody.AddForce (new Vector2 (0, jumpPower), ForceMode2D.Impulse);
            if(myRigidBody.velocity.y > jumpPower){
                myRigidBody.velocity = new Vector2 (0, jumpPower);
            }
            animator.SetBool ("isGrounded", grounded);
        }
    }
}

```

# Answer
> 1 votes
Here is a checklist of things to check:

1. Does the game use the same button for jumping and attacking ? I don't see the code that looks if the player has pressed the jump button anywhere.
2. Is "isJumped" turned false at any point by something ? In the code you provided it doesn't. And what's the point of a "isJumped" bool, if the Jump method doesn't change it ?
3. According to the code you provided, if "isJumped" isn't changed elsewhere, it will always be true, and the player will always be able to attack, even if he is jumping.

P.S. In the "JumpButton()" method you check if grounded is true, and if it is you turn it to true... It already is true because if it weren't, it wouldn't pass the 'if'. So it's useless to assign this bool to true right after the 'if', because it's going to be true anyway.

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


# Question
Title: Player animating the wrong direction once he is rotated
I have used the scripting root motion move the player when using an 'inplace' animation.

All works correctly until the players rotation is off 0,0,0. This is expected as the movement is along the transform.z axis but how can I account for the rotation in the script and apply it so the movement is correct in game?

The gorillacontroller script is the script we are trying to fix On playerGorilla. animator is on the playergorilla. The gorilla1 is the gameobject holding the mesh and the bones for the character.

I will also add the transforms are moving this was my silly mistake because I had tool handles in global instead of local.

This makes it even more confusing however because all tranform.z (blue axis) are facing the correct way for the animation to work but the animation is only ever playing in the original direction where the rotation is 0,0,0,0.

```
using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Animator))]

public class RootMotionScript : MonoBehaviour {

    void OnAnimatorMove()
    {
          Animator animator = GetComponent<Animator>();

          if (animator)
          {
               Vector3 newPosition = transform.position;
               newPosition.z += animator.GetFloat("Runspeed") * Time.deltaTime;
               transform.position = newPosition;
          }
    }
}

```

# Answer
> 1 votes
You can use transform.forward to get the local z-axis(blue) direction converted in world space. So you can just do

```
transform.position += transorm.forward * animator.GetFloat("Runspeed") * Time.deltaTime

```

Make sure you get the forward property on the right gameobject (it depends on your models and animations, usually is the root gameobject or the skeleton parent)

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


# Question
Title: Similarities and Differences between LWJGL and Android OpenGL?
So, since I’ve been working a lot with LWJGL recently, I’ve come to learn that Android has native OpenGL support. So, what does this mean for me? Is OpenGL handled the same way it is in LWJGL? What’re the larger differences between the two?

# Answer
Because OpenGL is a completely separate entity, most of the stuff is the same, but there are some differences.

There are no separate classes for different version (like GL20, GL11, etc.), everything is in the same package.

As with LWJGL, you'll need to use buffers to put data into VBOs, but you can also pass these to the draw methods without creating any type of storage for them (like the above mentioned VBOs), but this is a "hey, you can do this" type of difference, and because it's very slow, you shouldn't rely on it.

Creating the context is probably the biggest difference. You can't use GLFW. Instead you'll need to fiddle a bit with the built in GLSurfaceView.

All in all, the differences aren't huge and usually only apply to the way you call the methods, the order of things you need to do is largely the same, so you'll get familiar with it pretty quickly by just reading a tutorial on it.
> 3 votes

---
Tags: opengl, java, android
---


# Question
Title: Doing an SNES Mode 7 (affine transform) effect in pygame
Is there such a thing as a short answer on how to do a Mode 7 / mario kart type effect in pygame?

I have googled extensively, all the docs I can come up with are dozens of pages in other languages (asm, c) with lots of strange-looking equations and such.

Ideally, I would like to find something explained more in English than in mathematical terms.

I can use PIL or pygame to manipulate the image/texture, or whatever else is necessary.

I would really like to achieve a mode 7 effect in pygame, but I seem close to my wit's end. Help would be greatly appreciated. Any and all resources or explanations you can provide would be fantastic, even if they're not as simple as I'd like them to be.

If I can figure it out, I'll write a definitive how to do mode 7 for newbies page.

edit: mode 7 doc: http://www.coranac.com/tonc/text/mode7.htm

# Answer
**Mode 7** is a very simple effect. It projects a 2D x/y texture (or tiles) to some floor/ceiling. Old SNES use hardware to do this, but modern computers are so powerful that you can do this realtime (and no need of ASM as you mention).

Basic 3D math formula to project a 3D point (x, y, z) to a 2D point (x, y) is:

```
x' = x / z;
y' = y / z;

```

When you think about it, it makes sense. Objects that are far in the distance are smaller than objects near you. Think about railroad tracks going to nowhere:

If we look back at the formula's input values: `x` and `y` will be the current pixel we are processing, and `z` will be distance information about how far the point is. To understand what `z` should be, look at the picture, it shows `z` values for image above:

> purple = near distance, red = far away

So in this example, `z` value is `y - horizon` (assuming `(x:0, y:0)` is at the center of screen)

If we put everything together, it becomes: (pseudocode)

```
for (y = -yres/2 ; y < yres/2 ; y++)
  for (x = -xres/2 ; x < xres/2 ; x++)
  {
     horizon = 20; //adjust if needed
     fov = 200;

     px = x;
     py = fov;
     pz = y + horizon;

     //projection
     sx = px / pz;
     sy = py / pz;

     scaling = 100; //adjust if needed, depends of texture size
     color = get2DTexture(sx * scaling, sy * scaling);

     //put (color) at (x, y) on screen
     ...
  }

```

One last thing: if you want to make a Mario Kart game, I suppose you also want to rotate the map. Well it's also very easy: rotate `sx` and `sy` before getting the texture value. Here is the formula:

```
  x' = x * cos(angle) - y * sin(angle);
  y' = x * sin(angle) + y * cos(angle);

```

and if you want to move through the map, just add some offset before getting the texture value:

```
  get2DTexture(sx * scaling + xOffset, sy * scaling + yOffset);

```

NOTE: I tested the algorithm (almost copy-paste) and it works. Here is the example: http://glslsandbox.com/e#26532.3 (requires recent browser and WebGL enabled)

NOTE2: I used simple math because you said you want something simple (and don't seems familiar with vector math). You can achieve the same things using the Wikipedia formula or tutorials you give. The way they did it is much more complex but you have much more possibilities for configuring the effect (in the end it works the same...).

For more information, I suggest reading this Wikipedia article about perspective projection.
> 50 votes

# Answer
Here is the code to make it. I is the same code of the tutorial that I made on my blog. Check there to learn the Mode 7 method and the RayCasting.

Basically, the pseudo code is it:

```
//This is the pseudo-code to generate the basic mode7

for each y in the view do
    y' <- y / z
    for each x in the view do
        x' <- x / z
        put x',y' texture pixel value in x,y view pixel
    end for
    z <- z + 1
end for

```

Here is the code that I made in JAVA, following my tutorial.

```
package mode7;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;

/**
 * Mode 7 - Basic Implementation
 * This code will map a texture to create a pseudo-3d perspective.
 * This is an infinite render mode. The texture will be repeated without bounds.
 * @author VINICIUS
 */
public class BasicModeSeven {

    //Sizes
    public static final int WIDTH = 800;
    public static final int WIDTH_CENTER = WIDTH/2;
    public static final int HEIGHT = 600;
    public static final int HEIGHT_CENTER = HEIGHT/2;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {

        //Create Frame
        JFrame frame = new JFrame("Mode 7");
        frame.setSize(WIDTH, HEIGHT);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        //Create Buffered Images:
        //image - This is the image that will be printed in the render view
        //texture - This is the image that will be mapped to the render view
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        BufferedImage texture = ImageIO.read(new File("src/mode7/texture.png"));

        //The new coords that will be used to get the pixel on the texture
        double _x, _y;

        //z - the incrementable variable that beggins at -300 and go to 300, because
        //the depth will be in the center of the HEIGHT
        double z =  HEIGHT_CENTER * -1;

        //Scales just to control de scale of the printed pixel. It is not necessary
        double scaleX = 16.0;
        double scaleY = 16.0;

        //Mode 7 - loop (Left Top to Down)
        for(int y = 0; y < HEIGHT; y++){

            _y = y / z; //The new _y coord generated
            if(_y < 0)_y *= -1; //Control the _y because the z starting with a negative number
            _y *= scaleY; //Increase the size using scale
            _y %= texture.getHeight(); //Repeat the pixel avoiding get texture out of bounds

            for(int x = 0; x < WIDTH; x++){

                _x = (WIDTH_CENTER - x) / z; //The new _x coord generated
                if(_x < 0)_x *= -1; //Control the _x to dont be negative
                _x *= scaleX; //Increase the size using scale
                _x %= texture.getWidth(); //Repeat the pixel avoiding get texture out of bounds

                //Set x,y of the view image with the _x,_y pixel in the texture
                image.setRGB(x, y, texture.getRGB((int)_x, (int)_y));
            }

            //Increment depth
            z++;
        }

        //Loop to render the generated image
        while(true){
            frame.getGraphics().drawImage(image, 0, 0, null);
        }
    }
}

```

The result is:
> 4 votes

---
Tags: pygame
---


title: Get next tile by given angle

text:
# Question
Title: Get next tile by given angle
I am new to game development, and I have been building some game with LibGDX engine.

*The following function might make you feel bad*

The function I am going to show, is accepting the current rotation index of my player (player has 4 rotations, north, south, west, east). The function will return how much to jump in X to get the next tile according to his direction (angle) and the selected move (you can only select left, right or forward per turn):

```
public int getIncrementXForRotation(int rotationIndex) {
    switch(this) {
        case MOVE_FORWARD:
            switch(rotationIndex) {
                case Face.EAST:
                    return 1;
                case Face.SOUTH:
                    return 0;
                case Face.WEST:
                    return -1;
                case Face.NORTH:
                    return 0;
            }
        case MOVE_BACKWARD:
            switch(rotationIndex) {
                case Face.EAST:
                    return -1;
                case Face.SOUTH:
                    return 0;
                case Face.WEST:
                    return 1;
                case Face.NORTH:
                    return 0;
            }
        case MOVE_LEFT:
            switch (rotationIndex) {
                case Face.EAST:
                    return 0;
                case Face.SOUTH:
                    return 1;
                case Face.WEST:
                    return 0;
                case Face.NORTH:
                    return -1;
            }
        case MOVE_RIGHT:
            switch (rotationIndex) {
                case Face.EAST:
                    return 0;
                case Face.SOUTH:
                    return -1;
                case Face.WEST:
                    return 0;
                case Face.NORTH:
                    return 1;
            }
        case TURN_LEFT:
            switch(rotationIndex) {
                case Face.EAST:
                case Face.SOUTH:
                    return 1;
                case Face.WEST:
                case Face.NORTH:
                    return -1;
            }

        case TURN_RIGHT:
            switch(rotationIndex) {
                case Face.NORTH:
                case Face.EAST:
                    return 1;
                case Face.WEST:
                case Face.SOUTH:
                    return -1;
            }
    }
    return 0;
}

```

Same function for `Y`.

Now I looked at this, and i thought to myself.. north can be an `0`, and east can be `90`, and south can be `180` and west can be `270`, am I right?

So there is a way to mathematically do these coordinate increment according to the angle, isn't there?

```
The reason I classified my player angles by `enums` is because each direction is an image.

```

# Answer
> 1 votes
Yes, you can do it with angles. However it's also easy to do it with a table. The main idea is to be consistent with directions, using 0, 1, 2, 3 in either clockwise or counterclockwise order. That way you can add directions together to represent rotations.

With tables:

```
int dx[4] = [1, 0, -1, 0];
int dy[4] = [0, 1, 0, -1];

public int getIncrementXForRotation(int rotationIndex) {
    /* let's assume your enum is
        MOVE_FORWARD = 0, MOVE_RIGHT = 1, MOVE_BACKWARD = 2, MOVE_LEFT = 3
        and FACE_EAST = 0, FACE_SOUTH = 1, FACE_WEST = 2, FACE_NORTH = 3
     */
    int dir = (int(move_direction) + rotationIndex) % 4;
    return dx[dir];
}

```

With angles, if 0 = east, 1 = south, 2 = west, 3 = north, you can use `dx = Math.cos(direction * Math.PI/2)`, `dy = Math.sin(direction * Math.PI/2)`.

Depending on the orientation of your axes, you may have to flip the y direction (use `-Math.sin` instead of `Math.sin`).

---
Tags: libgdx, mathematics
---


title: 2d Collision detection libgdx

text:
# Question
Title: 2d Collision detection libgdx
**The Logic**

The player which is a cube (32 by 32 pixels) checks if their is a cell next to it that has the name Wall. (This is done using a tileset).

To do this collision check I made four checks in this order:

* Is their a wall under the player.
* Is their a wall to the left of the player.
* Is their a wall to the right of the player.
* Is their a wall above the player.

If the player for example touches the wall to the left of him The x coordinates of the player are set to the tile right of the wall(cell) that was collided with.

**The Problem**

If for example I move the player left, the loop will first check for a collision under the player however this makes the player move up if their is a wall to the left of the player which he is touching. (Note: it doesn't always do this only if the player moved enough pixels to the left). The player should have just stopped moving to the left. Moving up was not desired.

**Experiments**

I tried adding the left and right check for collision first. This way the bottom check should not see the cell. This made the player teleport to the left and right of the cell the player was currently on because gravity has time now to drag the player down enough pixels. (The player is always affected by gravity and I rather not change this for it wouldn't make sense for an entity like the player to not be affected by it).

Making the movement speed of the player smaller. This did have an affect which was more desired but the players movement speed should not be effected at all as a fix.

**The Code**

**Collision detection code**

```
    // Floor collision
    if (map.isWall(xCoordinates, yCoordinates - 1) || map.isWall(xCoordinates + 31, yCoordinates - 1))
        yCoordinates = ((int)(yCoordinates / 32) * 32) + 32;

    // Left collision
    if (map.isWall(xCoordinates - 1, yCoordinates) || map.isWall(xCoordinates - 1, yCoordinates + 32)) {
        xCoordinates = ((int)((xCoordinates - 1) / 32) * 32) + 32;
        canMoveLeft = false;
    } else
        canMoveLeft = true;

    // Right collision
    if (map.isWall(xCoordinates + 32, yCoordinates) || map.isWall(xCoordinates + 32, yCoordinates + 32)) {
        xCoordinates = ((int)(xCoordinates / 32) * 32);
        canMoveRight = false;
    } else
        canMoveRight = true;

    // Roof collision
    if (map.isWall(xCoordinates, yCoordinates + 32) || map.isWall(xCoordinates + 31, yCoordinates + 32)) {
        canGoUp = false;
    }

```

**The isWall function**

```
public Cell getCellByPixel(float cellPositionX, float cellPositionY) {

    if (cellPositionX >= 0 && cellPositionY >= 0)
        if (tileid.getCell((int)cellPositionX / 32, (int)cellPositionY / 32) != null)
            return tileid.getCell((int)cellPositionX / 32, (int)cellPositionY / 32 );

    return null;
}

private TiledMapTile getTileByPixel(float cellPositionX, float cellPositionY) {
    if (getCellByPixel(cellPositionX, cellPositionY) != null)
        if (getCellByPixel(cellPositionX, cellPositionY).getTile() != null)
            return getCellByPixel(cellPositionX, cellPositionY).getTile();

    return null;
}

// Check if the cell has a tile with the property of Wall. We can see this in the tsx file.
public boolean isWall(float cellPositionX, float cellPositionY) {
    if (getTileByPixel(cellPositionX, cellPositionY) != null)
        if (getTileByPixel(cellPositionX, cellPositionY).getProperties().get("Wall") != null)
            return true;

    return false;
}

```

**Player movement**

```
private void Movement() {
    if (canMoveLeft)
        if (Gdx.input.isKeyPressed(Keys.A) || Gdx.input.isKeyPressed(Keys.LEFT))
            xCoordinates -= (playerMovementSpeed * Gdx.graphics.getDeltaTime());

    if (canMoveRight)
        if (Gdx.input.isKeyPressed(Keys.D) || Gdx.input.isKeyPressed(Keys.RIGHT))
            xCoordinates += (playerMovementSpeed * Gdx.graphics.getDeltaTime());
}

```

# Answer
# A different approach for collision resolution

Good question, your workflow seems to be the: (1) move the player, (2) check if the player is inside a wall, and (3) try to push the player out of the wall if he is inside of it.

A possible issue here, is that once you are inside of a wall, you're never really sure where to push the player to. Furthermore, really fast-moving objects (such as bullets) might be able to jump through walls altogether (e.g. if your wall is 32px wide, and the bullet is traveling 128px per frame).

A different approach could be the following: (1) check if there is a wall where the player *would* be placed, (2.A) if there is no wall, move the player, or (2.B) if there is a wall, don't move the player.

This resolves the first issue, where to put the player when he ends up inside a wall. However, we can still move through walls if the player is moving too fast. Additionally, the player won't stop right next to the wall. E.g. if the player is moving 8px per frame, and he is 4px away from the wall, he will stop right there (as he would end up inside the wall), whereas you actually want him to stop right next to the wall at a 0px distance.

# Poor man's approach to pixel perfect collisions

A simple way to resolve this issue that works on walls of any shape (even slanted ones) is to perform multiple collision checks. E.g. if your player object is moving at 8px per frame, instead of collision checking one 8px movement, you would check 8 1px movements. This way the player could decide to make 4 1px movements, until he is snug against the wall, and not perform the next 4 1px movements. In terms of code, you would be replacing this:

```
if (CollisionAt(player.x + 8, player.y) == false) {
  player.x += 8;
}

```

by this:

```
for(int i = 0; i < 8; i++) {
  if (CollisionAt(player.x + 1, player.y) == false) {
    player.x += 1;
  }
}

```

Obviously, once you hit the wall, you can stop your for-loop as all succeeding collision checks will yield a collision:

```
for(int i = 0; i < 8; i++) {
  if (CollisionAt(player.x + 1, player.y) == false) {
    player.x += 1;
  } else {
    break;
  }
}

```

Additionally, you probably want both horizontal and vertical movement. You could simply perform those in succession, which means collision checking is performed in an L-shape (similar to the movement of a knight in chess). Usually this is a fine approximation for true diagonal movement. Let's say your velocity vector is composed of `velocityX` and `velocityY`, the code becomes:

```
for(int i = 0; i < velocityX; i++) {
  if (CollisionAt(player.x + sign(velocityX), player.y) == false) {
    player.x += sign(velocityX);
  } else {
    break;
  }
}
for(int i = 0; i < velocityY; i++) {
  if (CollisionAt(player.x, player.y + sign(velocityY)) == false) {
    player.y += sign(velocityY);
  } else {
    break;
  }
}

```

where the `sign(x)` function is `1` for a positive `x` and `-1` for a negative `x`. The above approach resolves the problem of jumping through walls when moving too fast, as all intermediate positions are checked. Additionally, it also makes your character stop right next to walls. Even better, your character wil even stop snug to corners when performing diagonal movement, similar to "wall sliding" in FPS games.

# A possible improvement

The above is a "poor-man's approach" however, as it becomes more computationally expensive the faster your player moves. Unless your game contains thousands of player characters, you are probably just fine.

A more optimized approach would be to use mathematical equations to find the collision-points for various kinds of geometry in one shot. For example, the problem of finding the collision point between two rectangles, where one is traveling along a defined movement vector can be solved in one equation. Many equations exist for various shapes and purposes. I personally read Collision Detection in Interactive 3D Environments by Gino van den Bergen and found it a great resource for the mathematics behind collision detection. If you search for "collision detection/resolution" or "physics engine development" you'll find a lot of nice alternatives.

Using these equations, your movement codes becomes something along the lines of:

```
float closestCollision = inf;
for(Wall wall : allWallsInTheGame) {
  float t = FindEntryPoint(player, wall, velocityVector);
  if (t < closestCollision) {
    closestCollision = t;
  }
}
player.position += t * velocityVector;

```

Where `FindEntryPoint()` caculates how far you can move along the velocity vector before hitting an object. If it returns `0`, it means you are instantly hitting a wall, if it returns `1` it means you can travel over the full vector.

This is a lot faster, as you are only iterating over all walls once, rather then once for every 1px movement. After all, the `CollisionAt()` function in the poor man's solution has to iterate over all walls as well.

# Solution to your problem

To summarize all of the above: a simple approach would be to make multiple small 1px movements. Rather then trying to solve the problem when the player ends up inside a wall, you could check *before* making the move. This approach is fine, but definitely not optimized. For an optimized solution you want to use one-shot equations for finding collision entry points.
> 5 votes

---
Tags: java, libgdx, collision-detection
---


# Question
Title: What's the best way to train PID controllers?
This is borderline non-gamedev but PIDs are commonly used in games so I thought I'd give it a shot.

I've got a few PID controllers in my game, used for things like steering and throttle control. I'm having trouble tuning them accurately. It never feels like I'm getting closer to the optimial solution, and it's very tempting to just leave them "good enough" with the odd oscillation or spike I can't get rid of.

The one controller that's driven me to this post with frustration produces minor oscillations for very very small error inputs. At large inputs it's ok but not very stable.

Does anyone have any tips or resources on how I can train these things more reliably?

# Answer
There's actually a decent article in AI Game Programming Wisdom 2 by Euan Forrester regarding PID Controllers.

I'll just reiterate what he said about tuning the different coefficients:

1. ***Start with the proportional coefficient (P)*** \- This has the largest effect on the behaviour of the controller. Set the other 2 coeffs to 0 and tune P until you get a rough desired effect.
2. ***Only vary one coefficient at a time*** \- Get a decent feel for one coefficient to make sure it does approximately what it does while keeping the other 2 constant.
3. ***Tune the coefficients in real time*** \- The benefits are a bit obvious really. You don't want to recompile everything every time you make a change to a value, that's just common coding sense.
4. ***(Optional) Have an instant replay feature in place*** \- This will just help in case you observe something really weird happening with your PID values so you can replay the steps up until that point.

He also offers a number of online resources (some of which are dead links so I'll only post the ones that are still available):

Visual Loop Tuning

Tuning a PID Temperature Controller

Hope that helps

~Ray
> 8 votes

# Answer
For starters, Wikipedia actually has a good article on how to begin tuning. Without more details it's hard to go into more detail in a response.
> 2 votes

# Answer
Recent #AltDevBlogADay article describes PID controllers quite nicely, and the WebGL example on author's site can be useful for fine-tuning the variables.
> 2 votes

# Answer
**Don't tune pids using the simplistic "trial and error" method!** You will never get good results because parameters depend on each other. Use FOPDT (first order plus dead time) model together with IMC formulas to calculate Kp, Ki and Kd from test data.

Do a step test on your control signal (directly towards the "plant" without controller) and record your process variable that you are trying to control as it relates to the control signal. Then look at the data and note down process gain, deadtime and process time. (more info here and here).

Generally just read through the whole ControlGuru site. It is a very good resource. I have used the FOPDT model quite successfully to just get the right pid values instantly without any trial and error. It works great and produces an optimal controller. When you then compute your Kp, Ki and Kd from Kp, Ti and Td you also have an option to specify "aggressiveness" value which is a good way to just tell your already properly tuned controller how fast it should converge.

Also you should probably use derivative on PV instead of derivative on error. There is really no point in most cases to do derivative on error. To do this you use negative sign before Kd and use this formula:

This avoids an effect called "derivative kick" when you change your setpoint. More info here.

I never tune manually anymore at all. I think FOPDT model is the simplest method there is to tune PID loops very quickly. You also have to distinguish though between self regulating (self-stabilizing) process and an integrating process (which does not stabilize - such as a position of an object after a force has been applied to it). The tuning methods are a bit different but also are described at the controlguru site here.
> 2 votes

---
Tags: controllers
---


# Question
Title: Why are there so few games compiled for 64-bit processors?
I noticed that I could not find any game that has a native 64-bit version on the x86 platform (there are some for platforms, obviously for example the Nintendo 64). In fact when I asked if the Allegro library supported 64-bit, the developers had no idea. When I tried to compile something for 64-bit my compiler failed (it was MingW, it wrote that 64-bit is not implemented).

This this make me wonder: why?

At least if the issue was 32-bit-only machines, you could make two `.exe`s and run the more appropriate one or something. But I haven't even seen that, so why does nobody make 64-bit games?

# Answer
> 7 votes
Not enough of the gamer market is running a 64-bit OS. If your game was 64-bit only, it may not run on a number of customers' machines, giving both lost sales and increased support/return costs. This is likely the #1 reason, though that's conjecture on my part. Once the Steam hardware survey indicates that \>90% of users are running a 64-bit OS, more games are likely to start being 64-bit only.

If your game has 32-bit support, you probably have no benefit to also QAing and delivering a 64-bit copy. There are some moddable games like Bethesda's that could definitely use a 64-bit version for people who like to add more content, but those are a rarity.

There's also the argument of speed. 64-bit AMD64 has a lot of speed benefits over 32-bit IA32, but it has a disadvantage in pointer sizes. For some apps, 64-bit builds are actually slower or use too much additional memory. A game engine may or may not have these problems, depending on design, and so a 64-bit version may not be a good idea for that engine.

A lot of engines out there simply don't support compiling in 64-bit and it's not seen as a worthwhile use of time/money to fix. One big engine I've worked with recently for instance has all kinds of 64-bit-unclean issues; since the game barely tops 1GB of memory usage, there's really just no incentive to spend the time it would take to fix up just yet.

The new console generation and the increasing pressure on visual fidelity will likely push games to 64-bit before too much longer. We're just not there quite yet.

# Answer
> 1 votes
Not just about market, but about need, where is the need ? 64 bits is good when you need more than 3GB (for windows), or 4GB (for mac) in main RAM. Many games are texture and render targets heavy so its about space in the graphics card rather than the RAM, and the graphic cards addressing is handled by driver, it may be whatever, 32 bits, 48 bits who knows, anyway you've got to limit yourself to something reasonably in the range of the target hardware space. 1 GB ~ for desktops, ~100MB for mobiles...

# Answer
> 0 votes
AAA games these days do come out with 64bit executables. For example Fallout 4 is 64bit.

The most important question one should be asking is this: Does the game **needs** to be 64bit ?

The important difference of a 64bit game is that it can use more RAM than a 32 bit game. There is also the additional benefit that 64 bit variables (for example decimal type) are processed faster because they are not cut in half, but this kind of variable rarely is used in video games, it's mostly used for money calculation in bank software etc.

So if a game doesn't really need a 64bit executable, why should it have one ? Remember that 64bit software can't run on 32bit operating system. So there is no need to make a game available for less people if the game doesn't really need the more RAM.

As for the "bit wars" of consoles of the past, it was all a marketing trick, and the number of bits was referring to different things in different consoles.

For the NES, SNES, and Sega Genesis the 'bits' (8, 16, 16) were referring to the color depth capability of the GPU. Playstation 1's 32 bits were referring to the actual processor, and N64's 64 bits were referring to the bus bandwidth of the GPU.

The processors and the games of consoles have been running on 32bits from the console generation of PS1 and N64 up to the generation of XBOX360 and PS3. Only in the latest generation of XBOX1 and PS4 the CPUs and games of consoles made the jump to 64bit computing.

---
Tags: marketing
---


# Question
Title: How do I make a 2D World Political map in unreal engine 4?
Can someone explain the basics of making a 2D World map in unreal engine 4 (e.g. similar to the ones used in Plague inc., age of civilizations, etc.)

I've seen it being done in unity, but couldn't find any similar content in unreal engine 4...

Thank you.

# Answer
> 2 votes
I'm going to speak in language agnostic terms because I don't know Unreal Engine 4.

The most obvious way I imagine it to be is you have 2 images. In one of them, you draw the map with all the regions colored in a unique color each. This is the hidden image. In the other, you actually draw what will be displayed to the player, lining up the regions with the hidden image.

Then you keep a dictionary of colors, mapping each color that appears in your hidden image to a certain province name or province object.

You do this so that you can take the position of the mouse pointer relative to the top-left corner of the image you display, check which color the pixel in that position in the hidden image is, and go to the dictionary to find which province the player selected.

---
Tags: maps, unreal-4, grid, blueprints
---


title: Preferred way to render text in OpenGL

text:
# Question
Title: Preferred way to render text in OpenGL
I'm about to pick up computer graphics once again for an university project. For a previous project I used a library called FTGL that didn't leave me quite satisfied as it felt kind of heavy (I tried lots of rendering techniques, text rendering didn't scale very well).

My question is, is there a good and **efficient** library for this? If not, what would be the way to implement fast but nice looking text? Some intended uses are:

* Floating object/character labels
* Dialogues
* Menus
* HUD

EDIT: Preferably it could also load fonts

# Answer
A popular framework is Crazy Eddie's GUI.

But whilst that is appealing, its not unusual to roll your own (and perhaps regret it as the scope increases later ;))

Its normal to have your glyphs on bitmaps and then draw the bitmaps using OpenGL.

Sometimes you show transient text that might only appear for a handful of frames. Just using GL\_QUADS+glVertex will be sufficient. But for any large quantity of text or any long duration of visibility its well worth putting the GL\_QUADS in a VBO - I've noticed big performance improvements from this.

There is of course the question of generating the actual glyphs that you need. There are programs like bmfont that you can use for that. Or you might need rather more complicated rendering, e.g. freetype on demand. I've been using bmfont with my own renderer quite happily, its very straightforward to deduce.
> 4 votes

# Answer
There are a lot of ways - depending on what you want... Like everywhere else, there isn't something like "the best solution". Which plattform is your target? Which language are you using? What is about text resizing/rotation - is it necessary? Do you need to be able to render TrueTypeFonts? Whats about Multilanguage/Unicode? How do you want to store your text (which encoding etc.)?

I used in the past also FTGL, as well as pure freetype (http://www.freetype.org/ FTGL is based on this), different kind of bitmap fonts, outline fonts... Now I'm mostly addicted to bitmap fonts, but thats only my personal preference. Because I dont want to deal with different charsets, encoding and stuff like that anymore - and licensing for bitmapfonts is also easilier and cheaper than for TrueTypeFonts. And its usable on every plattform that can load images. I use simply an quad in openGL and map a part of my texture on it. The other side is: The font will be only clean resizable at a factor about +/-50%. If you can live with that, I would suggest using a bitmapfont.

If you have also to deal with different encoding/charsets you should find a way to load and use TrueTypeFonts (like with freetype, using another library or with your own implemenation)...

Also have an look at nehes different tutorials on this topic:

http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=13 Bitmap Fonts

http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=14 Outline Fonts

http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=15 Texture Mapped Outline Fonts

http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=17 2D Texture Font

Good luck!
> 9 votes

# Answer
If you want to use bitmap fonts, you can't go far wrong with the Angelcode Bitmap Font Generator: http://www.angelcode.com/products/bmfont/

It converts a truetype font to one or more textures (with nicely packed glyphs), and outputs a little file containing the UVs and spacings (I find that the XML output is particularly easy to work with, and the quality of the spacing data is generally very good, even without true kerning)
> 6 votes

# Answer
I'm using the libraries of Sean Barret to render truetype-glyphs under OpenGL (stb\_image, stb\_truetype).

The Recast/Detour-project is using these libraries to create an user interface (IMUI)
> 1 votes

# Answer
Consider QML. It's a fully functional UI library with an easy to use syntax. Its feature set is significantly better than CEGUI in my experience, and it has better documentation, support and community since its primary target is desktop applications and the ability to render offscreen is just sort of a bonus.

Pros:

* It uses OpenGL on the back end for all rendering
* It can load any font available to the host system and can also parse additional fonts you include as resources
* It uses signed distance field text rendering for efficient and high quality output
* It can render directly to an OpenGL texture, so you can place the results in your game environment easily
* Qt has lots of language bindings

Cons:

* Qt is a big framework
* Using QML in Direct3D or Vulkan projects requires jumping through hoops to get the GL texture into the appropriate API (or waiting for someone to write native D3D / Vulkan renderers for QML)
* There are still some minor quirks in QML where it will try to use a native control even if you're rendering to an offscreen surface, like when you try to open up a dropdown for a list item.
> 0 votes

---
Tags: textures, rendering, performance, fonts, text
---


title: Turn a spaceship at a max rate

text:
# Question
Title: Turn a spaceship at a max rate
Using the following to turn a spaceship in a C# FarseerPhysics simulation.

```
 var turnPower = _Inventory.EngineTurnPower * time;
 body.ApplyTorque(turnPower);

```

If the user keeps holding in the turn key the ship will go into a superspeed turn och chaos were it eventually is impossible to tell which direction it is facing.

What would be some good way of limiting the turn speed that the user can cause, without limiting the simulation itself.

# Answer
There's no friction in space so what is happening is actually the proper realistic behaviour: The ship spins faster and faster.

If you want to limit rotation speed you can use Body.AngularDamping to add friction or clamp Body.AngularVelocity or both.

Adding friction/damping will reduce acceleration gradually.

Clamping velocity will put a hard limit on the speed and effectively cut acceleration to zero instantly.
> 4 votes

---
Tags: c#, box2d, farseer-physics-engine
---


# Question
Title: cube collider losing shape upon rotation
I'm not sure what's going on here. I have a cube which I have turned into a rectangle; it's a child of a plane which is the "ground" so that they share rotation (this is a pinball table).

To create these cubes, I just used the create =\> 3d shape =\> cube/plane option. No packages are used.

The issue is when I rotate the rectangle, the collider visibly becomes wrong.

This is before rotation:

This is after rotating on the y axis:

The collider *does* seem to rotate, but not at the correct amount. Can anyone shed some light as to what's going on here?

Here's the inspector and hierarchy:

I also tried making the plane a cube, it didn't change anything.

# Answer
> 1 votes
It seems like the issue is that I cannot change the rotation on a child object when applying a scale to the parent.

In other words, when inheriting scale, don't use rotation.

I'm not exactly sure why this is the case but here's my takeaway. Apply the scale to the object which is being rotated, not to its parent.

---
Tags: unity
---


# Question
Title: How can I draw the "cone of view" of a camera in a flat 2D minimap?
I have a 3D world with some model in it (the XZ-plane grid, some gray boxes and a red box). In the upper-left corner I'm trying to draw a *minimap* that should represents the whole world in 2D (flat). As you can see I already achieved to draw the grid and the boxes just using their scaled position. With the same logic I drew the camera too so here's my question: how can I draw the "cone" of view for this camera? In the image below I just drew a green shape that should explain what I mean better than words (obviously the green one in the image doesn't represent the actual view for this camera, it's just an example).

I'm using LibGDX with a PerspectiveCamera so I got access to all the camera information like the *fow*, the *frustum* and so on. Any idea how to implement this?

# Answer
> 2 votes
> I'm using LibGDX with a PerspectiveCamera so I got access to all the camera information like the fow, the frustum and so on. Any idea how to implement this?

To get the cone, you need to know the horizontal field of view of your 3D camera. If you have that, you just need to take the vector representing the direction in your 2D minimap and add half the field of view to it to get one side and subtract half the field of view to get the other size. Use the near and far plane of the frustum to show how far it extends.

# Answer
> 0 votes
Simply explained and without code, you can get the normalized direction vector of the camera and just convert it to minimap's position exactly the same way you do with the rest of objects.

You have camera position, so you can place your camera in the right point of the minimap.

Then, you use it's direction vector to align/rotate a sprite which would represent that cone of view.

Does it help?

---
Tags: java, libgdx, camera, projection
---


title: Compare mouse movement to the pattern

text:
# Question
Title: Compare mouse movement to the pattern
There are some games where you need to make special movement with your mouse (spell casting or any other action).

**Something like this**

So basically, how can I compare mouse movement to my pattern (let's say defined by series of points (x, y). I assume there's no need to track the position every frame, there must be an interval.

But in terms of technique, how can I do it?

# Answer
> 4 votes
I think the best way to solve this is by using a neural network that has been trained extensively on a lot of data. Draw your own shapes, make your friends draw them etc. It would then be able to guess which one the user tries to draw even if it's not perfect.

More info on how to model a neural network to recognize hand drawn shapes can be found here

---
Tags: mouse, motion, patterns
---