# Question
Title: Anti-cheat Javascript for browser/HTML5 game
I'm planning on venturing on making a single player action rpg in js/html5, and I'd like to prevent cheating. I don't need 100% protection, since it's not going to be a multiplayer game, but I want some level of protection.

So what strategies you suggest beyond minify and obfuscation?

I wouldn't bother to make some server side simple checking, but I don't want to go the Diablo 3 path keeping all my game state changes on the server side.

Since it's going to be a rpg of sorts I came up with the idea of making a stats inspector that checks abrupt changes in their values, but I'm not sure how it consistent and trusty it can be.

What about variables and functions escopes? Working on smaller escopes whenever possible is safer, but it's worth the effort?

Is there anyway for the javascript to self inspect it's text, like in a checksum?

There are browser specific solutions? I wouldn't bother to restrain it for Chrome only in the early builds.

# Answer
The short answer is you can't do it. Anything that runs client side, especially from source, can be modified to defeat your tactics trivially. If you put in place a client side checker to look for abrupt changes, a user can just disable the checker.

The good news is that, generally, there is very little cheating on single-player games. The only major exception being for games that have large "youtube highscore" communities like Line Rider, where players compete with each other over YouTube.

If you are aiming for that, or are just too stubborn to accept that people might cheat in the game, or are keeping high-scores yourself (which is a form of multiplayer) then what you must do is all of the calculations server-side. Yes, everything that matters. You can't even repeat the calculation client side to try to give the user the score and then 'verify' it with the server because the user can then just disable the check and disable any system that ensures there are checks.

I wish there was a better answer to this, but there isn't.

That said, there are things you can do to make it a little harder to cheat. They will not stop anyone serious from doing it and releasing a toolkit to cheat, but it will slow them down:

* Minify and Obfuscate your JS, which absolutely will make the code harder to read. You can de-minify and sort-of de-obfuscate but you can never get back the right variable and function names, nor comments.
* Bake in values with a different language. In this case you can use PHP or other server side languages to handle static setup variables. If the jump distance is always supposed to be 2 spaces, normally you'd define a jump distance for the player object. Don't, handle that with PHP so that the JS source ends up with 2s plastered all over the code in a million places. This has the happy additional side effect of being able to speed up your JS too.
* With some practice, you'll get proficient with the mix and you can even custom-build your JS for each player. Which is another way to prevent cheating. If each player's code is different somehow, then it is harder to write a cheat that can be part of a toolkit.
* Finally, you can checksum the source based on the player's identity. Say their IP address and/or username. You know what the player-specific version of the JS will be, you can bake in a checksum and require that it be the same on the other end. Easy to disable like any client-side JS, but once again makes it a little harder to make a toolkit.

So. As you see, it is probably not worth it to go this route. It is hard. Requires a lot of really silly coding practices to do, and is ultimately still relatively easy to defeat. You'll need to do all the calculations server-side to prevent cheating. Or let go, and accept that cheating will happen.
> 46 votes

# Answer
I already answered a question like that here, and I'm sorry to tell but:

> I wouldn't bother to make some server side simple checking, but I don't want to go the Diablo 3 path keeping all my game state changes on the server side.

Is the baddest thing you could have say here. If you wanna do an "anti-cheat" engine, you'll have to do that. You can add anything you want client-side, to facilitate the server-side work, but you must never trust the client. All Logic you have must be at least server-side. You can reproduce it client-side if you want, but no client-side only solution will do it.

And by the way, if you wanna find the weakness of your program, don't obfuscate it, let people see your code and tell you "here, you have an issue".

That's good for you, for your code, for your users and for the community.
> 15 votes

# Answer
Well, a good place to start is to use the Object.freeze function (which will enable protection against object patching).

This "prevents new properties from being added", "prevents existing properties from being removed", "prevents existing properties, or their enumerability, configurability, or writability, from being changed"; any changes to the internal state should be done through accessors. The following example works on chrome (should work on firefox, I dont know about IE though...):

```
var b = {}
// Fill your object with whatever you want
b.a = "ewq"
// Freeze all changes
Object.freeze(b)
// Try to put new value. This wont throw any error, put wont work either,
// as we shall see ...
b.b = "qwe"

// Values
console.log(b.a); // outputs "eqw"
console.log(b.b); // outputs  undefined

```
> 3 votes

# Answer
unfortunately, you have to go the diablo 3 path, if you are really concerned about hacks/cheats. if you are not, then basic checks you must do or its strongly advised to do.

* buy checks - If I am buying something, I should have enough gold
* sellchecks - If I am selling something, I need to have that item in my inventory trade checks - same as sell weapon
* equip checks - If I am equipping a weapon, do i have/own it?
* damage checks - If I am attacking something (enemy), I can't hit more than the maximum damage my weapon could(here you should not expect the client to tell which weapon he has used because it should have been persisted earlier)
* crafting checks - If I crafted something, do I have all ingredients/components required?

... and so on

1 point is little bit tricky is the hero's position, since you are not much worried about it you can leave it, but its better you do that too with a minimum check like one below

* I am at place1 @ T1, I am at place2 T2, what is the minimum time it takes to travel from place1 to place2 and it matches my T2 - T1. You can have mapping of this from small to large depending on the map size. You should have list of at least major areas like, NPC - boss, NPC - enemy spawn area (not necessarily exact location)

Hope this helps, it sounds difficult but you need to learn to make real working games
> 2 votes

# Answer
Its basically not possible. It would be so easy to work around anything you put in place to prevent cheating.

The thing is with any software you distribute people can modify it in memory easily.

Besides if they want to cheat, let them. They're just ruining the game for themselves. There's no real practical use to cheat in this situation, you'd just destroy the gameplay for yourself.
> 1 votes

# Answer
I had an idea for a measure you could take to prevent/reduce cheating (in addition to other answers). You could have it set up so that the client is not given all the source code at one time, rather that every time the client wants to, say, purchase a new item in the store, that the client would have to send certain information to the server, and only recieve all the information for whatever they are purchasing if the information all matches up with what it's supposed to. If it doesn't, the server blacklists their IP or something.

You could use this in conjunction with what Dampes8n said about using different source versions, that if you can figure out a way to generate a lot of different versions, so that each user would be running an entirely different source version each time, that failing the check blacklists that source version, too, that it won't ever give out the correct item info for that source version ever again.

The main reason this would be effective is that if a hacker doesn't get the hack right the first time, this would make it much harder for them to modify the hack, because every time the hack doesn't work perfectly, they have to change their IP and write the hack all over again for the new source version.
> 1 votes

# Answer
Yes, it can't *fully* be done. Always have check on the server. Anything that has an impact on the game should require authorization from the server.

*That is the extend to which I will repeat other answers.*

However, we can do a lot more towards the end of preventing cheats than just checking on the server. *Well, we might have to add some special server checks.* However, be aware that client side checks are not worthless, they save bandwidth and server work when cheaters are not involved.

With that said:

* Mitigate rough clients: Serve over HTTPS, use Cross-origin resource sharing (CORS), allow only the same origin, use subresource integrity. I suggest to implement a service worker to enforce it on all requests, which will also mean that the game won't work by simply moving it to HTTP (because without HTTPS there is no service worker, the server worker is doing the client part of CORS and the server expects CORS), and if they serve over HTTPS it won't work because the server will reject the other origin.
* Mitigate scripting: Use authentication and require a token to do any action. Each update cycle the server should give the client a new token, and the token is consumed by doing whatever it does... doing anything requires a valid token, the token is always changing, and thus not viable to guess, and if the client sends the same token twice or sends a wrong token the server knows that something is up. For extra protection: create a Message authentication code (MAC) of the token with a secret key and add it to te cookie. Modifying the cookie will kill the session (and they need to guess the key), and modifying the token will make the MAC check fail.
* Mitigate code modifications: Aside from subresource integrity (which modern browsers will also check in runtime), keep your variables under a limited scope (using let, self executing anonymous functions, and javascript modules). Also, not rely on the DOM (the DOM is for IO only, not storage, if you need to attach attributes wrap your DOM objects and add them to wrappers). This way, whatever you on console should not be able to reach game logic (unless you exploit some browser vulnerability). You might also consider using techniques to detect developer tools (these are specific per browser, and may not work in all cases or stop working in the future... thus, this is an arms race).
* Something is up? Did the session break? Kick the player from the current match, request to login again. Consider a captcha... that also has the benefit of telling the user that *"we know something rare is going on"* (it was not a random server failure), and yes, that is a form of mitigation. *Oh, and do not foget to log these. You need to be able to verify why they happened, both to prevent false postives and to answer support tickets.*

Yes, this are all mitigations. We can still have a custom made browser that will not check integrity and let you reach and mess with variables in local scopes... then the game code will send the modified data with the right token, and that is where the server checks come into play.
> 0 votes

---
Tags: javascript, html5, security
---


# Question
Title: Tangent space normal mapping visual problem along UV islands (using Vulkan)
I'm learning Vulkan and computer graphics. First time implementing normal mapping. I've been struggling with this for days now and I can't seem to find the problem - so that's the question. What is wrong here and how to fix it?

First, here is a short description of how I handle things. On the CPU I calculate MVP and inverse M matrices, with the inverse M I transform the eye position and light positions from world to model space. Then I pass the MVP and model space positions to the vertex shader via a uniform buffer. The vertex shader calculates light vectors (vector from vertex position to light position) and the eye vector and transforms them to tangent space with the inverse TBN matrix (the shader gets the vectors T, B and N from the CPU via input attributes). This is then passed through the rasterizer to the fragment shader, from which point things are straight forward.

As one might imagine, the differently illuminated areas are UV islands.

The lighting still changes based on the position of the model.

Here's a picture of tangent space bases and light vectors in model space for each vertex. The bases are different for the double vertices along the seams, but that is expected due to different UV coordinates. The light vectors should still be valid in each tangent space (after being transformed by the inverse TBN matrix).

This is a color representation of one of the light vectors. There is a clear correlation between these vectors and the lighting problem. But as far as I can tell the change in color (in this image) along the seams is expected because the tangent spaces are orientated differently. One thing to note is the front right leg of the turtle - depending on the orientation of the turtle, some parts of some islands will be black for whatever reason.

Now, here is the relevant code:

vertex shader

```
#version 450
#extension GL_ARB_separate_shader_objects : enable
#extension GL_ARB_shading_language_420pack : enable

#define lightCount 2

layout(location = 0) in vec3 inPos;
layout(location = 1) in vec2 inUV;
layout(location = 2) in vec3 inNormal;
layout(location = 3) in vec3 inTangent;
layout(location = 4) in vec3 inBitangent;

layout(set = 0, binding = 0) uniform VSUniformBufferObject {
    mat4 MVP;
    vec4 eyePos;
    vec4 lightPos[lightCount];
} ubo;

layout(location = 0) out vec2 outUV;
layout(location = 1) out vec3 outEyeVec;
layout(location = 2) out vec3 outLightVec[lightCount];

out gl_PerVertex {
    vec4 gl_Position;
};

void main() {
    gl_Position = ubo.MVP * vec4(inPos,  1.0);

    outUV = inUV;

    mat3 invTBN = transpose(mat3(inTangent, inBitangent, inNormal));

    outEyeVec = invTBN * (ubo.eyePos.xyz - inPos);
    for (int i = 0; i < lightCount; i++) {
        outLightVec[i] = invTBN * (ubo.lightPos[i].xyz - inPos);
    }
}

```

all the input attributes are in model space

fragment shader

```
#version 450
#extension GL_ARB_separate_shader_objects : enable
#extension GL_ARB_shading_language_420pack : enable

#define lightCount 2

layout(location = 0) in vec2 inUV;
layout(location = 1) in vec3 inEyeVec;
layout(location = 2) in vec3 inLightVec[lightCount];

layout(set = 2, binding = 0) uniform sampler2D samplers[2];
layout(set = 1, binding = 0) uniform FSUniformBufferObject {
    vec4 lightColors[lightCount];
} ubo;

layout(push_constant) uniform PushConstants {
    int mode;
} push;

layout(location = 0) out vec4 outColor;

const vec4 ambientComponent = vec4(0.05, 0.05, 0.05, 1.0);
const float maxDistance = 5.0;

void main() {
    vec4 texColor = texture(samplers[0], inUV);
    vec3 texNormal = texture(samplers[1], inUV).xyz;

    vec3 N = normalize(texNormal);
    float distance = length(inEyeVec);
    vec3 E = inEyeVec / distance;

    vec3 diffuseIncoming = vec3(0.0, 0.0, 0.0);
    vec3 specularComponent = vec3(0.0, 0.0, 0.0);
    for (int i = 0; i < lightCount; i++) {
        float D = length(inLightVec[i]);
        vec3 L = inLightVec[i] / D;
        D = (distance + D)*(distance + D);

        float cosTheta = max(dot(N, L), 0.0);
        diffuseIncoming += ubo.lightColors[i].rgb * cosTheta * ubo.lightColors[i].a / D;

        if(push.mode > 0) {
            vec3 R = reflect(-L, N);
            float cosAlpha = max(dot(E,R), 0.0);
            specularComponent += ubo.lightColors[i].rgb * pow(cosAlpha, push.mode) * ubo.lightColors[i].a / D;
        }
    }

    //outColor = texColor * (vec4(diffuseIncoming, 1.0) + ambientComponent) + vec4(specularComponent, 1.0);
    outColor = vec4(normalize(inLightVec[0]), 1.0);
}

```

push.mode is zero so the specular lighting is off

drawing commands

```
glm::mat4 VP = P * V;
glm::mat4 invM;
Rendering::VSUniformBufferObject vsubo;
for (auto obj : objs) {
    ModelInfo &m = modelInfos[obj.modelId];

    vsubo.MVP = VP * obj.M;
    invM = glm::inverse(obj.M);
    for (int i = 0; i < 2; i++) {
        vsubo.lightPos[i] = invM * lightPos[i];
    }
    vsubo.eyePos = invM * V[3];
    vsUniformBuffer_m.fill(0, sizeof(Rendering::VSUniformBufferObject), static_cast<const void *>(&vsubo));

    vkCmdBindDescriptorSets(b, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines_m.pipelineLayoutPtrs[0], 2, 1, descriptorPool_m.descriptorSets.data() + obj.textureId + 3, 0, nullptr);

    vkCmdDrawIndexed(b, m.size, 1, m.start, 0, 0);
}

```

EDIT 1:

I've rendered the dot product of N (normal vector) and L (light vector). The normal map itself looks fine - just like any other normal map, even when rendered onto the model. The light vector is correctly transformed into model space. As far as I can tell this means the only thing left that can be wrong is the calculation of the TBN matrix. I used blender to bake my normal map from multires. I'll append the code for T, B and N calculations.

```
std::unordered_map<Rendering::Vertex, uint32_t> uniqueVertices;

for (const auto& shape : shapes) {
    int i = 0;
    for (const auto& index : shape.mesh.indices) {
        Rendering::Vertex vertex = {};

        vertex.pos = {
            attrib.vertices[3 * index.vertex_index + 0],
            attrib.vertices[3 * index.vertex_index + 1],
            attrib.vertices[3 * index.vertex_index + 2]
        };

        vertex.uv = {
            attrib.texcoords[2 * index.texcoord_index + 0],
            1.0f - attrib.texcoords[2 * index.texcoord_index + 1]
        };

        vertex.normal = {
            attrib.normals[3 * index.normal_index + 0],
            attrib.normals[3 * index.normal_index + 1],
            attrib.normals[3 * index.normal_index + 2]
        };

        vertex.tangent = {};
        vertex.bitangent = {};

        if (uniqueVertices.count(vertex) == 0) {
            uniqueVertices[vertex] = static_cast<uint32_t>(vertices.size());
            vertices.push_back(vertex);
        }

        indices.push_back(uniqueVertices[vertex]);

        i++;
        if (!(i % 3)) {
            size_t indicesSize = indices.size();
            uint32_t i0 = indices[indicesSize - 3];
            uint32_t i1 = indices[indicesSize - 2];
            uint32_t i2 = indices[indicesSize - 1];
            Rendering::Vertex &v0 = vertices[i0];
            Rendering::Vertex &v1 = vertices[i1];
            Rendering::Vertex &v2 = vertices[i2];

            glm::vec2 duv1 = v1.uv - v0.uv;
            glm::vec2 duv2 = v2.uv - v0.uv;
            float k = 1 / (duv1.x*duv2.y - duv2.x*duv1.y);
            glm::mat2x2 UV(duv2.y, -duv1.y, -duv2.x, duv1.x);
            glm::mat2x3 E(v1.pos - v0.pos, v2.pos - v0.pos);
            glm::mat2x3 TB = k*E*UV;

            v0.tangent += TB[0];
            v0.bitangent += TB[1];
            v1.tangent += TB[0];
            v1.bitangent += TB[1];
            v2.tangent += TB[0];
            v2.bitangent += TB[1];
        }
    }
}

for (int i = 0; i < vertices.size(); i++) {
    vertices[i].tangent = glm::normalize(vertices[i].tangent);
    vertices[i].bitangent = glm::normalize(vertices[i].bitangent);
    glm::vec3 &T = vertices[i].tangent;
    glm::vec3 &B = vertices[i].bitangent;
    glm::vec3 &N = vertices[i].normal;
    T = glm::normalize(T - glm::dot(T, N) * N);
    B = glm::cross(N, T);
}

```

The comparison operator for the Vertex structure only compares position, normal and uv coordinates.

# Answer
> 0 votes
Turns out the problem was the way I interpreted the normal map. I was too focused on the transformations and it completely slipped my mind.

This:

```
vec3 texNormal = texture(samplers[1], inUV).xyz;

```

should have been this:

```
vec3 texNormal = 2.0 * texture(samplers[1], inUV).rgb - 1.0;

```

because (128, 128, 255) from the normal map maps to (0.0, 0.0, 1.0) in tangent space. So (128, 128, 128) would map to the origin - this would of course be an invalid normal, that's just how the coordinates from one space map to the other.

More details can be found here http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-13-normal-mapping/

---
Tags: glsl, normal-mapping, vulkan
---


# Question
Title: How can I determine which tiles in a tilemap an oriented bounding box (OBB) overlaps?
I need to detect collisions between an oriented bounding box and a static tile map. My tile map class looks something like this:

```
function Tilemap(width, height, tiles) {
    this.width = width;        // Width of the map in tiles
    this.height = height;      // Height of the map in tiles
    this.tiles = tiles;        // 1D array containing tiles, grouped by row
}

Tilemap.prototype.getTile = function (x, y) {
    return this.tiles[y * this.width + x];
};

Tilemap.prototype.setTile = function (x, y, value) {
    this.tiles[y * this.width + x] = value;
};

```

My question is this: How can I determine which tiles an OBB, represented as an array of vertices, overlaps?

(I am writing in JavaScript but answers for any language would be appreciated.)

# Answer
> 2 votes
You can approach this as a polygon rasterization problem.

Take the four lines that make up the edges of your bounding box and rasterize them to your tile grid using a line drawing algorithm like eg. DDA.

For each row of tiles marked this way, keep track of the leftmost and rightmost tile in that row that any of your lines touch. Then you can fill the box by including all tiles between these left & right extremes.

# Answer
> 0 votes
I guess you could do something like this:

```
var x_min = Math.floor(v[0] / this.width),
    y_min = Math.floor(v[1] / this.height),
    x_max = Math.ceil(v[2] / this.width),
    y_max = Math.ceil(v[3] / this.height);

```

In this case, the tiles are all the ones from `getTile(x, y)` where `x` is between `x_min` and `x_max` and `v` is your selection box.

---
Tags: collision-detection, javascript, tilemap
---


title: libGDX 3D texture is stretched

text:
# Question
Title: libGDX 3D texture is stretched
I'm working on a 3D maze game using libGDX. I'm using MeshBuilder to render the walls. All walls are a single part made using a ModelBuilder in the create():

```
    ModelBuilder modelBuilder = new ModelBuilder();
    MeshPartBuilder meshBuilder;
    Vector3 corner00 = new Vector3(),
            corner10 = new Vector3(),
            corner11 = new Vector3(),
            corner01 = new Vector3(),
            normal = new Vector3();
    modelBuilder.begin();

    Texture wallTexture = new Texture("wall.PNG");
    wallTexture.setWrap(Texture.TextureWrap.Repeat, Texture.TextureWrap.Repeat);
    wallTexture.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
    Material material = new Material(new Material(TextureAttribute.createDiffuse(wallTexture)));
    meshBuilder = modelBuilder.part("room1", GL20.GL_TRIANGLES,
            VertexAttributes.Usage.Position | VertexAttributes.Usage.Normal |
                    VertexAttributes.Usage.TextureCoordinates, material);
    Array<Wall> walls = level.getWalls();
    for (Wall wall : walls) {
        Vertex v1 = wall.getV1();
        Vertex v2 = wall.getV2();
        meshBuilder.rect(corner00.set(v1.getX(), v1.getY(), 0), corner10.set(v2.getX(), v2.getY(), 0),
                corner11.set(v2.getX(), v2.getY(), 10), corner01.set(v1.getX(), v1.getY(), 10),
                normal.set(wall.getNormal(), 0));
    }
    Model worldModel = modelBuilder.end();
    instance = new ModelInstance(worldModel);

```

I do this in order to decrease the number of draw calls. But I came across a texture-mapping problem:  The wall texture is stretched. How can I make it repeat the texture instead of stretching? Thanks

# Answer
After spending time learning more the libGDX 3D structure, I managed to fix it:

```
meshBuilder.setUVRange(0,0,Gdx.graphics.getWidth()/wallTexture.getWidth(),1)

```

While building the mesh part, I set the UV range from (0,0) to (n,1) - n is the number of times the texture image can fit inside the rect.
> 1 votes

---
Tags: java, libgdx, 3d, textures, maze
---


# Question
Title: How can I make my players interested in the game lore of my MMORPG?
In WoW (World of Warcraft), players skip all quest descriptions, and mindlessly spam "auto attack button", ignore the environment, lore, NPCs as they never existed. I.e., they enter a brain dead "mode". If you ask someone of them what he saw, he won't be able to remember a thing. Except the "Lvl 60" number.

I noticed that in my game, if I include lot of mobs i.e. 1 pack for every 10 seconds of distance traveled, the same effect happens. Players ignore all lore and are inflicted with amnesia.

I also noticed that if my dungeon starts empty e.g. the first 30 meters completely barren of mobs, the players go Lore heavy mode and spend every inch and cranny to find everything.

**Question:** How can I make a player switch to Normal Brain mode (craves for lore) after a group of enemies have been killed?

# Answer
> 25 votes
While the other answers give you good advice how to achieve your stated goal, I'd like you to consider a different angle.

# Experience vs. Test of Skill

Games can be put on an axis that goes from "experience" to "test of skill". All the old arcade games are almost completely on the "test of skill" side. Understandable, if the player being upset is not as important as that he just put 14 coins in the machine. However, coins are completely irrelevant for gaming at home, while word of mouth or a journalist saying they really enjoyed it (= the experience) could boost your sales. Games always have at least a bit of both though. The issue you describe is a clash of the two.

Your players are in "test of skill" mode, which is a lot like sports. You are "on edge", stuck to the controls, constantly making new decision. Missing the right moment would have bad consequences. If there's some text irrelevant to the current chaos, you just want to get rid of it, so you can focus on the task at hand again.

Now you want them to read the lore, which is more on the "experience" side: Sit back in the chair, scratch that itch you had, take a sip from your drink. That's quite a mood change, and that's not *too* easy for the brain. To be honest, when I read "every 10 seconds", that sounded incredibly stressful at first.

# Solution

So my advice would be to **make the switch less frequent**.

### Safe vs. unsafe Locations

For example, look at how a lot of RPGs do it: Display most of the lore in the safe city and then you go out to the wilderness for fighting. You fight through a dungeon without too many interruptions by lore. You defeat the boss and now the dungeon is *safe*, the player more at ease, so that's good timing to let the defeated boss reveal some more lore. But even then, in a lot of cases the bigger part of the story progression happens when you're back in the city.

# Story "to go"

Telling your story "on the way" is very entertaining though, don't bin that completely! It's actually really engaging if you go with the writing advice "show, don't tell": Instead of explaining in a text how the man is dead, he was shot by an arrow and from the arrow you see it was goblin, prefer to have your party *see* him being shot by a goblin when they enter the scene.

That's more work though, you'll have to decide if it's worth it. However, if it's not worth it, it's probably still better to have the player pick up a rune stone and the old wise man back in the city will decipher it later, instead of interrupting the fighting flow. This rune is then something they fought for, so they'll probably *want* to read it - just not right now.

Lowering the amount of switches between test of skill and experience will also make it less work for the players who only play for the technical part and just don't care about the story. **In the end, it's not like these people will pay less for your game because they aren't using it 100%.**

# Bonus

I'd advise you to have a look at Bartle's taxonomy of player types. For example, lore would generally not be as important to the "Killer" type ("They thrive on competition with other players"), but I'd expect more than a fair share of those in an MMORPG.

# EDIT - Healthy Mix

User Mooing Duck mentioned a game where story was narrated *while* you play the game. This made me realize that my answer could be interpreted more extreme than it was intended. So, just to be clear: "Experience" and "Test of Skill" are not an either-or thing - it's an axis and every moment in your game will be somewhere in between the two. The situations discussed previously were more towards either side of the axis, but that is not an issue. The issue was big change of where you are on the axis, done often and abrupt.

What Mooing Duck mentioned is more in the center. Being closer to the center allows you to make the switches smaller. Maybe you can even get rid of them altogether, which makes for a really coherent experience (the general meaning of the word "experience" this time).

However, you're working on an MMORPG. The people who are only interested in the sports part - taking down a boss with a team, repeatedly, because they want to get better at it - can be expected to make up a considerable part of your player base. If your narration is *only decent, but not great*, they might easily prefer no narration at all.

# Answer
> 40 votes
Players will mentally filter out any information which doesn't seem to be relevant for reaching the objective of the game. In an MMORPG, the objective is to level up and acquire equipment. All elements of the game are judged by how useful they are for achieving those objectives.

When following the game's narrative doesn't help to achieve these goals, then players will learn to ignore it.

However, there are games where players pay a lot more attention to the narrative. You can see that mostly in single player RPGs like the Mass Effect, Elder Scrolls or Fallout series. The reason is that these games prompt the player to make decisions based on the information they received through the narrative. And these decisions can have consequences, both narratively (e.g. "Which NPCs will agree or disagree with this course of action?") and mechanically (e.g. "What content will become available depending on my decision?"). So the player is forced to follow the narrative in order to obtain the information they need to make the decision they want to make.

So if you want your players to follow your narrative, make sure it contains information which is relevant for the decisions they have to make over the course of your game. Keep in mind that this is something you need to teach your players early and need to reinforce constantly. When you suddenly surprise the player with a decision in the middle of the game based on the narrative they were trained to ignore, they will rightfully feel cheated.

I'm looking forward to playing your game.

# Answer
> 20 votes
The simple answer is: you can't.

Some players enjoy lore, reading non-stop about a fantasy adventure and weird scenarios that unfold in front of them. Other players enjoy a hard puzzle that makes them think, without caring why they have to solve it. Others want to kill weak monsters and become stronger, so they can take down that one dragon that looked intimidating.

There is nothing you can do to stop this, and there is **nothing you should do**. Attempting to manipulate all players to think the same, will just make people hate your game.

I'm a person that do not enjoy reading a lot when playing video games. If there's lore, there's high chance I'll skip it. If the game developers decided I was a "brain-less zombie" and forced the text on my screen for several minutes, it's just my clue to close the game and throw it out of the window, as it's clearly not made for me (and people that think like me).

As long as players are having fun, why does it matter if they "have a brain" or not?

# Answer
> 14 votes
# Let them choose how much they see

Yes, they should be able to skip any dialogue, for those who want that, but that's pretty black and white - it tends to be either skip everything or skip nothing - it's hard or impossible to tell beforehand what would be actual useful or interesting information.

If you instead separate your dialogue into tiers, that could help matters:

* At the "base" tier, you have the core storyline, and a very brief message for optional quests.
* After this, players can either say "Ok" or some variant of "Tell me more" (ideally avoid an *actual* "tell me more" message, and have something an actual human being would ask in typical conversation).

# Stick to the interesting stuff

Some games might have really interesting lore, but then they start telling me about some farmer's wife who went to pick berries last night, but never came home, and how much they love each other, and how faithful she is, and that she always comes home, and it was close to this bandit camp, and he's very worried about her, etc., etc., etc. - at that point I not only stop caring about that specific piece of dialogue, but also *all* dialogue that game has.

Stick to what's actually interesting, don't just fill pages of text because you feel you need to explain every little thing in detail - a simple "Can you go look for my wife? She went to pick berries by the bandit camp." will do just fine if you don't have much interesting to say about that.

This also applies to your "main" lore - in some cases it might be better to remove some of the less important details in order to have a more concise and digestible story. Although finding a good balance between too few and too many details would probably be a topic all on its own. You can combine this with the point above - letting players choose how much they see.

# Split it into byte-sized chunks

Don't try to tell players a giant chunk of your lore all at once.

Let them regularly run into an NPC or book or whatever to give them a little more information.

Also try to stick to things that are actually relevant to what's currently happening.

# Do more than text scrolls

A game is not a book.

You'll lose the interest of a lot of players if you expect them to stop the game and just sit there and read for a while. Having a decent voice actor read the dialogue is much, much better, but still doesn't solve the underlying problem.

Instead, show them **cut-scenes** \- well, a game is not a movie either, but a cut-scene is much better than some NPC just standing there talking.

Or **have dialogue during gameplay**. This can either be a few words here or there, or it can be continuous speaking. Although there are a few caveats:

* **Players should actually hear it** \- in plenty of games the voice-over gets drowned out as soon as action happens.
* **Avoid multiple overlapping voice-overs**. This should go without saying, but some major releases have managed to get this wrong.
* **No conversations** here - it breaks immersion if you're going to have a conversation happen in the background when the character you're talking to is nowhere to be seen. It should be closer to someone telling a story.
* **Don't distract players** \- if you're trying to have an elaborate voice-over in the middle of an intense boss battle, that's not going to work (although you can still throw a line here and there). Also don't go to the other extreme and have the players just run with nothing else happening but the voice-over. It should be somewhere in between - some action, but nothing too distracting.
* **Have an NPC keep talking** \- this isn't a caveat, but rather an idea - when you start talking to an NPC, they will keep talking even if you run away. Be sure to keep in mind the caveats mentioned though (especially "no conversations").
* **Allow players to dismiss it, and disable it** \- if some dialogue is getting distracting, players should be able to stop it, and you should have an option so players who don't want to hear it don't have to stop *every* dialogue.

# Flavour text

One can tell an entire story using one or two sentences on every item, and players would feel kind of part of the story if they know this blade they're using belonged to that great warlord you told them about.

And maybe the item itself has an effect corresponding to what you said about that character.

# It's about the game world, too

Yes, your lore might be interesting, but it'll probably be quickly forgotten if the lore seems disconnected from the gameplay.

If, instead, the lore tells of this character who was in a war where he got his leg injured, and, when seeing this character, you can see the scar, they walk with a limp, and maybe this information is incorporated into a boss-fight with that character in some way, that's going to be much more memorable.

Or if you speak of a past civilization, and you could be cool to find some of their artifacts, some glyphs on walls, one of their cities, one of the last remaining members, etc.

Or the lore speaks of a great battle, and later you get to visit the site of the battle.

You could also have what you do affect the world - maybe you go back to a village after doing some quests for them, and you actually see the longer-term effects of what you did - maybe you find the villagers going further out into the forest after defeating the bandits.

The most important aspect here is perhaps **the effects of your overarching plot on the game world** \- if your story is about overthrowing some ruthless evil ruler, that wouldn't be very convincing if everyone you run into is just going about their day-to-day life, everything just looks "normal" and the quests are unrelated to this. It would be much more convincing if you constantly run into this ruler's soldiers, and especially find them tormenting the innocent, if you find some villages burnt to the ground and if the quests generally come about as a result of what the ruler did - either somewhat directly (kill some soldiers occupying a city) or indirectly (kill some bandits, which the villagers can't do themselves because the ruler enlisted or killed all able-bodied men in that village).

# You can't keep everyone interested

You just can't, some just care about the gameplay and that's okay.

# Answer
> 9 votes
I like TomTsagks answer.

But i want to add: make it obvious that there is lore to find. I really love lore, but if i'm in a dungeon i don't always expect it, so i'm not looking for it. It can get less obvious later on, but shot them, there can be something to find.

Use the lore to make the game easier. Give hints to puzzles, or to the weaknes of the next boss. This way people don't have to read it, but if they decide to look for lore and read it, they have an advantage.

# Answer
> 3 votes
How about including quests and puzzles that have optional, additional rewards that requires in game lore? This way, you reward them with the items that they desire and they will be paying attention to the lore of the game.

Here is an example. Imagine your game is in ancient Greece. Out of say 25 symbols, 3 symbols are sea, horse and trident. And the puzzle asks you to select 3 of these symbols.

**Edit as suggested by NotThatGuy:**

Indeed it is very difficult to balance these. However, there is a way to reduce the impact of any balancing issues. Say, if you earn two pieces of loot from the dungeon, a third piece would depend on the lore. Make it known upfront and make it optional with a timeout. So, if the player was paying attention, they will get the loot, if not, there will be no time to go back or google the answer. Also some sort of randomized question generation would help against google searches too.

# Answer
> 3 votes
A practical answer: **avoid long expositions**. People usually come to a *game* to *play*, not to read. If they wanted to read a wall of text, they would have grabbed a book. They may not be against reading some short stuff from time to time, but they won't stand walls of text in which you describe in a flowery fashion the same fantasy tropes and cliches they have read thousands of times before.

Usually in MMO themeparks, the fun starts when you are high level enough, after they have been burn out of bringing rat pelts to NPC, so time is gold, and nobody wants to take twice as long to read a slow-starting story to get to the good stuff, so they just skip the story for a while, and before they notice, they have skipped over all the non-superfluous bits of information that led them to the end game, and they understand nothing of what is happening in the climax, so they just keep skipping all the really interesting stuff, because without understanding the rest of the story, it is not as interesting. They still have a blast because the end game gameplay is worth it, and they haven't been burnt out by skipping quickly the early filler.

What I am trying to say is, if people want to play, they **will** play, and if people want to relax, wind down, and maybe kill some time reading, they will read. If you make your lore understandable in an "offline" or "asynchronous" fashion, **where the players go after your game's expositions after they are done with everything else and not the other way around** ("read my long speech on why I am so badass and the leader of our faction before going into that kickass battlefield to punch giant freaking monsters!"), many players will try to read in the inevitably long downtimes between activities, as long as the amount of exposition doesn't scare them (as in, don't write "ingame books" that are several pages long, because few players tend to read those). Making exposition happen on the "after-climax" parts of the game, in very spaced out two-paragraphs-at-absolute-most bits will increase the probability of people getting interested in your lore. People seem even more receptive to lore being delivered sentence by sentence (think Magic: The Gathering card descriptions, Dark Souls equipment description, etc), as it seems it is complicated to stop the brain from reading small bits of text, and before they realize, they will have read it whole, thus increasing their knowledge of the lore, and easily increasing the probabilities of them *caring* about the lore.

Another possible technique would be to make actual dialogues. One of the reasons many people skip NPC dialogues is because, well, they are not really dialogues, and because **they are playing to *live* their story, and not hear monologues about someone else's**. The player likes agency, which is why the player is playing a game and not watching a movie, **so why don't ask him to provide some input on what he thinks about what he is reading?** Given, the resulting dialogue tree will be complicated, but letting NPC talk in short bits, then asking the player how to respond with things that are not just meaningless yes/no options, or options to acquire more information that reveal more options to acquire more filler information, that could be perfectly skipped even by lore-addicted players if not for the actual quest-giving dialogue appearing only after all of them have been heard, could increase your player's engagement. Comes to mind a dialogue option in FTL: Faster Than Light, where the usually useless after the first reading flavour text describes a planet with X (where X is a random number) amount of moons, then asks the player in the next dialogue window how many moons there are. If they answer correctly, they are rewarded, otherwise, they are punished. This sends a clear signal and teaches the lesson that you should read the flavour texts more often, which would be integral to the game had it happened more often, but as it stands, it is mostly a "prank" on the developer's side. If, for the most part, you present your player with simple yes or no choices, where yes is always the good option, players will just learn to press Yes on every dialogue window; however, if you ask them whether they want to capture the Neutralnation's military supplies convoy and risk war, torture some Evilnation prisoners, or slap the NPC for their insolence, then maybe, just maybe, they will want to read the text above the dialogue options to find out why the hell you have reached this situation. In other words, people will be much, much more receptive to reading if it is showcased through CYOA mechanics, and choosing the "right" (or, probably better designed, all equally right, but differently interesting to different kinds of players) options truly matters to decide what will happen next.

Alternatively, **offer your lore passively via showing, not telling**. If your player sees two massive stone statues of giants clashing their swords in the background, where each of them looks like the statues you can find in many temples dedicated to different gods, they will understand that there were conflicts between these two gods almost instinctively. They may understand these are not regular statues, and in fact are the bodies of these two gods, who fought for so long, they both petrified before even being able to finish the fight; maybe some players will need extra pointers to understand something this specific, but all of them will begin to understand why the followers of each of these two gods are enemies. And it just took them a few seconds of looking around to reach this conclusion without suffering through paragraphs and paragraphs of purple prose! Wow, that's efficient!

# Answer
> 1 votes
There are a few ways I can think of to make lore "easier" on your players:

* Try to use cut-scenes or spoken dialogue over written text. If you absolutely need text, the Nielsen Norman group did an article on making text targeted towards lower literacy users.
* Try to limit the amount of lore used in your game. Normally in a movie, lore is only revealed when it is necessary to the story. So if you're facing a boss or entering a new area, you may be able to expose lore as a hint rather than an info dump.
* If you use cut-scenes and/or spoken dialogue, try and place longer media after strenuous events. If you've just managed to defeat a boss that's taken multiple lives to beat, you'll be more inclined to relax your fingers and watch a cut-scene.
* Humor, while not appropriate in every situation, can make people want to listen to lore, if only for an ironic laugh once in a while. (Bonus Points: If a humorous phrase becomes popular, it becomes great branding material)
* If you have randomly generated quests, which I assume will be common for an MMORPG, do the opposite of the previous tip. Make the objective clear and simple, just use a maximum of say, 3 sentences to describe what needs to be done.

# Answer
> 1 votes
Don't make your lore passive.

Think of it like light. You're in a dark lit room, full of nuance and subtlety, and suddenly you're struck by a bright flash of light, the garish glare of combat. When you are done, your eyes are still used to the bright. If your lore is still part of the dark room, they'll never sense it.

The lore needs to reach out to them, not just patiently wait in the dark.

The best way to do this will depend on what technology you have available to you, and your writing style. Final Fantasy games tended to do it with beautiful cut-scenes. Diablo II took that to an extreme, where the story is almost entirely in the cut-scenes. Others might find it effective to have the story lead the players to the next task.

In the early days of Everquest, every now and then a GM would lend their hand to make a roleplaying story great, whether it's surprise NPC visitor at a wedding or a dragon that's out of place. It didn't happen often, but it happened just enough to make it feel like the lore was alive and reaching out to you.

You might have a lore system where the lore actually plays a part in how you go through the dungeon. This then gives you feedback as to how well they are listening. If they're not listening well, maybe give them more reminders.

# Answer
> -1 votes
Make the lore interesting and people will get interested.

---
Tags: game-design, level-design
---


title: switching scenes in libgdx?

text:
# Question
Title: switching scenes in libgdx?
I'm writing a little something in libgdx to learn more about the platform. Currently, I have a simple generated world consists of tiles, which are just blocks of texture drawn to the screen. It's a simple setup, but I'm wondering how would I go about switching to a different "scene". For instance, just imagine a player, walking around in a grass field, enters a cave, and bam, he is in the cave. The world behind him has transitioned from a grass field to a cave (essentially, from one generated world to another).

I'm not very sure how libgdx handles scenes, so if anyone can share some tips, I'd appreciate it.

NOTE: I know this is a very broad question; right now I'm not asking for a specific solution but rather some tips to help me approach the idea I'm going after.

# Answer
> 1 votes
Do you have everything in the main game class? If so you can move each scene into its separate scene which each implements the Screen class.

For example

```
import com.badlogic.gdx.Screen;

public abstract class AbstractScene implements Screen
{

protected Game game;
protected Stage mainStage;
protected Stage uiStage;
public final int viewWidth;
public final int viewHeight;
protected boolean paused;

public AbstractScene(Game g, int viewWidth, int viewHeight)
{
    game = g;
    this.viewWidth = viewWidth;
    this.viewHeight = viewHeight;
    mainStage = new Stage(new FitViewport(viewWidth, viewHeight));
    uiStage = new Stage(new FitViewport(viewWidth, viewHeight));

    create();
}

public abstract void create();
public abstract void update(float dt);

@Override
public void render(float dt)
{
    uiStage.act(dt);
    if (!paused)
    {
        mainStage.act(dt);
        update(dt);
    }
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    mainStage.draw();
    uiStage.draw();
}
}

```

Now all you need to do is call the following function whenever you need to swap scenes.

```
game.setScreen(new ScreenClass());

```

---
Tags: java, libgdx
---


# Question
Title: How can I make the second soldier to stop walking once he is reaching the console?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Playables;

public class SpaceshipCutscene : MonoBehaviour
{
    public Transform player;
    public Transform[] npcs;
    public Transform console;
    public Camera FPSCamera;
    public Camera mainCamera;
    public Animator[] anim;
    public float rotationSpeed = 3f;

    private bool moveNpc = false;

    // Use this for initialization
    void Start()
    {

    }

    private void Update()
    {
        if (moveNpc)
        {
            // Soldier 2 rotating and looking at player
            Vector3 dir = player.position - npcs[0].position;
            dir.y = 0; // keep the direction strictly horizontal
            Quaternion rot = Quaternion.LookRotation(dir);
            // slerp to the desired rotation over time
            npcs[0].rotation = Quaternion.Slerp(npcs[0].rotation, rot, rotationSpeed * Time.deltaTime);

            Vector3 dirToComputer = console.transform.position - npcs[1].position;
            dirToComputer.y = 0;
            Quaternion rot1 = Quaternion.LookRotation(dirToComputer);
            npcs[1].rotation = Quaternion.Slerp(npcs[1].rotation, rot1, rotationSpeed * Time.deltaTime);
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.gameObject.tag == "SpaceshipCutscene")
        {
            FPSCamera.enabled = false;
            mainCamera.enabled = true;
            moveNpc = true;
            anim[0].SetTrigger("SoldierAimingTrigger");
            anim[1].SetTrigger("SoldierWalkingTrigger");
        }
    }
}

```

I have two soldiers(NPCS).

The first one npcs\[0\] is rotating facing the player and at the same time also playing animation.

The second npcs should ve rotating as well facing the console and then using animation start walking to the console and to stop in front of the console. But instead when he is reaching the console he start walking around the console nonstop.

The screenshot showing the animator state for the walking:

And the transition between the Ground and the Walking:

I'm using Cinemachine and using virutal camera: CM vcam1 to Follow and Look At the first soldier. The first soldier part is working fine the problem is with the second soldier.

UPDATE:

Instead trigger I changed the parameter to bool inside the OnTriggerExit I did:

```
anim[1].SetBool("Walk", true);

```

Then in the Update if moveNpc is true I did:

```
if (Vector3.Distance(npcs[1].position, console.position) < 4)
            {
                anim[1].SetBool("Walk", false);
            }
            else
            {
                Vector3 dirToComputer = console.transform.position - npcs[1].position;
                dirToComputer.y = 0;
                Quaternion rot1 = Quaternion.LookRotation(dirToComputer);
                npcs[1].rotation = Quaternion.Slerp(npcs[1].rotation, rot1, rotationSpeed * Time.deltaTime);
            }

```

But if I'm doing \< 5 the soldier will not move at all. If I'm doing \< 4 or 3 or 2 the soldier will move forward to the console but instead to stop he will keep move through the console then will walk in circles around the console nonstop.

# Answer
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Playables;

public class SpaceshipCutscene : MonoBehaviour
{
    public Transform player;
    public Transform[] npcs;
    public Transform console;
    public Camera FPSCamera;
    public Camera mainCamera;
    public Animator[] anim;
    public float rotationSpeed = 3f;

    private bool moveNpc = false;

    // Use this for initialization
    void Start()
    {

    }

    private void Update()
    {
        if (moveNpc)
        {
            // Soldier 2 rotating and looking at player
            Vector3 dir = player.position - npcs[0].position;
            dir.y = 0; // keep the direction strictly horizontal
            Quaternion rot = Quaternion.LookRotation(dir);
            // slerp to the desired rotation over time
            npcs[0].rotation = Quaternion.Slerp(npcs[0].rotation, rot, rotationSpeed * Time.deltaTime);

            float dist = Vector3.Distance(npcs[1].position, console.position);
            if ( dist < 4f)
            {
                anim[1].SetBool("Walk", false);
            }

                Vector3 dirToComputer = console.transform.position - npcs[1].position;
                dirToComputer.y = 0;
                Quaternion rot1 = Quaternion.LookRotation(dirToComputer);
                npcs[1].rotation = Quaternion.Slerp(npcs[1].rotation, rot1, rotationSpeed * Time.deltaTime);
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.gameObject.tag == "SpaceshipCutscene")
        {
            FPSCamera.enabled = false;
            mainCamera.enabled = true;
            moveNpc = true;
            anim[0].SetBool("Aiming", true);
            anim[1].SetBool("Walk", true);
        }
    }
}

```

I have two soldiers(NPCS).

## SOLUTION

In the Animator window of the Soldiers(NPCS) I added a Walk state with two transitions between the Grounded and Walk. And also added a new parameter name Walk type of bool:

The first transition is from the Grounded to the Walk and the parameter Walk is set to true. The second transition the one in the screenshot is from the Walk to the Grounded and the Walk parameter is now set to false.

In the script above I'm calling first to the Walk , true that make the Walk state to start the Walking animation. Then when the Soldier(NPCS) distance from the console is less then 4 I start the second transition Walk , false.

The Soldier is slowly change from Walking to Idle animation.
> 1 votes

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


# Question
Title: Unity - Raw Image Size scaled to Photoshop
I'm just a beginner in Unity, so basically, I want to find out the exact measurement unity of the raw image so that I can now design in photoshop. I tried in Pixels in photoshop but when I import it in unity, it seems that the image is stretched out. I also tried mm, cm, inch but none of these worked. How to scale it so that my designed image's dimensions in photoshop will be exactly the same as the dimensions in unity? How to scale it?

I tried pixels in photoshop but the image is stretched out indicating that it is not the right measurement unit.

# Answer
> 1 votes
There is no 1:1 relationship between the size reported by the Rect Transform and pixels. The actual (pixel) size on screen depends on the resolution (chosen by the end user) and the settings of your canvas.

If your canvas size is set to, say, 1920x1080, it will be pixel perfect only when the game is run in (full screen) 1920x1080. In other all other resolutions or window sizes, Unity will perform some scaling to compensate - which is usually what you want. Someone running at a lower resolution should still be able to see the entire UI.

With the canvas set to 1920x1080 and running at that resolution, the pixel values **will** match up though. I.e. a UI element with a width of 500 is 500px wide at that resolution.

I'd, however, recommend designing your UI elements for a *higher* resolution than your main target (unless you are targeting a platform with a fixed resolution). In my own game, for example, the UI was designed for a 1080p display, but I created all the art at 4x resolution so that the UI will scale nicely for someone running on a 4K screen (which, as time progresses, will only become more and more common).

---
Tags: unity, gui
---


# Question
Title: Is it possible/recommended to make a universal game library interface in C
Lets say I want a game to be able to run with SDL, Allegro, on Game parks or Tiny Arcade and I don't want to recode everything everytime I port my game.

The C and C++ language separate definition in .h files and source in .c files. My teacher said it could be possible use the same .h declaration file but have different .c implementation files.

So in theory I could write something like this in the .h (the syntax is not perfect)

`typedef myBitmapStruct;
void myBlittingFunction ( myBitmapStruct bmp, int x, int y );`

Then I could have different .c for each game library. myBitmapStruct will refer to a BITMAP in the allegro implementation, or an sdl\_surface in the SDL implementation, etc.

So in theory I think it could work, in practice it might lead to optimization issues. Since first it needs an additional method call because library functions are encapsulated. Second it might been additional code to make conversion or adjustments. For example allegro 5 use an on grid coordinate system, so 0.5 must be added to any x, y coordinates passed in parameter.

Do you think it could be recommended to do a such universal interface?

Did other people already attempted to do this before?

# Answer
While it is true that SDL already provides support for multiple platforms, it is of course possible to build another layer on top to abstract the specifics of SDL away from the rest of your code. We do the same in our engine, because SDL doesn't support all of our targets. Similarly, our renderer has an internal abstraction layer so we can support Vulkan, DirectX 12 and potentially other graphics APIs.

This kind of layering is bog standard in game engines. I wouldn't worry too much about the performance implications. Yes, there is a cost incurred with every additional (virtual) function call and those coordinate conversions aren't strictly free... but this overhead is probably insignificant in the grand scheme of things.

In my experience, the gain of having these abstractions (namely the option to switch an underlying API out if/when needed) generally far outweighs the performance cost.
> 2 votes

# Answer
What you are suggesting to do here is actually what a library like Allegro or SDL is doing for you.

SDL, for example:

> officially supports Windows, Mac OS X, Linux, iOS, and Android. Support for other platforms may be found in the source code.

SDL provides you with a `blit` function, which is implemented differently depending on which operating system you are compiling for. That means a game which uses SDL can be compiled for every one of these operating systems (as long as it doesn't use any operating-system dependent features outside of the SDL library).

Adding another abstraction layer on top of your game library would only make sense if you want to support a large number of platforms and just can't find a library which supports all of them. Or you could just as well write your own implementation of the SDL interface for that one obscure platform and link your application against that library when compiling for it.
> 1 votes

# Answer
I see your point.

> Or you could just as well write your own implementation of the SDL interface for that one obscure platform and link your application against that library when compiling for it.

In that case it would make more sense this way. But I might need understand the low level logic of that platform.

For example: The Gamepark has an SDK called Mirko SDK designed for game programmers. It makes sense to call Mirko from my source code, but it does not make sense to call Mirko from SDL (high level lib calling an high level lib). I would be more logical to extract the low level code in Mirko and make an SDL "driver" for it. But I would need deep understanding of the game park which I don't

What I proposed above was an interface that calls high level libraries, but it indeed add an additional call. By thinking about it, it could be more suitable to use C macro system. As it replaces code instead of calling code. I understand that macro are not perfect and could lead to errors, but that could be an alternative solution.
> 0 votes

---
Tags: interface
---


title: Event-Based Entity-Componenty-System

text:
# Question
Title: Event-Based Entity-Componenty-System
So, I'm new to ECS. The concept is very interesting in contrast to traditional OOP and heavy inheritance. I'm working on a game right now that is open-sourced, but does not actually have a game loop. It works by sending and receiving packets, and acting upon those received packets.

In that case, what would I be looking at in this relationship between Systems and Components? Let's say I have an incoming *Movement* packet that is telling me to move *Player A* 5 units to the right. And let's say I have a lot of different types of packet types (let's say up to 100), each for different stuff, like maybe making a purchase at an NPC store. Another one for purchasing at a player store.

Or maybe inviting and expelling players from a party. Or inviting and expelling players from a guild or alliance.

At that point, I start getting a little confused. I can definitely see similarities in ..

1. Adding/Expelling people from a party, guild, alliance

But each of those packets contain different information at their core. I'm tempted to write a component that Guilds, Alliances, and Parties can use (like AddRemoveMemberComponent), but the information coming in from the packet makes me hesitant.

How would those components handle specifically? Maybe I'm just entangling myself in traditional inheritance, so it's hard for me to see the uniqueness of data. Would I have unique systems for explicitly handling Party, Guild, Alliance expulsions and invitations? And how would I dynamically know what to do with these different packets coming in (different packets for alliance, guild, party).

# Answer
Entity movement is a great example.

In most games, they do not care what triggers the movement, only that entities move in a common and standardized way. So the idea is to design some middle-man concept that knows how to take and interpret the input source and transform that into a series of commands that the EC/ECS movement system understands.

In the case of ECS, you might have a system that knows how to listen for local input from the keyboard and mouse and upon getting input, it interprets that input into commands. It locates an entity that maintains a `PlayerController` component and then sets the appropriate toggles for whether the entity moves `Up`, `Down`, `Left`, `Right`.

Similarly, when network movement packets arrive, you might have another system that knows how to interpret the packet data, locates the appropriate entity by its id, checks that it still maintains a `NetworkController` component and sets the appropriate toggles for `Up`, `Down`, `Left`, `Right`.

Later on a movement system asks for all entities with controllers, regardless if they're player or network controlled. Its at this point the `Up`, `Down`, `Left`, `Right` get applied with the entity's current velocity and orientation to apply the requestesd movement.

The nice thing here is movement is handled in a standard way regardless of where the data came from so that you could easily replace the `PlayerController` with a `NetworkController` and allow some remote player to control your character, like while being mind-controlled or feared.

As for Guild, Party, or Alliance.... It would seem those are potentially different game constructs in their own right but share some underlying behavior where an entity particiaptes in a collective. Whether you intend to model those systems with a base class to share code, thats entirely up to you but a plausible design choice if you want.

But much like movement, the guild system would be notified when a guild packet arrives. The packet will be interpreted by the system to know which entity it should operate upon and what operation to take. Depending upon the operation, the entity is looked up and the appropriate action would be taken.

For example, if Entity 123 requested to join Guild Acme, then the system would first lookup that entity, verify that it does not presently have a guild component. If it does, we might error because an entity can only be associated to a single guild. If no component exists, we lookup the guild Acme, verify it exists, if so we create a guild component that references the guild's guid and then add that component to Entity 123's component list.

As to how you handle the routing of packets, that's entirely up to you.

You could build a map at runtime where you maintain a packet-type to either a system pointer or a function pointer for the callback or you maintain the mapping through some build-time mechanism so its effectively static at compile-time.
> 2 votes

# Answer
As Naro's said, you need a component for every player, that joins a Guild / Party / Alliance to save the information, that they are in that alliance or whatever.

But you most likely need a serverside system to keep track of your membership to the specific Guild.

Imagine, someone wants to join, so he sends a join request or accepts an invitation. As Naro's said, you check for that players components, but if its alright, you send a message to the server with the player-id and "join" for example.

Now, the server needs to keep track of the members in this guild. Maybe for some reason the player who wants to join is already in the Guild, but somehow didnt had the component associated with it. Or other players should get notified that someone joined.

In that case, you dont want to send that message to every player, just to the players in that guild.

That said, you could implement your Guild(s) as Entities themself, that have hasMemberComponent in addition to some other Guild-specific components (like rank, fame, community Gold etc.).

So, if something changes in the Guild, you dont have to send all these informations to every other player, just to the server. If you dont have a server and just peer-to-peer, then every client needs to have the guilds information.
> 1 votes

---
Tags: entity-system, entity-component
---


# Question
Title: Clarification on the correct way to call SpriteRenderer
This is probably a dumb question, born from my own ignorance, but I haven't been able to find a satisfying answer yet.

In this post Savlon gives example code for using SpriteRenderer to cycle through two sprites. What exactly is the purpose of the line:

```
private SpriteRenderer spriteRenderer;

```

To me this looks like we are storing an instance of the class SpriteRenderer inside the private pointer spriteRenderer. Because in the Start loop they write

```
spriteRenderer = GetComponent<SpriteRenderer>();

```

which uses GetComponent to address properties of SpriteRenderer.

Is this correct? If so, what is the advantage to doing this over creating Savlon's code inside a subclass of the SpriteRenderer class?

* Kensington

# Answer
```
private SpriteRenderer spriteRenderer;
...
Start()
{
   spriteRenderer = GetComponent<SpriteRenderer>();
   ...
}

```

Keeping a private reference to a Game Object's component is totally normal. It improves the performance as you ask Unity only once to fetch the component, no matter how many times you're going to use it.

You can't create a subclass of SpriteRenderer (because it belongs to a library) nor derive from it (because it's sealed).
> 0 votes

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


# Question
Title: How can Perlin Noise be modified to not tile?
In vanilla perlin noise, the texture repeats after 256 coordinates, due to the way it picks a gradient vector. In games that require an infinite procedural world, however, this is not an acceptable tradeoff. This requires a different method to pick the gradient vector. I need an alternative that is portable in C++, meaning that I will get the same noise for the same seed on different systems.

I have come across two options to do this:

* Using C++'s random api, using bitshift-modified coordinates as the seed, but this is very slow in practice and is too reliant on the exact implementations of the C++ random number generators, which may or may not guarantee the same sequence of numbers across platforms.
* Use a much faster random hash function I found in the old freespace virgin "perlin noise" (actually value noiswe) tutorial, which I saved before it went down. The issue with this one is that it has bitshift on signed integers, and thus has undefined behaviour in C++.

EDIT: Something I forgot to mention in the original question is that I need to be able to re-seed the perlin noise engine to get a different output. With vanilla perlin noise, I can simply use a seeded random shuffle on the hash table lookup array before calculating anything else.

# Answer
It sounds like you already know the solution to your problem: replace the initial 256-entry table lookup with a hash/digest of the whole coordinate value, not just the low 8 bits.

From there the only question that remains is which hash function to use, and there are tons out there that you can try on for size if the one in the tutorial didn't meet your needs.

> The issue with this one is that it has bitshift on signed integers, and thus has undefined behaviour in C++.

Note too that even if your coordinates *represent* signed positions in your game world or texture space, Perlin noise doesn't need to know that. All it cares about is reproducibly selecting different gradient vectors for each distinct set of integer inputs, so you can re-interpret the bit patterns as unsigned integers and it's still just as happy.
> 3 votes

# Answer
The original definition of Perlin noise doesn't mention a fixed size permutation table. That's only a speed improvement, because generating pseudo random values based on coordinates is usually a slow or complicated process.

Stefan Gustavson solved this issue in his glsl implementation by using a function. As stated here this won't make it infinitely long either, but you can pick a prime number large enough for your needs. For instance, using 9997643 and 9997237 would put the first repetition at 99948806512391, but make sure your data types can handle division by those values nicely.

Another approach is to use a seeded random generator. Create a unique number from the coordinates (for instance if you use two 32 bit integers for coordinates, then just do `x << 32 | y` to get a unique 64 bit number), set it as the seed of the random function and generate a value. That should be the same every time you query that position.
> 0 votes

---
Tags: c++, random, perlin-noise, cross-platform
---


# Question
Title: What Game mechanic can I implement to give players incentive to finish a race?
I am essentially making deathrace the game. How do I give players incentive to finish or participate in the race instead of strictly deathmatching on the race track.

Edit More Detail:

General Race Rules:

1. Death during the race knocks you out of the race
2. Weapons and defensive tools are picked by player at the start of the race where they are limited by the amount of "space" on the weapon and defensive system
3. Using a weapon increases the heat of the weapon system. certain weapons within a cars weapon system can only be used if the weapon systems temperature is below a certain threshold
4. Defensive systems are power based, where certain defensive tools can only be used if a cars power if above a certain threshold
5. Killing other players is fun but not required to win the race
6. Finishing the race or completing a lap or making progress around the track grants X

Where X is something I can't make appealing enough to dissuade player from just deathmatching on the race track.

# Answer
An economy system or unlock progression could be a good way to motivate this.

Here, you'd have a wide variety of parts - weapon & defensive tools with differing style & effectiveness, or vehicles with more or different arrangements of weapon & defensive system space, or additional characteristics like cooling rate perks. You'd gate some of these parts so that the player can't use them all in their very first race.

The gate could be a cost you need to pay or point threshold you need to hit to unlock a part type for use, or even a modest installation fee you pay every time you want to equip a part.

Killing all of the other players gets you a win and lets you advance to the next race, but is not the most effective way to earn the points or currency used to get new gear.

Instead, every time the player completes a lap (or even better, at every checkpoint) they earn a batch of this currency.

The value can increase from lap to lap (so I want to get to the late laps for maximum earning), or even award a bonus for the number of competitors still in the race (fictionally: your audience likes watching a more dramatic, contested race) - this encourages the player to play like a race and get ahead early, rather than thin the competition first before picking up an easy few laps with fewer opponents to fight.

Winning the race by crossing the finish line can grant the biggest pot of currency, making it a clear carrot to draw players forward.

So players who want to race with better and better equipment (or at least, more customized to their style) want to get far in the race to build up their points/currency for the next race.

Of course, at some point you'll run out of new & interesting gear to offer, so you can keep the motivation going with things like...

* "Prestige" levels the player can advertise on their name/profile for others to see ("I've earned enough points to unlock everything three times over!"
* Leaderboards for the top-scoring/earning players today / this week / this month
* Vanity customizations purchased / unlocked with the same points or currency (colour changing, decals)
> 3 votes

# Answer
I liked both answers already given, but wanted another idea:

What if, players that do not run through the race are punished for it?

Maybe the last player is the "Grim Reaper" who runs very slowly through the stage, but anytime it catches another player, it kills them. This is a Death Race after all.

Also, if a player manages to run so fast, to catch the Grim Reaper with a lap difference, they can either be forced to stay back and battle other players (By making the Grim kill players behind it as well - encourages fighting) or you can reward the player with something like "You just passed the Grim Reaper, you get a reward (upgraded weapons/armor?) but now the Grim is directly behind you!
> 3 votes

# Answer
**Time**

You could make the main race partly against the users own time. For example money for upgrades is given for winning, but achievements are for beating records.

**Peanlty**

You could have a referee that punishes you for unnecessary violence. It would potentially be unfair and would be hard to code, but a simple implementation could be slowing down to attack targets or not accelerating when you are clearly able to adds to an invisible penalty point counter. As the penalty points rise the crowd starts booing you. The penalty points are then used to punish the player with a low score or less money.

**"Magic trick"**

Or hide a trick that the enemies get harder to kill and more dangerous the fewer of them there are. Set it so a player can easily kill one or two opponents but as the pack thins the player is up against opponents beyond their skill. A 'deathmatching' player will probably not notice anything other than that their strategy isn't working and try to race through getting only a few kills where necessary, the big flaw here is players finding out and that ruing the game or making a meta strategy of not letting players through.
> 1 votes

---
Tags: game-design, level-design, game-theory
---


# Question
Title: Can you use A* to make a unit move nonspecifically?
A\* is typically used to calculate the best way to move towards something, and it's quite flexible when it comes to threats, extra movement costs, and 'refuelling' on the way to something.

However, if you designate only threats, perhaps with a main threat first and foremost, can you use it for "finding somewhere to go"? What about adding both threats, safety, resources and other such heuristic influencers to determine what a unit does when idle?

# Answer
> 1 votes
Sort of.

"Finding somewhere to go" is not, on the surface, what A\* is about. A\* is about finding how to *get* there, once you know where you want to go; A\* is just an algorithm for finding a traversal of some graph.

While it is widely used in games to find a traversal of a graph that represents navigable space (such as a grid), it can be used to find such traversals of graphs representing *whatever you want*, as long as you can express the concept as a graph with associated costs.

It's certainly possible to represent the decision space of an AI as a graph and use A\* to find paths through that graph. How you'd make that usefully work in a video game is not immediately clear and might require some experimentation.

For example if you construct a graph representing primary driving goals of an AI (flight aggressively, fight defensively, flee outright) arranged as spokes with interim nodes representing tailored, blended behavior options, you might be able to use A\* to find a path between two nodes that represents how the AI will change it's overall bearing over time. I'm not sure this is a practical approach (you could accomplish a very similar thing in a much simpler fashion), but it's something you could *technically* make work.

It's easier to see how it could work with a more concrete and defined scenario; for a more concrete example of path-finding in "decision space," take a look at this question and the answer by DMGregory.

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


# Question
Title: How to remove horizontal black bar at the bottom of the game screen in libgdx?
Here is the screenshot .Here is my Play constructor in Play class.

# Answer
> 1 votes
Here 5 options depending on your desired effect.

1. Set the camera position, so it is centered on a point above the player. (so that there are always enough tiles below the camera to fill the screen.)
2. Reduce the height of the window to clip the bottom area. (this will require a combination of #1 and reducing the window height to reach the desired effect)
3. Center the camera at a fixed height, so that the bottom row of tiles is flush with the bottom of the window.
4. Center the camera on the player, but clamp the height component to a minimum value that shows the bottom row of tiles flush with the bottom of the screen.
5. Expand the tileset to show tiles farther below the character.

Comment if you need more detail on how to achieve a specific option.

---
Tags: libgdx, android, camera, box2d, platformer
---


title: Pathfinding, 2+ tiles wide

text:
# Question
Title: Pathfinding, 2+ tiles wide
I recently started learning python and I'm working on a dungeon generator, using images for the rooms, hallways and junctions. Example of desired result.

So far I managed to generate a X * Y map and avoid the rooms from escaping the background image or colliding with each other (collision test); I was going to work on pathfinding to generate the corridors but ran into a problem. As you can see in the first image, some corridors and junctions are 1-tile wide while others are 2, and potentially wider.

Ideally I would use the generated grid to see where the corridors would go and "paste" whichever corridor or junction image would fit in that space.

Any tips on how to incorporate that into the pathfinding algorithm?, or if you have a better idea to generate the corridors, I'm all ears. Perhaps generating a single room, growing a corridor from there and adding a room at the end of that corridor, rinse and repeat?

# Answer
During pathfinding for a 2x2 unit, when checking a node's neighbors, only consider it a valid node if it's open *and that node's right/down/right+down neighbors are also open.* If they're not, treat it the same as a wall.

Rather than writing your own pathfinder just for this, you can use this trick to transform an NxN grid into a new (N-1)x(N-1) grid, and then feed that through any off-the-shelf pathfinder.
> 2 votes

---
Tags: path-finding, python
---


# Question
Title: How do I get a popup menu to block clicks from hitting UI elements beneath it?
You can see in the picture that I have a Canvas with a popup menu in it. I just enable this, and it covers the main menu stuff. Clicks go through it and hit stuff in the main menu.

I've tried adding an EventTrigger to the PopupRoot object, and adding an event to listen for PointerClick events, but it doesn't fire.

```
EventTrigger trigger = m_popUpRoot.GetComponentInChildren<EventTrigger>();
EventTrigger.Entry entry = new EventTrigger.Entry();
entry.eventID = EventTriggerType.PointerClick;
entry.callback.AddListener((eventData) => { PopupClickBlocker((PointerEventData)eventData); });
trigger.triggers.Add(entry);

```

I'm open to other suggestions. My current system is horrible; button click events query the Popup to see if it's enabled or not, then return doing nothing if it is. This doesn't work for sliders very well, so I want to do this the right way.

# Answer
> 0 votes
I used a `GraphicRaycaster` object on the root popup `Canvas` object, and set it to "Blocking Mask = Everything".

# Answer
> 2 votes
Use a CanvasGroup on the PopupRoot, and check the "Block Raycasts" option.

This will make the element block raycast from the elements behind it.

---
Tags: unity, events
---


title: Adding character stats/traits in Ren'py

text:
# Question
Title: Adding character stats/traits in Ren'py
I'm coding a relatively simple VN with RPG elements in Ren'py, with little prior programming knowledge. There's one aspect that I can't simplify further because it's important to the game's branches, but that I'm not sure how to enact.

There are four traits/stats the main character can have in this game:

* Viciousness
* Intelligence
* Creativity
* Charisma

You have two of the four. They don't have levels or anything -- it's simply 'do you have this trait or not'. You can't change traits after picking the two of them, you just have e.g. a Creativity/Viciousness build for the rest of that playthrough.

With my limited prior knowledge, the only way I can figure out how to enact this is with a giant mess of if-else statements. You would, for instance, start with:

```
default Intelligence = False

```

Then if you pick Intelligence as one of your stats:

```
$ Intelligence = True

```

Then, for anything further that requires Intelligence (or precludes it, as the case may be):

```
if Intelligence = True

```

But this sounds like a giant overcomplicated mess if I'm doing it for each and every time the game checks if you have/don't have a trait. There's a better way. What is it?

# Answer
> 1 votes
You should build up a system in which you can define what is required for actions (as of anything that requires these traits). Now, logically speaking you have A,B,C,D.

Sometimes you want A and B, sometimes you want A or B, sometimes you want A and (B or C). One way which comes to my mind is to create a class or struct (let's call it 'R') to tie together OR conditions, then whenever you have a requirement, you use a list or array of these conditions, which is an AND.

So the system would be used like this (\[ \] symbolizes one of 'R':

```
[A] [B]

```

This means you must have A and B.

```
[A] [B or C]

```

This means you must have A and either B or C.

For all of this you should use enums and some method or function like "CheckRequirements (List requirements)" which compares the traits of the player and compares them with the required ones and returns a bool.

I am not sure whether it's good to hard code such conditions rather than finding ways to solve it in more abstract ways. But it all depends I guess. Also I don't know which engine or scripting/programing language you are using.

---
Tags: architecture, renpy
---


# Question
Title: Unity : Changing color of 2D sprite distorts sprite shape
In my 2D game, my circle shape for example, appears round, but when I change the color then it turns into a low poly circle with 8-16 points, more like a potato. Is there any way around this?

```
    myColor = new Color32 ((byte)colorR1, (byte)colorG2, (byte)colorB3, visibility);
    Color32 negativecolor = new Color32 ((byte)colorR1, (byte)colorG2, (byte)colorB3, (byte)(255-visibility));
    MaterialPropertyBlock props = new MaterialPropertyBlock ();
    props.SetColor ("_Color", myColor);
    rend.SetPropertyBlock (props);
    props.SetColor ("_Color", negativecolor);
    backchildrend.SetPropertyBlock (props);

```

# Answer
> 0 votes
didn´t you try using the sprite renderer? That´s how I changed the colors of sprites. Use

```
SpriteRenderer sprite = GetComponent<SpriteRenderer>();
sprite.color = Color.red;

```

That should change the color of the whole sprite

---
Tags: unity, sprites, color
---


# Question
Title: How to calculate a quad based on a triangle pairs shared edge
Based on two given triangles, I would like to calculate a quad that can be used as a 'fat' line for the edge between the triangles.

I have googled around and while it is very easy to draw lines in OpenGL or DirectX, the problem is that you can only guarantee a thickness of 1 pixel.

To overcome this I need to generate a quad for the line.

So given the below image...

I have a set of triangles, and I want to draw a line where the red dots are. I know the start and end vectors for this line. And all the details of the triangles

I need to create a quad so that I can define the thickness (seen as the blue arrow)

An extra complication is that the triangles may not be on the same plane.

So from the side perspective, the 'line' would need to be created with its edge growing like this. Where both black lines are the sides of two separate tringles and the shared edge is from the point and moves into the screen.

All the calculation for this will be done offline

I am hoping that just a nudge in the right direction and I will be able to hammer this out on my own. (maybe)

OR if there is another way to solve the fat line problem then let me know. I will be rendering this using OpenGL ES 1 (without a shader)

Thanks.

# Answer
> 1 votes
Take the unit normal of each triangle, then normalize their sum. This gives you the normal of the plane of your quad, making an equal angle with each of its parent triangles.

```
Vector3 edgeNormal = Normalize(
      edge.leftTriangle.normal
    + edge.rightTriangle.normal
);

```

Next take the vector from the start to the end of the edge you want to fatten. Cross it with the quad normal to get a `perpendicular` vector in the quad plane, and normalize this too.

```
Vector3 edgeVector = edge.endPoint
                   - edge.startPoint;

Vector3 perpendicular = Normalize(
      Cross(edgeNormal, edgeVector)
);

```

The four corners of your quad are then:

```
edge.startPoint ± 0.5 * thickness * perpendicular
edge.endPoint ± 0.5 * thickness * perpendicular

```

---
Tags: 2d, triangulation
---