# Question
Title: How do I make three attack systems so that there is a rock-paper-scissors distribution, but equal average?
In the game, there are three attack systems: Strength-based, Magic-based, and Psionic-based.

The damage each type deals will be multiplied by their own modifier. The one for strength I have come up with is ((3 d6 rolls)\*10+Luck)/100.

How can I make similar calculations (willing to not use the one I came up with, but would like to do something similar) so that the Strength one beats the Magic one more often than not, the Magic one beats the Psionic one more often than not, and the Psionic one beats the strength one more often than not, by roughly the same amount on average.

I know that this sort of thing is possible.

If you take four spinners with six numbers, (5,4,3,5,4,3) loses 2 out of 3 to (6,6,0,0,6,6), which loses two out of three to (7,1,7,1,7,1), which loses 2 out of 3 to (2,2,8,8,2,2), which loses 2 out of 3 to (5,4,3,5,4,3).

# Answer
> 2 votes
In case the two parties each select an attack type (S/M/P) before the attack, you could do this:

Both parties roll two dice.

If they both use the same attack type (S vs S, M vs M or P vs P), then the damage dealt by each is the lowest valued dice.

If either party chose a dominant attack type (S over M, M over P or P over S), then that party deals according to highest valued dice.

That does result in a dramatic advantage though: 77% chance of win for the dominant attack over a 12% chance of win for the other.

To temper that advantage, you could instead let dominant party take best of three dice, versus dominated party take best of 2 dice.

---
Tags: mathematics, combat
---


# Question
Title: Examples of transforming camera in its local coordinates vs world coordinates OpenGL
I am trying to learn OpenGL and am doing some beginners learning exercises. One of the exercises is to translate and then to rotate the camera along its own local coordinates and not the world coordinate system.

I am at a loss at how to do one vs the other. I'm aware how to perform translations and rotations using glTranslatef() and glRotatef() functions. Through research I'm also aware of using the 4x4 transformation matrix to multiply our vector/s with to create the desired transformations, although I've not yet messed around with it personally so I'm not too familiar with the transformation matrix.

This being said, I still have questions regarding the local vs world coordinates. I understand that we can put into effect translations and rotations via these functions or the transformation matrix, but I'm concerned with understanding how we do one vs the other. I haven't found any explicit code/examples of transforming a camera (or a model, but I'm more concerned with the camera in this instance) with respect to the world coordinates, and likewise for transforming it with respect to its local coordinates. I feel like at this point I need something rather explicit, because I've felt confused for several days now.

Furthermore, there may be some conceptual things I am confused about. This is to my understanding: If we strictly move objects and the camera (which to my understanding functions like any other object in the world) by the local coordinate system, does that mean that all the local coordinate systems share the same position of their origin with each other and the origin of the world coordinate system? Then, on the other hand, if we strictly move objects/camera with respect to the world coordinate system, then all objects will always be on their own local coordinate system's origin, right? And assuming no object is positioned on the same spot, then no local coordinate systems origin will be positioned on the same spot, right?

# Answer
The glTranslatef() and glRotatef() calls are fixed function old-style OpenGL. It's best to forget about them.

Modern OpenGL uses vertex and fragment shaders, and it is up to your shader to project your geometry onto the screen.

To do this, vertices of your model have to be multiplied with what is called the "Model View Projection Matrix." Please bear with me for now before I address your question.

The Model-View-Projection matrix is just as the name implies: the multiplication of three matrices:

* Model Transformation Matrix
* View Transformation Matrix
* Projection Matrix

The **Model Transformation Matrix** represents how your model is positioned, oriented and scaled into the world. If you place your model at pos (4,5,6) for instance, this matrix would be:

```
1 0 0 0 // row0: the x-axis (1,0,0)
0 1 0 0 // row1: the y-axis (0,0,1)
0 0 1 0 // row2: the z-axis (0,0,1)
4 5 6 1 // row3: the position

```

The first three rows determine how the object is oriented (and scaled.) These axes need to be perpendicular to each other of course. The last row determines where the object is placed.

Here's the kicker: the **View Transformation Matrix** is nothing more than the inverse of the Camera Transformation Matrix.

So your program will place the camera in the world, using a transformation matrix just as it places objects in your world as described above.

When it is time to render your world, you take your Camera Transformation Matrix and invert it.

Mᵥᵢₑ ≔ Mcₐₘ ⁻¹

Generating a **Projection Matrix** is typically done only if the window is resized, and your window aspect ratio changes.

For how to create a projection matrix, for instance a perspective projection, you can read up here.

Multiply the model matrix with the view matrix, and multiply the result with the project matrix to get the fully concatenated Model-View-Projection Matrix.†

You typically pass this Model-View-Projection Matrix as a uniform to your vertex shader, which will multiply the vertices and normals with it. `gl_Position = modelviewprojmat * pos;`

Now to **finally get back to your original question**, how to move the camera in its local space.

So remember how we now keep track of a camera transformation matrix. It places the camera in your scene. To move or rotate your camera in its own reference frame, you can simply manipulate this matrix using information from that very same matrix.

An example: To make the camera step 0.2 units to the left, just get the Y-axis from the camera matrix by doing:

```
axis = cam_mat.getRow(1)      // get camera's Y axis, which points to the left
campos = cam.getRow(3)        // get camera's current position
campos = campos + axis * 0.2  // move it 0.2 units to the left
cam.setRow(3, campos)         // set the camera's new position

```

Another example: To make the camera yaw left and right, you rotate transformation matrix over its own z-axis. So you get the 3rd row of the camera matrix, and use that with an angle to create a rotation matrix. Apply that rotation to your camera transform, and the result will be the camera rotated using its own frame of reference.

Once you have updated the camera transform to your liking, you invert it to get the view transform, and combine it with projection and model transforms, and pass the result to your shader.

(†) Note that depending on convention, the matrix multiplication order is often proj * view * model, as the vertex is typically post-multiplied.
> 1 votes

---
Tags: opengl, transformation
---


# Question
Title: How to call a public function from another script in Unity?
```
public class MoveTowards : MonoBehaviour {

    int currentStartPoint;
    private Vector3 startMarker, endMarker;
    public float speed = 1.0F;
    private float startTime;
    private float journeyLength;
    public float smooth = 5.0F;
    List<Vector3> tempPositionList = new List<Vector3>();
    List<Vector3> positionList = new List<Vector3>
        {
            new Vector3(4,0,0),
            new Vector3(4,0,2),
            new Vector3(4,0,4),
            new Vector3(2,0,4),
            new Vector3(0,0,4),
            new Vector3(-2,0,4),
            new Vector3(-4,0,4),
            new Vector3(-4,0,2),
            new Vector3(-4,0,0),
            new Vector3(-4,0,-2),
            new Vector3(-4,0,-4),
            new Vector3(-2,-0,-4),
            new Vector3(0,0,-4),
            new Vector3(2,0,-4),
            new Vector3(4,0,-4),
            new Vector3(4,0,-2),
            new Vector3(2,0,-2),
            new Vector3(0,0,-2),
            new Vector3(-2,0,-2),
            new Vector3(-2,0,0),
            new Vector3(-2,0,2),
            new Vector3(0,0,2),
            new Vector3(2,0,2),
            new Vector3(2,0,0),
            new Vector3(0,0,0)
        };
    void Start()
    {
        currentStartPoint = 0;
        SetPoints();
    }
    public void SetPoints()
    {
        startMarker = positionList[currentStartPoint];
        endMarker = positionList[currentStartPoint + 1];
        startTime = Time.time;
        journeyLength = 2;
    }

    void Update()
    {
        Debug.Log(positionList.Count);
        float distCovered = (Time.time - startTime) * speed;
        float fracJourney = distCovered / journeyLength;
        transform.position = Vector3.Lerp(positionList[currentStartPoint], positionList[currentStartPoint + 1], fracJourney);
        if (fracJourney >= 1f && currentStartPoint + 1 < positionList.Count)
        {
            currentStartPoint++;
            SetPoints();
        }
    }

}

```

# Answer
> 0 votes
There are different ways,

1. Drag and drop script

```
public class YourOtherClass : : MonoBehaviour {
    public MoveTowards moveTowards;//assign by drag and drop in inspector
    void Start () {
        moveTowards.SetPoint();
    }
}

```
2. Attach your other script on same Gameobject where your MoveTowards script attached

```
public class YourOtherClass : : MonoBehaviour {
    MoveTowards moveTowards;//assign by drag and drop in inspector

    void Start () {
        moveTowards = GetComponent<MoveTowards>();
        moveTowards.SetPoint();
    }
}

```
3. FindObjectOfType

```
void Start () {
    //search by type, it is walid if you have only script with MoveTowards name in scene
    //hirarcey
    MoveTowards moveTowards = FindObjectOfType<MoveTowards>();
    moveTowards.SetPoint();
}

```

---
Tags: unity
---


# Question
Title: how to get the function work without update
I was working on Lerp on arrays of Vector3, i want this function to work without update function(like using loops) i am not getting how to implement it.

```
public class MoveTowards : MonoBehaviour {

    int currentStartPoint;
    private Vector3 startMarker, endMarker;
    public float speed = 1.0F;
    private float startTime;
    private float journeyLength;
    public float smooth = 5.0F;
    List<Vector3> tempPositionList = new List<Vector3>();
    List<Vector3> positionList = new List<Vector3>
        {
            new Vector3(4,0,0),
            new Vector3(4,0,2),
            new Vector3(4,0,4),
            new Vector3(2,0,4),
            new Vector3(0,0,4),
            new Vector3(-2,0,4),
            new Vector3(-4,0,4),
            new Vector3(-4,0,2),
            new Vector3(-4,0,0),
            new Vector3(-4,0,-2),
            new Vector3(-4,0,-4),
            new Vector3(-2,-0,-4),
            new Vector3(0,0,-4),
            new Vector3(2,0,-4),
            new Vector3(4,0,-4),
            new Vector3(4,0,-2),
            new Vector3(2,0,-2),
            new Vector3(0,0,-2),
            new Vector3(-2,0,-2),
            new Vector3(-2,0,0),
            new Vector3(-2,0,2),
            new Vector3(0,0,2),
            new Vector3(2,0,2),
            new Vector3(2,0,0),
            new Vector3(0,0,0)
        };
    void Start()
    {
        currentStartPoint = 0;
        SetPoints();
    }
    public void SetPoints()
    {
        startMarker = positionList[currentStartPoint];
        endMarker = positionList[currentStartPoint + 1];
        startTime = Time.time;
        journeyLength = 2;
    }

    void Update()
    {
        Debug.Log(positionList.Count);
        float distCovered = (Time.time - startTime) * speed;
        float fracJourney = distCovered / journeyLength;
        transform.position = Vector3.Lerp(positionList[currentStartPoint], positionList[currentStartPoint + 1], fracJourney);
        if (fracJourney >= 1f && currentStartPoint + 1 < positionList.Count)
        {
            currentStartPoint++;
            SetPoints();
        }
    }
}

```

# Answer
> 1 votes
You can use Coroutines if you don't want to use the Update function.

```
void Start()
{
    journeyLength = 2 ;
    StartCoroutine( Travel() ) ;
}

private IEnumerator Travel()
{
    for( currentStartPoint = 0 ; currentStartPoint < positionList.Count - 1 ; ++currentStartPoint )
    {
        Debug.Log( "Going to : " + positionList[currentStartPoint + 1] );
        for( float t = 0 ; t < journeyLength ; t += Time.deltaTime )
        {
            float alpha = t / journeyLength ;
            // Or use the following line if you want smooth movement :
            // float alpha = Mathf.SmoothStep(0, 1, t / journeyLength);
            transform.position = Vector3.Lerp(positionList[currentStartPoint], positionList[currentStartPoint + 1], alpha);
            yield return null ;
        }
        transform.position = positionList[currentStartPoint + 1];
    }
}

```

But keep in mind that coroutines can't be started if your GameObject is disabled

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


# Question
Title: How to achieve an aesthetic which looks like hand-made pencil and paper drawings?
I am a programmer in the process of making a stick figure game and I draw the figures myself. The thing is that they look like they are made of black pixels, but I want them to look photorealistic as if they were drawn on paper. They are also animated with short 4 frame loops, each frame drawn individually.

I want my game art style to look somewhat like the following drawings,   but imagine this is actually a game where everything is animated. Is this possible with proper art style alone or shading techniques should be involded in the process? If so, can you point me in the right direction?

# Answer
> 3 votes
If you want to replicate the aesthetics, you could try to replicate the process.

Instead of trying to pixel your graphics in an image editor, hand-draw them with pencil on paper and then scan them. Use an image editor to convert brightness to alpha transparency so the white parts are fully transparent and the dark parts are as opaque as they are dark (how to do this depends on your preferred image editor). If you prefer to work purely digital, you might want to use a graphic tablet and experiment with different brush settings which emulate pencils or felt tip pens. I would recommend working with black on an alpha-transparent canvas.

Objects like buildings or vehicles have white surfaces which are supposed to be opaque and obscure objects behind them. In order to do this, you should create a new layer in your image editor below your lineart. Fill the solid areas on the background layer with fully opaque white.

Then organize your animation frames into spritesheets. You should be able to use any 2d graphics API which can draw sprites with alpha transparency (most reasonably modern APIs should be capable of that).

---
Tags: art
---


title: Game UI Programming

text:
# Question
Title: Game UI Programming
I'm looking for recommendation for resources for learning UI Game programming, i'm creating a simple game in C++ and OpenGL but it gonna be UI heavy and i wanna learn how to write a good UI system for it.

# Answer
Recommendations for learning resources are (unfortunately?) off topic on gamedev.stackexchange so I won't answer that part.

Learning UI game programming can and should be split into 2 parts, Design and Development.

---

To learn about Development, the best you can do is to look at multiple existing complete frameworks (QT, WPF, etc), and try to figure out what is the same and what is different, and try to guess **why**.

In addition, I strongly recommend you use an existing GUI framework for C++ and OpenGL - because these are the technologies you decided to use - then look for tutorials specific to that framework. Using an existing framework will allow you to skip many "minor" issues which become a lot bigger once you have to solve them on your own. A great example of these "minor" issues is UI resizing for different screen sizes and resolutions.

---

UI Design unfortunately is trickier, and here you indeed need some book recommendations (which are off topic here). Other than book recommendations, my advice is that you focus on rapid prototyping.

The fastest prototypes are created with pen and paper. For interactive prototypes some specialized applications exist, but I recommend instead of specialized applications you create interactive prototypes using the very GUI framework you're going to use to create your game. This is another reason to use an existing framework: when prototyping you don't want to be stopped by the need to implement major features.
> 1 votes

---
Tags: opengl, gui, ui-design
---


title: Best way to render multiple objects

text:
# Question
Title: Best way to render multiple objects
I have a scene that consists of 1 player object, 1 platform, 1 enemy, and 1 background. Currently, this is how my render function looks like:

```
void Sprite::Render()
{
    glUseProgram(m_Program);
    glActiveTexture(GL_TEXTURE0);

    // Background
    glBindVertexArray(BackgroundVAO);
    glBindTexture(GL_TEXTURE_2D, m_Textures[1]);
    glUniform1i(glGetUniformLocation(m_Program, "Texture1"), 0);

    m_ProjectionMatrix = m_Camera.ViewToWorldMatrix();
    m_TransformationMatrix = m_ProjectionMatrix;
    m_TransformationMatrixLoc = glGetUniformLocation(m_Program, "TransformationMatrix");
    glUniformMatrix4fv(m_TransformationMatrixLoc, 1, GL_FALSE, &m_TransformationMatrix[0][0]);

    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, 0);

    // Enemy
    glBindVertexArray(EnemyVAO);
    glBindTexture(GL_TEXTURE_2D, m_Textures[2]);
    glUniform1i(glGetUniformLocation(m_Program, "Texture3"), 0);

    m_ProjectionMatrix = glm::translate(glm::mat4(), glm::vec3(EnemyX, EnemyY, 0.0f)) * m_Camera.ViewToWorldMatrix();
    m_TransformationMatrix = m_ProjectionMatrix;
    m_TransformationMatrixLoc = glGetUniformLocation(m_Program, "TransformationMatrix");
    glUniformMatrix4fv(m_TransformationMatrixLoc, 1, GL_FALSE, &m_TransformationMatrix[0][0]);

    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, 0);

    // Platform One
    glBindVertexArray(PlatformVAO);
    glBindTexture(GL_TEXTURE_2D, m_Textures[3]);
    glUniform1i(glGetUniformLocation(m_Program, "Texture4"), 0);

    m_ProjectionMatrix = glm::translate(glm::mat4(), glm::vec3(0.0f, -0.5f, 0.0f)) * m_Camera.ViewToWorldMatrix();
    m_TransformationMatrix = m_ProjectionMatrix;
    m_TransformationMatrixLoc = glGetUniformLocation(m_Program, "TransformationMatrix");
    glUniformMatrix4fv(m_TransformationMatrixLoc, 1, GL_FALSE, &m_TransformationMatrix[0][0]);

    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, 0);

    // Player
    glBindVertexArray(PlayerVAO);
    glBindTexture(GL_TEXTURE_2D, m_Textures[0]);
    glUniform1i(glGetUniformLocation(m_Program, "Texture2"), 0);

    m_ProjectionMatrix = glm::translate(glm::mat4(), glm::vec3(PlayerX, PlayerY, 0.0f)) * m_Camera.ViewToWorldMatrix();
    m_TransformationMatrix = m_ProjectionMatrix;
    m_TransformationMatrixLoc = glGetUniformLocation(m_Program, "TransformationMatrix");
    glUniformMatrix4fv(m_TransformationMatrixLoc, 1, GL_FALSE, &m_TransformationMatrix[0][0]);

    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, 0);

    glBindTexture(GL_TEXTURE_2D, 0);
    glBindVertexArray(0);
}

```

As you can see, it is unnecessarily complicated. And if I want to draw, say, two or more enemies, or 4 or more platforms, then it'd get ridiculously large! My question is this, how can I make this smaller? I prefer to be able to do something like this in my main.cpp: Sprite.Render(Player); Sprite.Render(EnemyOne); etc...

Looking forward to reading your tips, thank you!

# Answer
The archtypal solution to this is a scene graph. It may be a little complicated for a mere 5 or 10 objects, but it is basically the defacto standard for more complicated games like first person shooters.

The fundamental goal of a scene graph is to separate the data that describes what should be done from the code that does it. You create a set of "nodes" in the graph containing the data which describes the scene, and then you have a visitor that "traverses" the graph to execute the openGL drawing commands. Historically speaking, the division provided by a scene graph has been found to be very ideal for many many games. Toolkits like Unity rely on it heavily.

In such a scene graph, you could have a node that describes how to render a player. It's also typical to decouple the transformation matrices from the objects, so you'd likely have a transformation node (with the player location) with your player geometry and textures as a child node.

Scene graphs obviously get more complicated than that (I still don't understand OGL's scene graph fully), but it works well enough that nearly everyone does it.
> 1 votes

# Answer
Your code is very specific, and overly explicit. It is also not flexible.

Consider refactoring your code to:

1. Be reusable.
2. Be more generic.
3. Reuse data when you can.

Let me explain:

What can we say about how to render a given game entity?

To render each entity(in your case), you require:

1. Projection Matrix (unique to each entity)
2. Transform (unique to each entity)
3. A shader program (reusable, but may be unique)
4. A texture representing the sprite(may be unique)
5. A uniform location for your transform (reusable, if reusing same shader)
6. Number of vertices, and mesh handle for your quad, which will be textured(reusable, but not guaranteed to be unique in future)

To solve this problem, we can use object orientated principles to encapsulate graphics data:

* A ShaderProgram class which handles all shader functions.
* A Mesh class which stores mesh handle and number of vertices
* A Texture class, which stores the texture handle.
* Finally, an Appearance class, which stores the others.

Your code would then become something like:

```
void renderAll() {

    for (auto entity: m_entities) {
        entity->getAppearance()->getShader()->activate();
        entity->getAppearance()->getShader()->setTransform("TransformationMatrix",entity->getAppearance()->getTransform() );
        entity->getAppearance()->getTexture()->Bind();
        entity->getAppearance()->getMesh()->Bind();
        entity->getAppearance()->getMesh()->Draw();
    }

}

```

All the code you currently have is now hidden inside these classes. Doing this will allow you to provide new Meshes from file data, and makes your rendering engine more flexible. In this way also, you only have to write each bit of code once, then simply reuse the code over and over, as required.
> 1 votes

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


# Question
Title: How to know my lighting shaders matches famous models?
I have some diffuse and specular lighting shaders based on famous models like lambert etc. Thing is, how can I know that my shader is actually implementing the correct formula? I can see my materials does reflect light but how can I be sure that my formula matches the models. Any way to test this?

# Answer
> 1 votes
You can use a well known software that implements it correctly (such as Marmoset Toolbag) and compare its rendering of your object with your own renderer. If there is no difference, you know you've done it right.

---
Tags: unity, shaders
---


# Question
Title: Smoothing Pathfinding on Tile-Based Terrain but Free-Roaming Player
I'm sorry if this is a long post, but I feel as though the details should help clarify gray areas. I'll try and provide a detailed layout of what I'm trying to achieve, what I have so far, and where my questions stand/I'm stuck at.

(Will likely touch up how this post looks when seeing it live properly)

**Game Overview:**
I'm designing a top-down, single-layer, obstacle-based game that will consist of tile-based terrain (*only* squares). Players, enemies, and objects, however, will be capable of free-roaming and do not snap to any grid. Players, in particular, will vary in sizes and models, so as a generalization they could be circles, triangle, squares, X's, etc.

Since pathfinding is going to rely on solidity, this is the layout I am aiming for:

* Tiles will always be solid **or** not solid.
* Players and enemies will *never* be solid.
* It would be nice for objects to go either-or, but if not they can be non-solids.

**My Progress:**
I've got the the grid-based terrain set up in a Tile\[\]\[\] design. Since there's only 1 tile per (x,y) coordinate, this allows for clean referencing. Tiles, however, could change via triggers very seldom. So a non-solid Grass tile could turn into a solid Stone tile that is impassible.

Player movement via the mouse is in place. Although this will likely get overwritten with the pathfinding, it currently works with moving the player from point A to point B. The player class has its pixel-position, image, scale, and speed. A player will be 1 grid unit in size (currently 40x40px) and scaled from there. So 0.5 scale is always 20x20px.

Minor hit box detection is in place with bounding boxes as a very general design. Later this will likely get changed to a pixel-checking hitbox method.

**My questions/concerns:**
My main question for reference is which pathfinding method(s) can I use to know that my unit that isn't based on a grid can move through my map properly and not have clipping? Keeping in mind again that the player can vary in size and tiles can change solidity.

I've spent the past few days looking into pathfinding methods. I've looked into A\*, HAA\*, HPA\*, NavMeshes, and lightly into things like D\* and Dijkstra's algorithm. However, pathfinding in general is brand new to me when it comes to something that doesn't move directly on a grid.

**Reference material:**

The 2x2 teal box is the player. The green 2x2 is the goal. The dots are where the player's top left would be if he went on the grid one square at a time. The gold line is what I'd like to path like.

This HPA\* method seems like it'd work, but I'm not sure how to get the path smoothing to work. Would I just constantly see if the next point in the list is something I can go directly to without clipping and remove it if I can?

**End Comments:**
I'm not sure if posting some structural code here would provide any benefit as my issue is with the methodology of how to approach this rather than what I have so far.

I **do** know there are some topics involving this. I cannot link since I'm limited to two, but I see one here titled '**Tile-wide extent tracing on a grid**' that seems to ask a similar thing. The problem with almost all example pictures of pathfinding methods uses a size-less example. (Except this one, but it still clips in one of its turns)

The unit itself will have a turning speed involved, but I don't think that should affect the cornering. For the most part, I don't need smooth, car-like, turning if it's more work.

Please let me know if there's anything I missed, I should clear up, or if I've overlooked a topic that went deep into exactly what I'm asking. It's late and I wanted to get something up on here while I continue my search. I just feel lost in this implementation.

# Answer
Size and fit can be taken care of the heuristic that declares whether a move is valid during the path finding. Once the path itself is generated it's then up to a localized movement function to handle not bumping into things on the way, called path smoothing. Maybe paths with smoothing will help generate some ideas that work for you.

The last time I did this I used the path as a kindly suggestion and did local look-ahead to straighten out the zig-zags and then some hacking to always go wide around corners and allow colliding and sliding against the outside in favor of hooking up against the inside of the corner.

If at any point after a particular path has been generated the grid changes you must regenerate the path.
> 1 votes

# Answer
I got good results by using A\* then from the last node i was casting rays back to each node in the path, checking height of terrain on each ray to determine if it was still ok to walk there (you can add your own logic here, water, enemies, buildings ... etc ... mine was if height difference was less than 1 unit per 1 unit distance, then you can't walk), once i hit a node that fails the ray test, i used last node that passed the ray test, and cast rays from it to the remaining nodes, iterate till reaching the start point, and got nice paths, on open maps you will get a straight line between N-start and N-end

A\* = N(start), N1, N2, N3 N4 N5 ... N(end)

```
for i = end ; i >= start ; i--
    ray-test = true
    ii = i // ray must pass by default between 2 adjacent nodes

    while ray-test == true && ii != start
        ii--
        from N(i) cast ray to N(ii)
        ray-test = check path along the ray N(i) --> N(ii)

    //here N(ii) failed the ray-test,
    //thats how we got outside the loop
    //ignore all nodes between the end/destination
    //node than the last node that fulfills the ray test

    N(i).parent = N(ii+1)

```
> 0 votes

---
Tags: java, 2d, movement, path-finding, navmesh
---


# Question
Title: Moving one object from one point to another with acceleration
How would someone implement moving an object from one point in 2D space to another using these formulae to update objects:

```
m_position.setX/Y( m_position.X/Y() + m_velocity.X/Y() * dt + 0.5 * m_acc * pow(dt,2);
m_velocity.setX/Y(m_velocity.X/Y() + m_acc * dt);

```

I'm trying to make a pong clone and I'm having some trouble programming the AI paddle to go to the y coordinate where the ball will hit. (the y coord is predicted in a function).

Currently I have it so that it applies an acceleration of 1 until half the distance then an acceleration of -1 after it, but naturally it is overshooting by a lot, then trying to go back, etc.

# Answer
This is a job for a **PID Controller**:

**P**roportional **I**ntegral **D**ifferential Controller.

Consider this: if you are close to the goal, how hard do you push? It all depends on the velocity. If you are not moving, you push towards the goal. Yet, if you are already speeding towards the goal, you need to push in the *opposite* direction so you don't overshoot.

The PID controller will take an actual value (current pos) and a desired value (goal pos) and gives you a steer value.

This steer value is used to apply force to the paddle (or in other terms: accelerate/decelerate the paddle.)

This means you need to give your paddle two pieces of state: a position and a velocity.

Each frame you do:

```
accel = pidcontrol( desiredpos, actualpos, dt );
vel = vel + dt * accel;
pos = pos + dt * vel;

```

To tune the controller, you need to tune P, I and D constants associated with the controller.

I wrote a Primer on PID Control that explains it in detail, and comes with code too.
> 1 votes

# Answer
Your velocity is 0 when the ball stops, so the velocity must be 0 at the point where it would "overshoot" (when there's a direction change required in the paddle).

You can set your velocity to 0 and change paddle direction when your paddle has reached the y coordinate of the ball.
> 0 votes

# Answer
I believe it is as simple as accelerating until you are a **square root** closer and then decelerating to 0. This is because the final distance is equal to the square of the number you begin to decelerate at. If you begin to slow right after 3 pixels, you will end up at 9 pixels from your starting point. If you stop after 20 pixels, the final result will be 400.
> 0 votes

# Answer
For this purpose I would use Verlet integration. It's nice and easy to implement algorithm. You can read more about it here.
> 0 votes

---
Tags: c++, physics, sdl
---


title: OpenGL depth problem

text:
# Question
Title: OpenGL depth problem
I am drawing two cubes, first a red one and then a green one in front of the red one. When I rotate the camera I can see the green cube through the red cube.

I have enabled depth test and I clear depth buffer. I'm using OpenGL 4.4 core profile and a simple diffuse shader by the way.

# Answer
> 0 votes
I was using `gl_Enable(GL_DEPTH_TEST);` only at the beginning of my render process outside of the main loop so then I realized I should set this render state every frame before my render calls so I did it.

Example:

```
// main loop
while(true)
{
    // depth test
    gl_Enable(GL_DEPTH_TEST);

    // render calls...
}

```

---
Tags: opengl
---


# Question
Title: How to fire a projectile in a certain direction with constant velocity (directX 9)
I am working on a top down 2d shooter. I am trying to make the bullets go at a constant speed (in pixels) in the direction of the mouse. I am having trouble doing this. My bullets fire directly 45 degrees off where the mouse is. I wrote this method which sets all the angles and rate of travel.
travelRate: Bullet speed in pixels per frame

targetX: target X coordinate in pixels

targetY: target Y coordinate in pixels

changeX: how far the bullet should go per frame along the X axis (in pixels)

changeY: how far the bullet should go per frame along the Y axis (in pixels)

ent: The player/npc shooting the Projectile

I do not understand why my bullets are going at a 45 degree offset from the mouse.NOTE: I cut out some of the unimportant code from this method.

```
void Projectile::init(Entity * ent, int targX, int targY)
{
travelRate = 4;
setX(ent->getX());
setY(ent->getY());
targetX = targX;
targetY = targY;
float deltaY = getX()-targX;
float deltaX = getY()-targY;
float dLen = sqrt(deltaX*deltaX + deltaY*deltaY);
if (dLen == 0)
    dLen == 1;
deltaX /= dLen;
deltaY /= dLen;
float deg = rad * 180 / PI;
changeX = deltaX * travelRate;
changeY = -deltaY*travelRate;
}

```

# Answer
```
float deltaY = getX()-targX;
float deltaX = getY()-targY;

```

Could it be that you have mixed up deltaX and deltaY here?
> 0 votes

---
Tags: 2d, mathematics, directx
---


# Question
Title: How to mirror/reflect/flip a 4D transformation matrix
I am importing my animation keyframe joint data from Blender to my game engine. The joint data is a set of 4D matrices. Things are looking good except a remaining issue where the animation is facing the opposite direction than expected.

The matrices are column major, left handed coordinate systems. Y is up. I essentially need to reflect all the joints on the the Z axis. A rotation around the Y axis will not be enough because there are translation transformations that need to be mirrored as well.

**Edit**: I am looking for the math on how to do this in the engine and not from Blender.

# Answer
> 5 votes
To get a transformation matrix equivalent to the one you have, but reflected across a major axis you can compose it (multiply it by) a reflection matrix.

That is, if you have your input matrix M and you multiply by a matrix N that has the reflection.

To create the reflection matrix based on the major axis, you take the identity matrix and flip signs depending on the reflection you need.

You say you need to mirror the transformation on the `Z axis`, I understand this as reflecting against the `XY plane`. In other words, both `X` and `Y` values stay the same but `Z` is mirrored. That means that you will flip the sign of the 1 for the `Z axis`.

For clarity:

```
//                            x  y  z
                            _            _
                           |  1  0  0  0  |
                           |  0  1  0  0  |
Matrix_Mirrored_On_Z = M * |  0  0 -1  0  |
                           |_ 0  0  0  1 _|

```

Notes:

1. `*` denotes matrix multiplication.
2. As said above, the shown matrix keeps `X` and `Y` values the same, and flips Z. If that is not what you want, I hope you can build the matrix you need using this explanation.
3. As you would expect, composing the reflection matrix twice should give you back the original.
4. I have not taken translation into consideration. The reflection matrix is intended to mirror across the `XY plane` (`Z = 0`). If need to mirror a translated object, you may want to undo the translation, mirror and translate again, in doing so the object will keep its location while being flipped on the `Z axis`.

---
Tags: matrix, transformation, skeletal-animation, linear-algebra
---


# Question
Title: Get the dropped object using IDropHandler.OnDrop
In Canvas, I drag some UI objects to a panel using this code:

```
public void OnDrag(PointerEventData eventData)
{
   Vector3 screenPoint = Input.mousePosition;
   screenPoint.z = 10.0f;
   Item2Drag.position = Camera.main.ScreenToWorldPoint(screenPoint);
}

```

But what I can't figure out is when I dropped an object on the panel, how can I get the gameObject which has been dropped?

# Answer
> 3 votes
I figured it out.

I can get it by `eventData.pointerDrag` from OnDrop function.

```
public void OnDrop(PointerEventData eventData)
{
   GameObject droppedObject = eventData.pointerDrag;
}

```

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


title: How can I make a GameScreen?

text:
# Question
Title: How can I make a GameScreen?
I want to make game level select screen.

There are some stages which open, and some that are not.

So if you clear a second stage and quit the game for a while, when you come back, you can start at stage 3, 2 or 1 whatever you can click, but not from stage 4; you can't play it without completing stage 3.

I want to make something like this, but I have no idea how. What should I use to do it (boolean, database...)?

Can you give me some simple code structure?

# Answer
> 2 votes
I would first recomend you look into a few tutorial sites like Full Libgdx game tutorial or Games From Scratch.

Having said that, I will tell you how I handle game screens and level systems so that you can start at a level based from previous plays.

Libgdx comes with a Game class which you can extend for your application. This will be the starting point of your app. From this class you switch to different screens(Screen) depending on what task you're trying to accomplish, whether its changing the preferences, viewing high scores or playing the game.

Let's look at a single case that covers all the points in this question.

1. The user starts the app
2. The user is presented with a menu and chooses to view the options/prefs
3. The user goes back to the main menu
4. The user plays the game and dies at level 2
5. The end screen is shown to the user
6. The user is sent back to the main menu
7. The user plays again but starts at level 2
8. The user dies at level 3
9. The end screen is shown to the user
10. The user is sent back to the main menu
11. The user quits (and level 3 save point is saved)

Now we know how we want the process to play out we can start implementing this.

First our Game class which will control the changing of screens and saving of the current level. We also know we need a Screen for the menu, the game, the preferences and the end screen so we will add those in the Game class too. In our case shown above, this would be step 1.

**MyGameClass**

```
public class MyGameClass extends Game {
    private MenuScreen menuScreen; // has a menu on it
    private PreferencesScreen prefScreen; // has options to change game prefs
    private GameScreen gameScreen; // shows the game
    private EndGameScreen endScreen; // the end screen to show user points etc
    // constants for different screens
    public final static int MENU = 0;
    public final static int PREFERENCES = 1;
    public final static int APPLICATION = 2;
    public final static int ENDGAME = 3;

    // get the app preferences (for loading last level)
    Preferences prefs = Gdx.app.getPreferences("My Preferences");

    public int currentLevel = 1; // set the level to 1

    @Override
    public void create () {
         // load the level from prefs file(if no value is saved 1 will be used)
         currentLevel = prefs.getInteger("highlevel", 1);
         // change the screen to the menu
         changeScreen(MyGameClass.MENU);

    }

    // the method to change screen
    public void changeScreen(int screen){
         switch(screen){
            case MENU :
                menuScreen = new MenuScreen(this);
                this.setScreen(menuScreen);
                break;
            case PREFERENCES :
                prefs = new PreferencesScreen(this);
                this.setScreen(prefs);
                break;
            case APPLICATION :
                gameScreen= new GameScreen(this,currentLevel);
                this.setScreen(gameScreen);
                break;
            case ENDGAME :
                endScreen = new EndGameScreen (this);
                this.setScreen(endScreen);
                break;
         }
    }

    public void saveLevel(){
         prefs.putInteger("highlevel", currentLevel);
    }

}

```

Now the Menu screen. This screen should basically show a menu so the user can click buttons to choose what they want to do, be it look at the preferences, start the game or quit the application. This is step 2-3,6 and 10

**MenuScreen**

```
public class MenuScreen implements Screen{
     private MyGameClass parent;

     public MenuScreen(MyGameClass mgc){
         parent = mgc;   //store the parent class
         // so we can tell it to change screen
     }

     @Override
     public void show(){
         // code to show a menu and buttons etc
         // I usually use Scene2D Stage and TextButtons
         // in the button's listener I would change screen like this
         parent.changeScreen(MyGameClass.APPLICATION);
     }
}

```

Next the GameScreen which will show your game. This is the only screen that takes the parent class and an int value. The int value is to allow the game screen to choose which level to load. This is step 4, 7-8

**GameScreen**

```
public class GameScreen implements Screen{
     private MyGameClass parent;

     public GameScreen(MyGameClass mgc, int startLevel){
         parent = mgc;   //store the parent class
         // load level goes here using startLevel to identify which level to load.
     }

     @Override
     public void show(){
        // code to show your game
     }

     @Override
     public void render(float delta) {
         // game code goes here and when player dies
         // use parent.changeScreen(MyGameClass.ENDGAME);

         // if the player gets to the next level
         // update the parent level with
         parent.currentLevel++;
         // and save the current level to prefs
         parent.saveLevel();
     }
}

```

I won't go into details about the preferences screen as its explained in many guides. However the basic idea of this screen is:

**PreferencesScreen**

```
public class PreferencesScreen implements Screen{
    @Override
     public void show(){
        // code to show your preferences controls

        // in a button listener you would use
        parent.changeScreen(MyGameClass.MENU);
        // to go back to the menu
     }
}

```

This should of covered how to switch between screens and allow the game to load certain levels based on previous plays by saving the level in the preferences file.

# Answer
> 0 votes
You seem to be asking about at least two different things, how to save and retrieve data from disk (so it sticks around if you quit and come back,) as well as how to structure the data.

Regarding saving, I haven't used libgdx but a quick search turned up this built in method of saving small things.

Regarding how to structure the data, I would suggest thinking about what kind of questions you would like to be able to ask about what the player did, then store the data necessary to answer those questions in a convenient format. For example, if a player always goes from stage to stage consecutively then storing the highest level they got to might be the best option. If instead the player can skip stages and you want to track which specific levels they have and haven't played then a series of booleans is a good fit.

---
Tags: libgdx
---


# Question
Title: How to limit players to low-level content before they advance, if they can't die
I am making a game with the basic RPG elements: levels, xp, items, currency, stats, spells and monsters. The only different thing is that the player doesn't have hitpoints, you can't die. It's a simple game where you basically just kill and farm monsters.

Now a problem I'm facing right now is "content restriction". **I don't want my players to skip the low-level monsters simply because they can't die by the high-level ones.** So how can I achieve this?

# Answer
> 3 votes
I think you should use something more natural.. give the players goals (quests) they need to accomplish in order to proceed. The goals will implicitly require the players to kill monsters in order to progress to higher level areas. So yes organically restrict higher level zones by making the player progress to them by completing quests.

Another option I suggest is to make monsters run away if they don't get killed quickly enough so players will know a high level monsters is not a likely target and focus on lower levels until they are able to take it down quickly. This will give a sense of urgency to battle which is missing when the play cannot lose.

Give players new weapons and tools that make higher level monsters more attractive. Make the best XP - per - second area a same level area. The players can kill higher level monsters but it will lower their xp - per - second. Later give them a weapon that makes higher level an easier and more profitable target because they can farm more xp that way.

# Answer
> 2 votes
I dont think the question should be "How to *force* players" but rather, "how to make *very appealing* to players" to kill low level monsters. The more natural and logical way it is, the better.
You could take example of the pokemon series (I personally think, its one of the best RPGs ever made). You couldnt die. You would be just moved to nearest center (that is similar).
You *wanted* to kill low level monsters to advance your pokemons and thus allowing take down the big boss and gain badge (story goal motivation). You *wanted* to "catch them all" including the low level ones (collection motivation). And lastly you needed a skill to advance (cut, swim...). Those are hard limitation (unlock restriction motivation), plus you could visit previously inaccessible areas for big rewards, you can go as far as make visible big shiny swords across a obstacle.
To break it down: you want to kill small ones, to kill the big one and get "key" to next area, all appearing natural and very RPG. You could hide it just as you suggested - give boss hp regen as dps check.
So, actually best is combination - hard restriction between big zones (acts) while soft ones inside it (gaining strength to kill final boss and unlock new act, collections, sets,...).

# Answer
> 0 votes
You say you have spells. If they gain these through levels, you can provide skill barriers in the world that require higher level spells to overcome.

To borrow a trope, build in several "repair broken bridge" spells.

---
Tags: game-design, game-mechanics, rpg, level-design, balance
---


# Question
Title: How to design a damage formula in an RPG which keeps weapons with different attack speeds balanced?
I'm making a mobile rpg game, an infinite one where there is a loot system like Diablo 3. Weapons have attack and speed, armor pieces have a resistance value (not percentage).

The formula I'm using is:

```
float realDamage = SkillDmg * BaseDamage / ( BaseDamage + Defense )

```

The results are good, the damage gets bigger if the defense gets lower and it doesn't exponentially go up because of the division between ( **BaseDamage** \+ Defense ).

Lets say I have a sword with 1.0 attack speed that deals 50 damage. Thats 50 dps, and I have a dagger that I want it to attack faster, but of course deal less damage, to maintain the dps the logic says that if the daggers attack speed is doubled, the damage needs to be halfed (2.0 speed with 25 dmg ). But using the formula above you'll see that the actual real damage DPS is lower than the sword.

Iv'e solved this by making the dagger not do 25 damage but a bit more, doing some calculations I can make the real dps be the same to balance things. In this case the dagger at 2.0 speed would need to deal 32 damage to be the same real damage dps as the sword.

However, I want to display the DPS number on weapons. If I just display the daggers DPS as 32 dmg * 2 attackspeed it's going to be 64 dps, compared to the sword 50 dps, one will clearly say that the dagger is better, but of course it's not.

Possible solutions? Change the initial damage formula? If so to which one? Lets assume I don't change the formula, is there any solution? I really don't like having to trick the dagger to deal more damage than half to make it even...

I'd really wish I'd know the damage formula for diablo 3. I know that diablo 3 weapons DPS it's simply base damage * attack speed.

Edit:

```
Lets assume defense = 50 and normal attack (skillDmg = baseDmg)

Sword 1.0 attack speed dealing 50 dmg -> real damage hit=  50 * 50 / ( 50 + 50 ) = **25 dmg** = 25 dps

Dagger 2.0 attack speed dealing 32 dmg -> real damage hit = 32 * 32 / ( 32 + 50 ) = **12.5 dmg** = 25 dps

Sword item, lets display the actual sword dps, 50 * 1.0 = **50 dps**
Dagger item, lets display the dagger dps, 32 * 2.0 = **64 dps** (SHOULD BE THE SAME)

```

# Answer
> 20 votes
The problems you have with calculating DPS from that formula are because what you call `BaseDamage` doesn't actually seem to be that.

Assuming that all numbers are positive, `BaseDamage / ( BaseDamage + Defense )` will always resolve to a floating point number somewhere between 1 and 0. It doesn't matter if you have 10 `BaseDamage`, 1,000 `BaseDamage` or 1,000,000 `BaseDamage`, you will always be in that range. Where in that range depends on how the `BaseDamage` of the weapon compares to the `Defense` of the target. That means what *actually* affects the order of magnitude of the realDamage of an attack is mostly the `SkillDmg` multiplier.

Looking at these mathematical properties, I would not really call this weapon property `BaseDamage` but rather `DefensePenetration`, because it describes the ability of the weapon to overcome the enemy defense and still do most of its damage. This might actually be an interesting mechanic to have (or not... it's something you need to testplay), but it does not say much about the power level of a weapon.

So how do we solve this problem?

Well, there is no *right* solution to this problem. But a change which might do what you want to do (twice as powerful weapon = about twice as much damage) is to add the `BaseDamage` as another multiplicative factor:

```
float realDamage = SkillDmg * BaseDamage * BaseDamage / (BaseDamage + Defense)

```

If you like the defense penetration mechanic you accidentally discovered, this is how it would look with `Penetration` as a separate weapon stat:

```
float realDamage = SkillDmg * BaseDamage * Penetration / (Penetration + Defense)

```

The nice thing about this formula is that it scales quite well:

* Even when the defense is pathetic compared to the attack value, there is never more damage than attack. This gives you an upper limit on how much damage a character can inflict, which makes balancing far easier.
* On the other extreme, no matter how high the defense gets, it can never completely mitigate damage (except through rounding errors), so there is always room for improvement for the defender and there is never a completely pointless attack.
* When Defense and BaseDamage (and Penetration when you want it) are roughly the same, there is roughly half as much realDamage as BaseDamage. This is true no matter how large the values are. This is also what you can base your DPS estimation on. Simply assume that the enemy has as much defense as the weapon has attack/penetration, which means your DPS formula becomes `AttackFrequency * BaseDamage / 2`

Edit: Here are some tables with example values:

```
 Damage by Defense for single attack

              Defense
          |     0 |   35  | 50   | 100
       ---+-------+------+-------+-------
       35 |    35 | 17.5  | 14.4 |  9.1
Attack 50 |    50 | 29.4  | 25.0 | 16.6
      100 |   100 | 74.0  | 66.7 | 50.0

 Dps assuming HitFrequency = 100 / Attack

              Defense
          |     0 |   35  | 50   | 100
       ---+-------+-------+------+-------
       35 |   100 | 50.0  | 41.1 | 25.9
Attack 50 |   100 | 58.8  | 50.0 | 33.3
      100 |   100 | 74.0  | 66.7 | 50.0

```

As you can see from these numbers, high-damage-low-speed weapons are still nominally more powerful against the same enemy than low-damage-high-speed weapons if they have the same DPS according to `AttackFrequency * BaseDamage / 2`. But the effect is more visible on high-def enemies than on low-def enemies. Both are equally good on 0-def enemies. That means fast-attack weapons are *less bad* on low-def enemies than on high-def enemies.

This *might* be balanced by the fact that high-speed weapons give the player more flexibility regarding damage distribution and thus allows them to avoid wasting DPS on overkills. When the player faces a very large number of very weak enemies which all die with one hit, then a 5 attacks per second weapon can kill 5 enemies per second while a 1 attacks per second weapon can only kill 1 enemy per second. Another possible advantage appears when you add randomness to attacks. Due to the law of large numbers, many weak attacks will do a smoother and more reliable damage output than few strong ones. Players usually benefit from reliability. But when such considerations are irrelevant due to your game mechanics and/or encounter design, you will have to make your faster weapons a bit more powerful than they should be to compensate.

One way to give high-speed weapons a boost could be the introduction of effects which trigger with an x%chance per hit and do not depend on damage. These would be much more powerful with a fast-attack weapon because they would trigger far more frequently.

# Answer
> 0 votes
If you intend weapons of equal "power" to result in equal DPS, an easy solution would be to assign DPS directly and calculate damage per hit from that, e.g.

```
float realDamage = (SkillDmg * DPS / ( DPS + Defense )) / AttackSpeed

```

In this example, your sword would have 50 DPS and 1.0 attack speed and the dagger would have 50 DPS and 2.0 attack speed. If you want to display damage per hit, that's simply DPS divided by attack speed (i.e. 50 for the sword and 25 for the dagger).

Note that this gets rid of the "slower weapons are better vs high defense" mechanic, which I assume is what you want.

---
Tags: c#, mathematics, game-design, rpg
---


# Question
Title: Zooming in on procedural generated 2D terrain? (LOD)
My question is what methods are there to "zoom in" on a procedurally generated map using Perlin Noise (or Simplex).

If I have for example this generated

and I wanted to "zoom" into that little red square I drew, how could I achieve something to the likes of this (ugly drawn) example:

While staying true to the terrain above? I have heard of 3D methods but couldn't find any meant for 2D maps.

Any advice or help would be appreciated.

# Answer
Lets define your noise function for terrain generation as `f(x,y)`.

`f(x / 2, y)` will set the zoom on the X axis to 200%

`f(x, y / 2)` will set the zoom on the Y axis to 200%

So, it's `f(x / zoom, y / zoom)` for your noise function.

This is true for any function in maths.

You can translate your output too.

`f(x - 100, y)` will move your output by 100 tiles right.

`f(x, y - 100)` will move your output by 100 tiles up.

To zoom by a factor of `z` around point `(a,b)`, you'd transform your noise function `f(a,b)` to `f((x - a) / z, (y - b) / z)`.
> 3 votes

---
Tags: procedural-generation, perlin-noise, level-of-detail, simplex-noise
---


title: Character Model crashes game (Unity VR)

text:
# Question
Title: Character Model crashes game (Unity VR)
I am creating a VR game. Currently, I'm testing it on an `Android` device.

Now I when I run the application it runs smoothly and without any issue.

However when I add the following model:

And attempt to look at it the game crashes.

The model you see doesn't have any scripts on him only a transform component and an animator.

Has anyone tried something similar? or have an idea what the issue might be? **Update i have also tried this following scene**

So i tried to isolate the character completely from my original scene. So i made this:

Again if i have the character in the scene it crashes. if i remove the character it runs perfectly fine.

---

Another update:

If i remove the animator component from the model it works fine?

# Answer
> 0 votes
You need to reimport the char, and make sure the quality of the texture as well as size of the char are as low as your computer cpu. deactive the animator and use another character with controller script on it view the crasher. If it dont work tell your modeler to stop messing around.

# Answer
> 0 votes
I would run this through a model converter. Since you don't specify your current format, something like Max or Maya or Blender or a third party converter such as Spin3D or the like. It may be that converting to another format picks up certain glitches and fixes them implicitly.

And you could always convert back again if you wish, before importing into Unity. But I'd try with one of the alternative formats first, *then* back-convert if that works.

# Answer
> 0 votes
Does the app crash when you place the component on a different gameobject? If it does then the animator component might be causing some issues. Perhaps it isn't supported by the Android version that you are using. I remember in the past the animator causing meshes to dissappear with android 5.0, so it might be something related to this.

Is there any error thrown or warning when you run the app in debug mode on android? Or a crash report perhaps? It would make it easier to pin down the exact problem.

As for now I can only think of using the Unity animation, more info can be found at https://docs.unity3d.com/ScriptReference/Animation.html it does require some coding though to get all animations right.

Perhaps there is some compability issue with the animator component (or even unity) and the android version on your phone, so updating or checking the versions for any compability issue might be a good check too.

If you have an error log available or something that gives us more insight about the crash it would help us greatly.

As a final tip I do suggest you to make use of known and supported model types such as .fbx or .obj as example, using types that aren't well known might not be recognized by the device which can cause crashes.

---
Tags: unity, character, virtual-reality
---


title: How to achieve "Perfect Imbalance"

text:
# Question
Title: How to achieve "Perfect Imbalance"
I've heard the term "perfect imbalance" thrown around a lot, which seems to imply that it is okay for different game options to be strictly superior to others as long as the 'better' options require more player skill to use.

What strategies does one employ, generally, to achieve this? And am I even understanding the principle correctly?

# Answer
> 8 votes
Perfect imbalance relies on players shifting their strategies (collectively forming the meta of the game) in order to neutralize strategic advantages others might use against them.

That means we have two main ingredients:

1. A community of players competing against one another
2. Intransitive mechanics to counter other players' choices

Intransitive mechanics are named in reference to the Transitive Property in math, which says that if we know:

* `A > B`
* `B > C`

then for a transitive relation we can safely conclude that `A > C`.

For a transitive rule and a finite set of options, there's always one that's not less than any other. If we think of our relation as being one of gameplay advantage, that means one option isn't strictly weak against any other option, though it might be equally advantageous as several others.

The risk here is that it's fragile - if we don't get that equality of advantage exact, then we end up with one option that's strictly better than everything else, and ones that are strictly worse. Nobody wants to play a worse option, so our game can become one-note as everyone piles up on the dominant options.

**Intransitive or non-transitive rules** break this. The most familiar example is probably Rock Paper Scissors, where:

* `Rock ---defeats--> Scissors`
* `Scissors ---defeats--> Paper`
* `Paper ---defeats--> Rock` (the opposite of what a transitive rule would say, given the two rules above)

Now there's no way to put these into a strict order of better & worse - there's always a wrap-around point somewhere, some way to "beat the best." This makes balancing these types of mechanics much easier than in the transitive case, because we're not relying on exact parity of numeric relationships to keep two options balanced - instead it's baked into the cyclic structure of advantages.

In games you'll often see this expressed as counter relationships. A sniper character is weak against a fast/evasive character who can close the distance and take them on at close range, but that character will often be lightly armored and weak against a heavily-armored bruiser archetype, who might in turn be weak to being sniped from afar...

If a group of players is dominating by using one of these strategies, say the sniper, then other players can notice this and counter by deploying more fast/evasive characters, dethroning the snipers or forcing them to switch strategies. This keeps the strategic landscape dynamic, fighting the tendency to settle on one optimal strategy or tactic.

This works even when one of these characters/options is, by some definition, strictly more powerful. I recommend reading In Schreiber's Game Balance Concepts blog for the full details & math treatment on why. There he shows that even if we play a version of Rock Paper Scissors where rock wins count double (making it, at first glance, twice as advantageous to play), there's still a way for players to balance their strategic choices that keeps the game fair and interesting overall, without the game collapsing to always playing a particular option.

It doesn't always need to be exactly 3 options, or all in a single loop. Your move / unit / character / build / strategy relationships can be a spaghetti fractal of little loops inside bigger loops. As long as no one option (or group of options) is strictly dominated by all other options, nor strictly dominates all other options, then a sufficiently large & motivated player community will tend to seek out a ratio of choosing these strategies that overall roughly neutralizes individual advantage in the context of the current meta - something called a Mixed Strategy Nash Equilibrium if you want to get into the game theory of it. :)

Just beware that we can't rely wholly on this self-balancing feature of player communities to absolve us of all design responsibilities. Every strategic choice I need to make as a player just to counter the dominant strategies in the current meta is one less choice I have available to express my own play style and preferences - it's a choice that's effectively already made for me, constraining my play space. A little shifting of the strategic tides as the meta evolves can keep the game fresh over time, but when most of my choices are dedicated to fighting against the same lopsided design then I'm likely to be having less fun, and go look elsewhere for my challenge. So we still need careful balance, even when we allow it to be imperfect.

# Answer
> 6 votes
"Perfect Imbalance" means it is acceptable for a game to have one or two game playstyles which are objectively better than the alternatives, as long as there is a feasible counter for them.

Let's take the RTS game Age of Empires II, for example. (Or rather a simplified version of it. I omitted some details for clarity. AoE fanatics, please excuse my oversimplifications).

There are 3 essential combat unit archetypes: cavalry, infantry and archers. Of those three unit types, Infantry is the one with the worst power/cost ratio. Anyone building only infantry will lose against an opponent who builds only archers or only cavalry. So with just those 3 basic unit-types, there is no reason to ever go for infantry. That's a glaring imbalance.

But there is a catch: We haven't talked about the *non-essential* combat units yet. Both cavalry and archers have a dedicated counter-unit: Pikemen and Skirmishers respectively. A cavalry-army is easily defeated by a pikemen-army and an archer-army is easily defeated by a skirmisher-army. But outside of these two situations, both pikemen and skirmishers are pretty much useless. There is nothing they can do except countering the two otherwise superior strategies. So if the enemy tricks you into wasting resources on preparing to counter a strategy she isn't actually pursuing, you will be in a pretty precarious situation.

Infantry has no such direct counter-unit. So you can't really do much wrong by building infantry. So Infantry is suddenly a viable option again.

---
Tags: game-design, game-mechanics, balance
---


# Question
Title: How to make levels that never get old, even with a leveling system?
I always get the feeling that in games with a linear plot and leveling system, players never go back to the older levels because the monsters there are too easy and the world has nothing new to offer there.

Players usually don't go visit floor 1 just for memory's sake or to remember the good times they had there. In fact, they probably forget what happened there and move on like it's nothing. For some reason, this bothers me to no end.

Is there a way to remedy that? I don't want the feeling of certain game areas to become obsolete to the player as the story progresses.

I want my game to be dynamic and ever-changing, with things to offer at every location, at every point in the player's game progress, even if one place is not at the right "level" to match with the player's current overall character levels. There should be a kind of equality, where at no point does the player tire of one place and can move freely from one place to the next. Does this sound slightly open-world ish?

This is not only for replayability, but also to provide a certain kind of elegance to the game. I feel like there is something lacking, and something that might be able to be improved, in RPGs, where the story is everything and so "old" levels are treated as second-class citizens. I was always slightly bored when I had "conquered the world" and ran through every monster like it was spaghetti.

One of the solutions I thought of is to simply update the monsters, treasure chests, items, dialogue, etc. at the old locations. Perhaps even updating the graphics would provide a visual cue that the player can have some more novel experiences there. However, isn't that essentially just changing the very nature of the location itself? The problem I have with that is that players will then forget what happened because the place itself disappeared/changed.

If anyone thinks of any good ideas, I would like to hear them. Thanks!

# Answer
## **Make Locations Evolve with the Player**

As a player, I particularly enjoy the game when my actions affect the world (or if I'm presented with an illusion of it). I would come back to the locations I've been in before and meet new characters or seek other significant changes. Nothing in the world should stay the same, *static* throughout the player's walkthrough. Make the old location *feel* like a new one, but still remain more or less the same place so that the players will recognize it, and they will love it. It's in human nature to come back to the places we've been to and see how they changed.

A decent example of this is **Pillars of Eternity**. Throughout the playthrough some locations change, new characters and questlines appear, new buildings arise or fall, and players are *interested* in coming back and exploring again. For instance, Raedric's Castle, which (spoilers)

> can be cleared by the player, but later in the game the King would return in a form of an undead and retake the castle, slaughtering everyone in the way and raising them to serve in his army.

A *bad* example is **Dragon Age 2**, where every new quest would take place on the *same exact locations* over and over without any noticeable changes, rendering the game *extremely* repetitive.

When the locations never change, and players come back to them only to feel like they've gone back in time, it hurts immersion. For example, the starting town in **Neverwinter Nights 2** doesn't change at all during the first stage of the playthrough (which, in in-game time, should take at least a couple weeks). When the players come back to visit and expect the villagers to have rebuilt the town and try to recover, they're greeted with the same town on fire and scared townsfolk they left. Frustrated, they leave to never come back again, feeling like they've been robbed of a potentially interesting experience.

Automatic scaling and autopopulation of locations in RPGs is okay, but the majority of your players will come back for stories and experiences, not additional grinding that they might as well find at the new locations (unless they're desperate for some extra character levels).
> 2 votes

# Answer
There are various techniques you can use to keep low-level content interesting for high-level players.

## Automatic level-scaling

To make a low-level environment a challenge for a high-level player, simply upscale the enemy stats to match the player's level. When you are developing an RPG, you usually have tons of charts and formulas which tell you what stats are expected on what level, so you should have the necessary tools to simply turn a level 5 enemy into a level 50 enemy.

But if you constantly scale everything exactly to the player's level, then character level becomes meaningless. There is no point in getting stronger when at the same time the whole world also becomes stronger in a way which perfectly balances out.

You might instead let the player control the scaling. When they explore low-level content, let the player choose by how much they want to upscale it. Or you might tie the level-scale of the world to story progression, not player progression. Just make sure the player doesn't accidentally progress so fast in the story that they no longer have content available which is easy enough to let them catch up. A good way to avoid this is placing difficulty spikes (e.g. boss battles) just before story events which result in a world upscale.

## Character Level Resets

The Disgaea series has an interesting leveling mechanic which constantly keeps low-level content relevant: The reincarnation system. You can reset a character back to level 1, and when you level them back up, they are slightly stronger than they were before on the same level. Various mechanics make the process of getting the character back to the average level of the rest of the party a lot faster than it sounds, but it still keeps low-level content relevant.

The Disgaea games also do that level-scaling thing quite well, by the way.

## Progression in width, not height

Instead of just making the player-character stronger, make them more versatile. Give them new abilities which change the way the game is played, but don't make them considerably stronger mechanically.

The earlier parts of the Zelda series are a good example of this.
> 1 votes

# Answer
The Gothic series did this reasonably well, by "re-stocking" enemies as well as items (e.g. herbs to collect) at certain points in the game. This worked for three reasons:

1. While the games had plenty of "linear" character progression, rewards scaled more slowly than difficulty, so lower level monsters still gave relevant amounts of XP. In addition, being outnumbered greatly increased the difficulty of a fight. Instead of luring one or two wolves at a time, higher level players would fight the whole pack at once, gaining XP faster by accepting a tougher challenge. Later in the game, larger packs of the same or similar monsters would be spawned so that areas kept their "feel" while becoming a bit more challenging.
2. Resources like money, XP and herbs were finite. Remembering a spot where rare herbs grew and checking back a chapter or two later was useful because you couldn't just farm the new area over and over. As players progressed, their ability to utilize these resources grew (to a point) with their stats, for example by being able to turn herbs into health potions instead of just eating them. This also meant that a fight could be "lost" by wasting more magic or healing items than the encounter was worth, so a bigger HP pool didn't necessarily mean you should handle easier challenges carelessly, even if you could.
3. Difficulty wasn't uniform. Many early areas contained higher level monsters that the player had to avoid for quite a while. Most would go back at some point to kill that damn troll that used to chase them around.

There were other mechanisms that counteracted the above to an extent, but these can still serve as examples on how to give earlier areas meaning throughout the game.
> 1 votes

# Answer
Some approaches:

* Procedural content, so that the same "recipe" can still give a different surprise each time (example: Spelunky)
* Game mechanics that are still challenging even after hours of gameplay - which often means, make your game hard, make it easy to die (Spelunky again, Dark Souls)
* Achievements and rewards you can get for beating levels in novel ways - beat the record time, collect all the coins, cross it without getting hurt, without being noticed, without killing anybody, find all the secret areas, etc. (this can go along with having tables of what has been done / obtained in each level..)
* Online high-score leaderboards for each levels
* A lot of hidden areas in all your levels (so that you think "hmm I may have missed some in the old levels")
* Areas in the old levels you can only access with powers you get later on in the game (Blaster Master, Zelda, Metroid, etc. do this a fair amount)
* Challenges who scale with your level (the Elder Scrolls games)
* Special items that can only be farmed in certain areas
> 1 votes

# Answer
# Have Enemies Levels Rely upon the Player(s)'

If I'm not completely mistaken regarding what you're asking, this is a mechanic I've also been planning for my game. Somewhat—now, this isn't the *best* example, per se, but it works—like *The Legend of Zelda: Breath of the Wild*, you can have your **enemies' stats load in relation to your players' levels as opposed to their progress in the game or their location** (of course, your area-specific enemies should be loaded in their respective areas, but their *stats* shouldn't be based on their location).

Now, this can be achieved by giving your enemies levels, just like the player. To give the game a better, **more realistic feel**, have their levels slightly randomized depending on what they are—**no motley crew of actual monsters are going to have the exact same skillset**, while maybe **an army of robots would**. For example, if your main character is level 5, you could have your enemies appear at *levels 3-7*.

Having your enemies levels based upon your own can and will immensely help your game in terms of balance and replayability. It **eliminates the need for grinding** (which is *almost unanimously hated* by gaming communities), gives the game a more organic feel to it, and keeps the challenge consistent throughout the entire game. Furthermore, bosses could be handled this way, which would be an incredible mechanic that I've not yet seen before.
> 1 votes

---
Tags: game-design
---


# Question
Title: Should I switch to a game development library?
I'm making an RPG-like 2D game from scratch with Java.

By now I'm in a pretty advanced stage with my game, but I encountered a problem- my game using too much CPU.

I know it's because my game loop doesn't use `Thread.sleep`. I looked for a solution on the internet but most of the answers were "*you should move to LWJGL or LIBGDX*". I also didn't find any good advice for using `Thread.sleep` in my game loop.

So, should I move my platform to some of those libraries, or could someone give me some advice how to deal with my CPU usage problem?

Here is my game loop:

```
public void run(){
    int fps = 60;
    double timePerTick = 1000000000 / fps;
    double delta = 0;
    long now;
    long lastTime = System.nanoTime();

    while (running){
        now = System.nanoTime();
        delta += (now - lastTime) / timePerTick;
        lastTime = now;

        if (delta >= 1) {
            tick();
            render();
            delta--;
        }
    }

    stop();
}

```

I will just mention that I don't think that moving to one of those libraries will make things easier in the future, and that's because I'm in a pretty advanced stage in my game.

# Answer
> 1 votes
There is no reason to switch to a library, unless you want to cut out a particular step from your development process.

In your particular case, I perceive that you may be updating your game logic and render everything too often, which makes your loop inefficient.

Try a game loop with *fixed update time step, variable rendering*, which is agreed to provide the smoothest possible experience to a player. In that kind of loop, you'd update your game logic a fixed amount of times a second, and render it every time you have an opportunity to (particularly, when the computer has updated all the game logic and is idle).

While this will be more efficient in terms of CPU usage, it may be more of a challenge to implement as certain issues (such as the need for extrapolation) will have to be addressed.

Example code:

```
double previous = getCurrentTime();
double lag = 0.0;
while (true)
{
  double current = getCurrentTime();
  double elapsed = current - previous;
  previous = current;
  lag += elapsed;

  processInput();

  while (lag >= MS_PER_UPDATE)
  {
    update();
    lag -= MS_PER_UPDATE;
  }

  render();
}

```

Check out Game Loop chapter of Game Programming Patterns book by Robert Nystrom for some good examples and detailed explanations. That chapter was also used as a source was this answer.

---
Tags: java, libgdx, performance, lwjgl
---


title: Split a grid into random paths

text:
# Question
Title: Split a grid into random paths
I need an algorithm to split a grid into randomly generated paths where:

* A path is a list of cells connected at most to two adjacent cells.
* Paths have a minimum and maximum length.
* All cells in the grid belong to a path.
* Grid might have gaps.

The algorithm must be random, with no artificial bias. With this I mean:

* There should be no bias for path positions/trajectories (e.g. wrong if a path always starts at `(0, 0)`, paths always starting adjacent to other path path ends, etc.)
* There should be no bias for path lengths. E.g. algorithm must not favor a short length if a longer path would fit.
* Natural bias due to grid state (even intermediate states) is fine (unavoidable?).

Input is `width`, `height`, `number of gaps`.

Example of finished grid:

```
1--1  0  4--4
|     |  |
1--1  0  4--4
   |  |     |
2  1  0  4--4
|     |
2  0--0  3--3
|           |
2--2  3--3--3

```

Example of grid with gaps:

```
0--0--0  2--2
      |     |
.  1  0  .  2
   |  |     |
1--1  0  2--2
|
1  .  3  3--3
|     |     |
1--1  3--3--3

```

# Answer
> 2 votes
I would suggest you look into tunnelling algorithms, which are used to generate random mazes.

The very basic algorithm is similar to a recursive back-tracker algorithm:

```
currentCell = startCell

do {
    tempcell=currentCell
    for each direction (up/down/left/right) do {

        if tempCell+direction is valid(inside maze, not already tunnelled) {
            currentCell = tempCell+direction
            currentCell.previous = tempCell
            end loop
        }
    }
    if(tempCell== currentCell) {// no new path selected. backtrack
        currentCell = currentCell.previous
    }
} while (currentCell != startCell)

```

You can modify this algorithm to have some custom additional constraints, such as making sure that there is not another tunnelled cell within X cells, which would create gaps.

This is a very rough way to do it. There is a ton of online material about it, which I suggest you read.

# Answer
> 2 votes
This question may be a better fit for the comp sci SE or the math SE as it leans on some non-trivial theoretical CS / combinatorics. If you need truly unbiased behavior, you'll probably need to ask over there. That being said, I suspect that may not be what you want though. for instance, as stated, your problem description would allow things like a 4x5 area divided into 20 paths of size 1, or a 4x5 area with 19 gap tiles.

The solution presented here does not provided that level of unbiased behavior. Here's the overview of a solution:

* Select your gap tiles.
* Build a spanning tree of the remaining area(s). Since the gaps are random & it's possible that they might partition the initial area into two disjoint regions.
* For each spanning tree, examine every intersection & modify the connectivity such that it connects at most two adjacent cells.
* Finally, examine each resulting path & consider splitting it as needed. As an extreme example, it's possible that your initial spanning tree has no branches (that is, it's a long serpentine path that fills the whole area); if that's undesirable, use some max length & subdivide the paths such that no region exceeds your threshold. Ensuring a minimum path length is not entirely possible with this approach; I suspect adding such a constraint results in a much harder problem that scales very poorly.

Here's an example, where * indicates a cell & . indicates a gap. Randomly pick some gaps:

```
*  *  *  *  *

*  .  *  .  *

*  *  *  *  *

*  *  *  .  *

```

Next, build a spanning tree. The only two ways to produce unbiased spanning trees (& by extension, unbiased mazes) are Wilson's algorithm or the Aldous-Broder algorithm (or a cross-over version that starts with one & switches to the other in an attempt to speed it up). If you don't need truly unbiased techniques, Kruskal's algorithm is pretty good & much faster. Jamis Buck's *Mazes for Programmers* is a great resource that covers the biases of numerous maze algorithms.

---

To address the minimum length constraint raised via comments: Favoring longer paths is a bias. In that case you, you should try either the recursive backtracker (RB) algorithm or the hunt-and-kill (H&K) algorithm for building your spanning trees. Truly unbiased algorithms have ~30% dead ends & ~22% dead ends. In contrast, the RB & H&K algorithms are have ~10% dead ends & intersections. That should correlate to longer paths. On average RB gives tends to have a longest path that's approximately double that of the longest path from H&K, thus RB biases 1 long path & many shorter paths whereas H&K biases towards more average length paths. Try both, run some tests & see if one work better. If you like both, use both & pick between them at run time, either randomly or based on the output. Also, the biases & %'s reported are for grids without gaps - I anticipate similar results with gaps, but the results may vary.

---

To continue, here's a possible spanning tree with the intersections labelled for later use:

```
*--*  *--*--*
|           |
*  .  *  .  *
|     |     |
*--A--B--*--C
   |  |     |
*--*  *  .  *

```

Next break the intersections. There are a couple of different ways to do this, each with some tradeoffs. Probably the least biased way is to first select the count (1-3 for a 3-way intersection, 2-4 for a 4-way) & then select the directions. Obviously breaking N connections on an N-way intersection will orphan the connecting node to a path of size 1. Alternatively, you could lower the max, thus ensuring that the connecting node attaches to at least one other node. This can still orphan other nodes, but that can sometimes be fixed as a post processing step if desired.

Starting with A, there are connections going Left Right & Down. Randomly select how many to break (1 or 2) & then randomly select that many. Let's say we break L & D, the result is now:

```
*--*  *--*--*
|           |
*  .  *  .  *
|     |     |
*  *--B--*--C
      |     |
*--*  *  .  *

```

At B, I'll break U & D. At C I'll break L, resulting in:

```
*--*  W--*--*
|           |
*  .  Y  .  *
|           |
*  *--*--*  *
            |
*--X  Z  .  *

```

Note that Y & Z are orphaned. In this case, it's possible to join them to W & X respectively, but in general you cannot guarantee you'll have such options. You could attempt to find a different spanning tree, but that may not help as it's possible that some nodes may start as orphans:

```
*  .  *  *  *

.  .  *  .  *

*  *  *  *  *

```

Ultimately, it depends on what you're making. For most games, any reasonably balanced (even if subtly biased) solution is probably going to be good enough. If not, request migration to the comp sci SE or the math SE.

---
Tags: algorithm, grid, random
---


# Question
Title: Any reason 3D character models aren't split into multiple models / files?
I'm just curious if there as any reason why artists are so resistant to split their 3D models into multiple fbx files. I just find the code design much cleaner if 3D models are split up into multiple files, rather than having to dig through bone hierarchies to choose different parts of a model the code needs to control. Something similar is the 2D project layout with characters broken into different sprites, and being able to grab those by name. (I get that the artist can name bones to make the search nicer, but a search still needs to be done instead of giving a path) So, I get that it has to do with animating movement, but why can't that be split into multiple files? (For a maya workflow at least)

# Answer
> 2 votes
Splitting meshes would work as you intend only if every polygon in the mesh is influenced by no more than 1 bone.

If you want the model to bend smoothly polygons need to be influenced by more than one bone so your different parts will have more than one bone and require a search just the same.

Here's an example of bone-weighting with just 5 of the bones selected (in colour)

If we look closer at the pelvic area we can see a triangle affected by 4 bones at once:

Isolated we can see the blend of 4 bones represented by 4 colours:

This means it's not possible to break down the mesh strickly by bones attached.

It would also cause a performance issue in most cases as each batch of triangles would need to be drawn in a separate draw call in order to change the set of bones affecting the part currently being rendered.

Having the entire mesh as one object allows the GPU to deform (animate) and draw the whole mesh all at once.

---
Tags: 2d, 3d, software-engineering, art
---


# Question
Title: What Scala-oriented game frameworks exist?
I'm looking into Scala game development, and wondering if there are any game frameworks oriented towards it, rather than Java.

Java has Slick2D and LWJGL, but they do not take advantage of Scala features.

# Answer
> 3 votes
There isn't much in the way of game specific frameworks/engines. What does exist is largely immature though can help provide a higher level of abstraction for rendering:

* Sgine - http://www.sgine.org \- This one has been undergoing a rewrite for a long period of time, I woulnd't count on this one for anything practical anytime soon. I looked at this early on in creating my game, and while it looked extremely productive for tiny projects, I decided not to use it after finding too many core problems in my mind to justify it's use in anything substantial.
* Simplex3D - http://code.google.com/p/simplex3d \- Provides math, data binding and rendering libraries, I haven't used this one, but it looks solid for what it provides.
* Scage - https://github.com/dunnololda/scage \- 2D only, I have little familiarity with this project, it seems tailored to small projects, the network api looks neat though.

I've built an engine directly on top of LWJGL over the past year. In retrospect it seems to have been a good idea. I honestly can't imagine using anything but Scala at this point (though except maybe Rust one day in the far future). I simply couldn't stand to use something as unproductive as Java or C++ again.

Not that it's a great measure of size, but my game including the engine/framework is approx 440 scala classes.

A side note: The game libraries suffer from similar problems to Scala libraries as a whole, especially in their (and in some way Scala's) relative immaturity, they're all written in their own interpretation of how Scala code should be written (something which is very diverse amongst scala libraries).

# Answer
> 2 votes
I do not know what specific features of scala you'd like to see in a game lib. My gut-feel says it is better to use a well known and fully functional java engine than a new scala one. Using java libs out of the box is one of the "specific features" of scala ;-).

A while back, I wrote a small game in Scala using the GTGE. I can really recommend it. The scala source code is on launchpad if you'd like to take a look before using it.

# Answer
> 0 votes
The best way to keep up with this now will be to peruse (and update) the awesome list on ScalaGameDev. The site also aims to host discussion related to Scala game development using (currently) gitter, though this was just created..

---
Tags: scala
---


# Question
Title: How to end a game when player picks up certain number of objects
I've got a small maze game where the player has to find a certain number of objects. If the player find all of them, I want the game to end. For now, I just simply want it to stop gameplay completely. I'll worry about ending it elegantly later. This is what I have, but I can't figure out what to put in the if statement. I can't seem to find a simple game state end function or anything like that. (Not really a whole lot of code to show for this. If for some reason someone needs to see more, please let me know and I can post other code, I just don't think anything else is relevant).

```
void APlayerCharacter::Tick(float DeltaTime)
{
    Super::Tick(DeltaTime);

    if (Score == 5)
    {
        //WHAT CAN I PUT HERE TO END GAME????
    }

}

```

# Answer
> 0 votes
Here is something you might try.

They propose this function call:

`FPlatformProcess::RequestExit(false);`

In any case, it's a pretty bad idea doing this check in the `Tick` function. If you are picking objects, it's better to check if you got all the objects you need in the collider method, so you do it once every time you get a new object, not every tick.

Greetings

---
Tags: c++, unreal-4
---


# Question
Title: Ogre3d 2.1 - How to apply texture on mesh?
I have searched forums and tried to read the Ogre 2.1 samples, but I still have no clue how to apply texture on mesh :(

Here what I've done so far.

1. I use Easy Ogre Exporter to export the scene (actually I just need the model and texture). I got the following files:
    * modelRoot.mesh
    * modelRoot.skeleton
    * model.material
    * model.tga

Note: I also use OgreMeshTool\_d.exe to upgrade the mesh from v1 to v2.

2. I render this model into Ogre:

In the file resources2.cfg:

```
[Essential]
Zip=../Data/DebugPack.zip

```

I add the model files (4 files I got from Easy Ogre Exporter at step 1 above) into DebugPack.zip file.

And I use this code to add the model into the Ogre scene

```
void MeshHelper::CreateMesh(Ogre::String szFileName, Ogre::Vector3* scale)
{
    /*Bring the mesh to scene*/
    m_meshItem = m_sceneManager->createItem(szFileName,
        Ogre::ResourceGroupManager::
        AUTODETECT_RESOURCE_GROUP_NAME,
        Ogre::SCENE_DYNAMIC);
    m_meshSceneNode = m_sceneManager->getRootSceneNode(Ogre::SCENE_DYNAMIC)->
        createChildSceneNode(Ogre::SCENE_DYNAMIC);
    m_meshSceneNode->attachObject(m_meshItem);
    if (nullptr != scale)
        m_meshSceneNode->scale(scale->x, scale->y, scale->z);
}
...
meshHelper.CreateMesh("modelRoot.mesh", &meshScale);

```

But I can only render the model without texture :(

Please help me to apply these texture into my model

* model.material
* model.tga

Thanks for reading :)

# Answer
Oh boy, finally I discover how Ogre apply texture on mesh.

Ogre just read the mesh file (.mesh), then read the skeleton file (.skeleton), then read the material file, the material file (.material) tells Ogre where is the texture file for this mesh, then Ogre read the texture file (.tga). So in C++ code, just tell Ogre where is the mesh file is enough.

The problem here is the file model.material, which Easy Ogre Exporter generated, is outdated to Ogre 2.1. So Ogre did read this file, but it didn't accept the format of this file. All I have to do is read other material file format in Ogre 2.1's sample to learn the format so that I can re-write this material file (model.material).

Currently, in Ogre 2.1, the model.material should be fixed like this:

```
hlms modelMaterial__46 pbs
{
    roughness   0.4
    fresnel     1.33

    diffuse_map     model.tga
}

```

Note:

* modelMaterial\__46 is the material name generated by Easy Ogre Exporter, better keep the name because the mesh file (modelRoot.mesh) recognize this name. Maybe in your case, it is other name (for example: modelMaterial\__69)
* model.tga is the file name of the texture file, of course :)
> 0 votes

---
Tags: textures, 3d-meshes, ogre, 3d-modeling
---


title: SIMD C++ library

text:
# Question
Title: SIMD C++ library
In the past, I've used Visual Studio with the DirectX XNA math library. Now, I'm using the GNU compiler collection. Can anyone advise a SIMD math library with a good documentation?

# Answer
You can also do it "yourself" using the **SSE (Streaming SIMD Extensions) instructions** and the **intrinsics** ( \*mmintrin.h files ) of your compiler/proc.

---

**Tutorials**

Here is an example of how to use SSE instructions with assembly:
http://neilkemp.us/src/sse\_tutorial/sse\_tutorial.html

And here is a tutorial on how to use SSE instructions with intrinsics:
http://www.codeproject.com/KB/recipes/sseintro.aspx

A practical guide to using SSE SIMD with C++:
http://sci.tuomastonteri.fi/programming/sse/printable

---

**Useful informations**

Intel C++ Intrinsics reference (useful to get the list of instructions):
http://cache-www.intel.com/cd/00/00/34/76/347603\_347603.pdf

SSE & SSE2 Intrinsic support for the enhanced instruction sets supported by Intel and AMD processors (useful to all kinds of informations relative to SSE and SIMD):
http://msdn.microsoft.com/en-us/library/y0dh78ez%28v=vs.71%29.aspx

Overall instructions list and informations about SSE, SSE2, SSE3, SSSE3, SSE4, 3DNow etc (different versions of SSE for different proc architecture):
http://softpixel.com/~cwright/programming/simd/sse.php

---

If you prefer a **linear algebra framework** I eared about Eigen:
http://eigen.tuxfamily.org/
http://eigen.tuxfamily.org/index.php?title=FAQ#Vectorization (about SIMD support)

And finally if you need more answers about C++ SIMD Frameworks, here is a **StackOverflow link**. (C++ SSE SIMD framework) :
https://stackoverflow.com/questions/4953121/c-sse-simd-framework
> 15 votes

# Answer
Both of these vector/matrix-libs have optimized SSE2 code, Sony also has an Altivec for PowerPC compile switch:

1. Sony's vectormath SSE2 and Altivec
2. Bullet's Linearmath SSE2
> 3 votes

# Answer
by a little seraching i think you can use bullet's math library, bullet itself is an opensource physics engine and it seems to have a powerfull math library beside it. here is a shortcut to download link http://sourceforge.net/projects/bullet/files/SIMD%20and%20amp\_%20Vector%20Math%20library/simd%20math%201.02%20and%20vector%20math%201.01/simdvectormath.tgz/download
> 1 votes

# Answer
It is not here yet. But there will be a boost.simd library (hopefully). Take look at this presentation (given last week at boostcon)

https://github.com/boostcon/2011\_presentations/blob/master/thu/simd.pdf
> 1 votes

# Answer
AMD has the open source SSEPlus project, although I have never used it so I can't comment on its quality or applicability.
> 0 votes

# Answer
While not exactly focused on using SIMD, I find glm to be a very good general-purpose math library when it comes to games. It doesn't support arbitrary matrices and the like, but it has streamlined features to be used with 3D graphics and it has features to enable SSE as well as some faster implementations of common algorithms.

While it is specifically designed to be used with OpenGL, I have found it to be very useful for a variety of tasks. It heavily uses operator overloading which makes it very easy to use and maintain the code that uses it.

It is based on the OpenGL GLSL language, which has very solid documentation, and any differences are well documented too.
> 0 votes

---
Tags: c++, mathematics, simd
---


# Question
Title: Suspend user interaction in unity during animation
What is the best way to suspend user interaction during an animation in Unity? Is there any standard technique that good games use.

E.g. In case of a card game, I am trying to flip a card. But if I click on the card in quick succession, it messes up the game.

Thanks!

# Answer
> 2 votes
If you are using an Animator controller, then I imagine you could so something similar to Hamza Hasan's answer in this other question. Set up two states, one idle, when you accept user input, and one animating. Transition to the animation when you set a trigger, let's say `FlipCard`. Transition back to idle automatically when the animation finishes. Now your code will look something like this, modified from Hamza Hasan's answer:

```
public Animator anim;

//condition for whether input is allowed
bool canFlip = true;

void OnMouseDown() {
    if (canFlip) {
        canFlip = false;
        anim.SetTrigger("FlipCard");
        //call coroutine which will handle resetting the state after
        StartCoroutine("FinishAnimation");
    }
}

//a coroutine. Will keep coming back to continue this code without
//blocking other code.
IEnumerator FinishAnimation() {
    //waits at this loop while the animation is still running
    while(anim.GetCurrentAnimatorStateInfo(0).normalizedTime < 1.0f) {
        yield return null;
    }
    //if we get here, the animation is complete
    canFlip = true;
}

```

---
Tags: unity, animation
---