# Question
Title: Making sure my users don't fake that they've completed a task I can not verify electronically?
I hope this is worded alright, I didn't know how else to describe it. I'm developing a game that has the user set their own "missions" that take place in real life. A simple example would be "Smile at a stranger". Then they can mark it complete and win coins with which they can use to buy real prizes.

However, because these tasks cannot be verified to see if the user has *really* completed them, I'm worried that people will just mark things as complete to win coins and get prizes without working for them. I used a fitness iphone game years ago where this was the case.

How do you suggest I prevent this from happening?

**Edit**: My first thought was to add a max amount of missions a user could do a day. Something like two. And let users that subscribe (so the more serious users) have limitless missions a day.

Thank you for the suggestions so far!

# Answer
> 1 votes
# Make tasks that are verifiable

"Take a picture with a stranger" can be verified: the user can upload a photo. The system doesn't need to *do* anything with this photo other than store it away somewhere. Then if a user is suspected of cheating (by a system that looks at their number of complete tasks and how long it took them to do so, etc. etc.--a much easier problem to solve using statistics) an admin/moderator can pull up all of the photos/etc. that were used as proof and do a manual check.

Another task might be to visit a landmark / particular location. They can then check in via their device (and you can request GPS coordinates). Those coordinates are spoofable (as evidenced by all the people cheating at Pokemon GO) but are as reliable as a random photo upload (again: an admin/mod can pull up the records of where they checked in, etc. etc. and see if it was plausible that they could get there).

# Answer
> 1 votes
If the task cannot be verified, you need to rely on the user to self-verify. For this to work, the users need to be intrinsically motivated to perform the task.

**Minimise external rewards**

If you offer too much external rewards relative to the intrinsic value of the task - such as prizes for smiling at a stranger - you can decrease the intrinsic motivation for the task. This is known as the overjustification effect. And once the user becomes extrinsically motivated, they are way more likely to cheat.

If possible, minimise or offer no external rewards at all. You should focus on reinforcing the intrinsic motivation, for example via praise. Praise is a good tool to use as it is less meaningful when the user cheats. Also, don't underestimate the satisfaction of checking items off a list, or measuring progress.

**Use tasks that build toward a verifiable goal, and reward that**

For example, if you were creating a health and fitness app, you might have small, unverifiable tasks like "ate a healthy meal today". But eventually, these lead to verifiable changes, like weight loss, or being able to run a certain distance. You might not reward the unverifiable tasks but you can reward the verifiable ones. The rewards still need to be small enough to avoid encouraging cheating. It also depends on how easy it is to cheat, and how powerful the intrinsic motivation is (e.g. actually being fit and healthy) v.s. the external reward.

# Answer
> 0 votes
This seems pretty implausible barring proper verification. The best I can think of is having multiple users verifying each other on different devices. This is still fairly simple to get around, but would at least provide some barrier. It also requires multiple users working together, which is both a good thing and a bad thing. On one hand, it means better virality for app distribution. On the other hand it means people who aren’t socially active wouldn’t be able to use the app.

A more lenient option would be to award a few points whenever they check something off with a maximum of one a day or something, but if they get another user to verify it, they get more points and another chance to check off something the same day.

Just remember, this is pretty simple to get around. Owning two devices is all that’s necessary. You could require a Facebook login to verify that two different accounts exist at least, and rely on Facebook’s Terms of Service to “guarantee” every person has only one account.

If these are things that can be verified with a video, you could have users upload videos of them doing whatever it is and multiple other random users can watch the videos and confirm or deny that it happened (maybe awarding points for videos you watch for other users). This would invite trolls to share NC-17 content though, so... hmm.

# Answer
> 0 votes
Maybe you could have the user select a minimal duration for each task, only after which they would be able to mark the task as completed.

If users are forced to live some life in between visits to the app, they may be more likely to have a try at the tasks.

Cheaters may not be patient enough to wait out even the most minimal duration in order to cheat.

This wouldn't guarantee that nobody cheats, of course, but might help "serious" users get the most out of the app.

You could also have the app ask, when the user tries to mark a task as completed, "Are you being honest with yourself?" This may not curb cheating all that much, but if this is a self-help kind of app, it might be an interestingng touch.

---
Tags: game-design, rpg, economy
---


title: Understanding Torque in Unity

text:
# Question
Title: Understanding Torque in Unity
This is (hopefully) a simple question that should avoid me asking a more complex question. This is in Unity (2D) but hopefully this is a general physics principle I am not getting.

I am applying a torque to a 2D object. The object has a scale of 1, a RigidBody2D with a mass of 1 and no angular drag or undergoing gravity. It is a CircleCollider2D with a radius of 1. There is nothing else attached to the object.

In the following code I apply a torque of Pi for one second. In linear motion (and from my understanding of torque) I would expect the angular velocity, after one second, to be Pi (or 180deg/s). However, running this code and printing out the speed at t=1.0, the speed is 90deg/s.

```
void FixedUpdate()
{
    if (time < 1.0f)
    {
        rigidbody2D.AddTorque(Mathf.PI);
    }
}

```

This is consistent, applying a torque of 2Pi gives me a velocity of 1Pi after the time. Where is this factor of 2 coming from?

# Answer
> 1 votes
A torque is a force which will be applied on the tangent of the circle :

So for the same force applied the velocity of the point where the force is applied will be the same, knowing that : If the diameter change but the force stays constant, a smaller diameter means smaller perimeter so less way to travel to make an angular degree so the angular speed in degrees per seconds will be faster with a small diameter than with a large diameter for exactly the same force applied!

More math frenzy definition at wikipedia

# Answer
> 1 votes
I can answer part of this old question, but not all of it because not enough information is given such as what properties are being used to measure the velocity and how it is being converted to Pi as a unit. For example, `Rigidbody2D.angularVelocity` is given in degrees per second and I can only assume that is being converted to radians, but that conversion is not shown. Show us more of the code and raw output.

Aside from that, torque is torque. It doesn't matter "how" it is being applied as long as it is applied at the expected value. Assuming the default units of kg, m, and s, a torque of Pi N-m could come from Pi kg at radius 1 m, or 1 kg at radius Pi m (both assuming perpendicular force), or any other set of factors that equates to Pi N-m of torque. If it does matter how the torque is applied then use a different method to apply it such as `Rigidbody2D.AddForce()`, `Rigidbody2D.AddForceAtPosition()` or `Rigidbody2D.AddRelativeForce()`.

It makes sense that a smaller cylinder accelerates faster than a larger cylinder of the same mass, given the same torque (assuming, that is, you left them at the same mass). The larger cylinder would be less dense overall with more mass further away from center. A merry-go-round with children hanging on the outside edge is harder to accelerate than with the same children huddled near the center.

The problem I see here, however, is that you show an increase in rotational velocity of 16x (or 4x^2) when it should have been only 4x for half the radius:

* angular acceleration = Torque / (0.5 * mass * radius^2)

+ 1.0r cyl = Pi / (0.5 * 1 * 1.0^2) = 2Pi radians/s^2
    + 0.5r cyl = Pi / (0.5 * 1 * 0.5^2) = 8Pi radians/s^2
* angular velocity = angular acceleration * time

+ 1.0r cyl = 2Pi radians/s^2 * 1s = 2Pi radians/s = 360 deg/s
    + 0.5r cyl = 8Pi radians/s^2 * 1s = 8Pi radians/s = 1440 deg/s

But it is not possible to guess where the fault lies (the engine or your code) without more information.

---
Tags: unity, physics
---


title: Creating a Nations Stockpile

text:
# Question
Title: Creating a Nations Stockpile
If I created different XML files for each Nations' Stockpiles and made an XMLmanager to do updates such as resource consumption and trade, wouldn't that be too much resource intensive? I mean, if I had to access each Nations' stockpiles every tick and update them (Quantity, Price, Quality).

Is there any other faster way to manage all those updates?

From the back and forth in the comments, I've came up with this approach.

```
public class Nation
{
    public string NationName;
    public int Population;

    public void NationCreator(string name, int pop)
    {
        NationName = name;
        Population = pop;
    }

    public class Stockpile
    {
        public int food;
        public int water;
        public int wood;

        //Then methods to work with that stockpile
    }
}

```

However, after some thinking and reading, my next approach to this problem will be Arrays but I only know how to make an array of one particular type like:

```
double[] balance = { 2340.0, 4523.69, 3421.0};

```

How could I do an array like this (Lua style array) in C# language?:

```
raw_material = {
    cotton = {
        Value = 17.50
    }
}

```

# Answer
> 1 votes
I'd be inclined to do something a little like this:

First we define somewhere our collection of resource types (assuming this is a controlled list that will only be expanding occasionally during development. If you want dynamic resource types that can be expanded by mods / DLC, the Type Object Pattern can serve that need. But for most cases we can keep it simpler.)

```
public enum ResourceType {
    Food,
    Water,
    Wood
    // Add resources here as needed.
}

```

Next our stockpile can be implemented as a key-value store that maps resource IDs to the quantity of resource held. (If you need, instead of an `int`, the content of this structure can be a `struct ResourceRecord` including not just quantities but storage capacity, production rates, expiration date, quality, etc...)

```
Dictionary<ResourceType, int> _stockpile = new Dictionary<ResourceType, int>();

public int GetResourceStock(ResourceType kind) {
    int held = 0;
    _stockpile.TryGetValue(kind, out held);
    return held;
}

public void AddResource(ResourceType kind, int quantity) {
    // For safety & debugging, you may want to Assert here that quantity > 0.
    int held = GetResourceStock(kind);
    _stockpile[kind] = held + quantity;
}

public bool TryWithdrawResource(ResourceType kind, int quantity) {
    int held = GetResourceStock(kind);
    if(held < quantity)
        return false; // I lack enough funds to spend.

    _stockpile[kind] = held - quantity;
    return true;      // Transaction completed successfully.
}

```

Here I've shown this as a dictionary, for maximum flexibility. This might be overkill for your needs though - if your list of resources is small & fixed, an array indexed by the enum-as-integer would work fine - I show that style in another answer. Or if any given stockpile can contain only a few (dozens of) resource types, a `List<ResourceEntry>` would be comparably fast to search.

What's nice about this is that now you can define resource production & costs in data. If our `food` and `water` resources are particular named variables, then we need different lines of code to check & modify each one. But by abstracting this out, the same code can act on any single resource or collection of resources with only data changes. For example, we can model costs & purchase checks for any number of resources like this:

```
public struct CostEntry {
    public ResourceType resource;
    public int quantity;
}

public bool CanAfford(CostEntry[] costs) {
    foreach(var cost in costs) {
        if(GetResourceStock(cost.resource) < cost.quantity)
            return false;
    }
    return true;
}

public bool TryPurchase(CostEntry[] costs) {
    // If we can't afford it, stop right away.
    if(CanAfford(costs) == false)
        return false;

    // Now that we know we can afford it, spend all the required resources.
    foreach(var cost in costs) {
        TryWithdrawResource(cost.resource, costquantity);
    }
    return true;  // Done.
}

```

---
Tags: unity, c#, data-structure
---


# Question
Title: Age Rating: female nipples poking through clothing?
Pretty simple and straightforward question, what rating would a game get for something like this?

# Answer
> 4 votes
The age rating system for games and movies is not just a max() function where the highest offending item sets the rating.

Some things will automatically give you an Adult-Only rating and some will automatically go to PG or Teen, but there's a vague point system for intermediate ratings.

These rules changes often and some of the items are somewhat subjective and will be slightly influenced by the reviewer and the target market. Australia, America, Europe, China, Korea, and Japan to name a few regions all have different rating/point systems. It also depends on cultural factors and current political mood.

The answer is there is no answer: For the final items it's often a back-and-forth with the review board (eg: "tone down one of those 3 items") to reach the target age rating.

Poking nipples (regardless gender) are generally around the everyone/teen (age 10-14) rating range due to the surrounding context and overall tone of the game that often goes with it but adding too many other risqué items can raise the rating and even then it varies by cultural region.

---
Tags: content-rating
---


# Question
Title: Why when coloring some objects they are coloring at once fast and not in N seconds?
In the first script I'm doing a reference in the Start for the Colors script: In the Update I did that when i press once on the key C it will StartCoroutine and will change some objects color.

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjectsManipulation : MonoBehaviour
{
    //Scaling
    private Scaling scaling;

    //Lights
    public DimLights dimlights;
    private Coroutine lightCoroutine;

    //Colors
    private Colors colors;

    //Rotating
    private Rotating rotating;

    private void Start()
    {
        scaling = GetComponent<Scaling>();
        scaling.Inits();

        colors = GetComponent<Colors>();
        colors.Initis();

        rotating = GetComponent<Rotating>();
    }

    // Use this for initialization
    void Update()
    {
        //Scaling
        if (Input.GetKeyDown(KeyCode.F))
        {
            //Flip the scale direction when F key is pressed
            scaling.scaleUp = !scaling.scaleUp;

            //Stop old coroutine
            if (scaling.scaleCoroutine != null)
                StopCoroutine(scaling.scaleCoroutine);

            if (lightCoroutine != null)
                StopCoroutine(lightCoroutine);

            //Scale  up
            if (scaling.scaleUp)
            {
                //Start new coroutine and scale up within 5 seconds and return the coroutine reference
                rotating.rotateBack = false;
                scaling.scaleCoroutine = StartCoroutine(scaling.scaleOverTime(scaling.objectToScale, scaling.maxSize, scaling.duration));
                lightCoroutine = StartCoroutine(dimlights.dimLightOverTime(1, scaling.duration));
            }

            //Scale Down
            else
            {
                //Start new coroutine and scale up within 5 seconds and return the coroutine reference
                rotating.rotateBack = true;
                scaling.scaleCoroutine = StartCoroutine(scaling.scaleOverTime(scaling.objectToScale, scaling.minSize, scaling.duration));
                lightCoroutine = StartCoroutine(dimlights.dimLightOverTime(0, scaling.duration)); ;
            }
        }

        //Change color
        if (Input.GetKeyDown(KeyCode.C))
        {
            StartCoroutine(colors.ChangeColor());
        }

        //Rotate
        if (Input.GetKey(KeyCode.R) && !scaling.scaleUp)
        {
            rotating.x += Time.deltaTime * rotating.rotationSpeed;
            scaling.objectToScale.transform.localRotation = Quaternion.Euler(0, 0, rotating.x);
            rotating.keyPressed = true;
        }
        if (Input.GetKeyUp(KeyCode.R))
        {
            rotating.keyPressed = false;
        }

        if (!rotating.keyPressed && !scaling.scaleUp && rotating.rotateBack == false
            && DetectInteractable.detected == false)
        {
            scaling.objectToScale.transform.rotation = Quaternion.LookRotation(Camera.main.transform.forward);
        }

        if (DetectInteractable.detected == true && !scaling.scaleUp)
        {
            rotating.x += Time.deltaTime * rotating.rotationSpeed;
            scaling.objectToScale.transform.localRotation = Quaternion.Euler(0, 0, rotating.x);
        }
    }
}

```

This is the Colors script. I have array of GameObject and i did two foreach loops:

The problem is that it's coloring all the objects at once and I set the colorDuration to 5 seconds. What I want is to color all the objects in the array in 5 seconds in colorDuration. Not each object in the array 5 seconds but all of them together at 5 seconds.

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Colors : MonoBehaviour
{
    public GameObject[] objectsToColor;
    public Color startColor;
    public Color endColor;
    public float colorDuration;

    public void Initis()
    {
        foreach (GameObject rend in objectsToColor)
        {
            startColor = rend.GetComponent<Renderer>().material.color;
        }
        endColor = Color.green;
    }

    public IEnumerator ChangeColor()
    {
        float t = 0;

        while (t < colorDuration)
        {
            foreach (GameObject rend in objectsToColor)
            {
                t += Time.deltaTime;
                rend.GetComponent<Renderer>().material.color = Color.Lerp(startColor, endColor, t / colorDuration);
                yield return null;
            }
        }
    }
}

```

# Answer
> 3 votes
Your coroutine is yielding and increasing the time variable with every object you process. What you likely want to do is, in that order:

1. increase the time variable
2. update **all** the objects
3. and *then* yield until the next frame

Like this:

```
while (t < colorDuration) {

    t += Time.deltaTime;

    foreach (GameObject rend in objectsToColor) {
        rend.GetComponent<Renderer>().material.color = Color.Lerp(startColor, endColor, t / colorDuration);
    }

    yield return null;
 }

```

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


title: OpenGL c++ cube render back issue

text:
# Question
Title: OpenGL c++ cube render back issue
I'm testing on OpenGL and I've created a cube that rotates, but everytime I launch it some weird bugs happens and sometimes opengl gives priority to the back faces and other times it just break and increase screen size.

Here a video showing what happens to me: https://i.gyazo.com/881e352dbf56d4df5b0cefb671e7ebf4.mp4

What can be happening??

I use Glew with GLM for GL, SDL2 for interface and Soil2 for image loading

**Vertex Shader:**

```
#version 330 core

layout (location = 0) in vec3 position; layout (location = 2) in vec2 texCoord;

out vec2 TexCoord;

uniform mat4 model; uniform mat4 view; uniform mat4 projection;

void main() {
    gl_Position = projection * view * model * vec4(position, 1.0f);
    TexCoord = vec2(texCoord.x, 1.0 - texCoord.y); }

```

**Fragment Shader:**

```
#version 330 core

in vec2 TexCoord;

uniform sampler2D ourTexture1;

void main()
{
    gl_FragColor = texture(ourTexture1, TexCoord);
}

```

**Main.cpp:**

```
#include <iostream>
#include <fstream>
#include <string>
#include <glew\include\GL\glew.h>
#include <glm\glm\glm.hpp>
#include <glm\glm\gtc\matrix_transform.hpp>
#include <glm\glm\gtc\type_ptr.hpp>
#include <SDL2\include\SDL.h>
#include <soil2\include\SOIL2.h>
const GLint WIDTH = 800, HEIGHT = 600;
SDL_Window* m_window;
SDL_GLContext m_glContext;
GLuint m_shaders[2];
GLuint m_program;
GLuint m_texture;
static std::string LoadShader(const std::string& fileName) {
    std::ifstream file;
    file.open((fileName).c_str());
    std::string output;
    std::string line;
    if (file.is_open()) {
        while (file.good()) {
            getline(file, line);
            output.append(line + "\n");
        }
    }
    else {
        std::cerr << "Unable to load shader: " << fileName << std::endl;
    }
    return output;
}
static GLuint CreateShader(const std::string& loc, GLenum shaderType) {
    std::string text = LoadShader(loc);
    GLuint shader = glCreateShader(shaderType);
    if (shader == 0)
        std::cerr << "Error creating shader" << std::endl;
    const GLchar* shaderSourceStrings[1];
    GLint shaderSourceStringsLength[1];
    shaderSourceStrings[0] = text.c_str();
    shaderSourceStringsLength[0] = (GLint)text.length();
    glShaderSource(shader, 1, shaderSourceStrings, shaderSourceStringsLength);
    glCompileShader(shader);
    return shader;
}
int main(int argc, char* argv[]) {
    SDL_Init(SDL_INIT_EVERYTHING);
    //From V3.3 to V3.3 with no compat to older versions
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
    SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); //Color Size
    m_window = SDL_CreateWindow("Test",
        SDL_WINDOWPOS_UNDEFINED,
        SDL_WINDOWPOS_UNDEFINED,
        WIDTH,
        HEIGHT,
        SDL_WINDOW_OPENGL);
    SDL_SetWindowResizable(m_window, SDL_TRUE); //Allow resize
    m_glContext = SDL_GL_CreateContext(m_window); //Set GL Context
    glewExperimental = GL_TRUE;
    //Allow textures alpha
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    //Allow Depth
    glEnable(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    if (glewInit() != GLEW_OK) {
        std::cerr << "Failed to init Glew" << std::endl;
    }
    m_program = glCreateProgram();
    //Load Vertex and Fragment Shaders
    m_shaders[0] = CreateShader("core.vs", GL_VERTEX_SHADER);
    m_shaders[1] = CreateShader("core.fs", GL_FRAGMENT_SHADER);
    for (unsigned int i = 0; i < 2; i++)
        glAttachShader(m_program, m_shaders[i]);
    glLinkProgram(m_program);
    glValidateProgram(m_program);
    GLfloat vertices[] = {
        -0.5f, -0.5f, -0.5f,  0.0f, 0.0f,
        0.5f, -0.5f, -0.5f,  1.0f, 0.0f,
        0.5f,  0.5f, -0.5f,  1.0f, 1.0f,
        0.5f,  0.5f, -0.5f,  1.0f, 1.0f,
        -0.5f,  0.5f, -0.5f,  0.0f, 1.0f,
        -0.5f, -0.5f, -0.5f,  0.0f, 0.0f,
        -0.5f, -0.5f,  0.5f,  0.0f, 0.0f,
        0.5f, -0.5f,  0.5f,  1.0f, 0.0f,
        0.5f,  0.5f,  0.5f,  1.0f, 1.0f,
        0.5f,  0.5f,  0.5f,  1.0f, 1.0f,
        -0.5f,  0.5f,  0.5f,  0.0f, 1.0f,
        -0.5f, -0.5f,  0.5f,  0.0f, 0.0f,
        -0.5f,  0.5f,  0.5f,  1.0f, 0.0f,
        -0.5f,  0.5f, -0.5f,  1.0f, 1.0f,
        -0.5f, -0.5f, -0.5f,  0.0f, 1.0f,
        -0.5f, -0.5f, -0.5f,  0.0f, 1.0f,
        -0.5f, -0.5f,  0.5f,  0.0f, 0.0f,
        -0.5f,  0.5f,  0.5f,  1.0f, 0.0f,
        0.5f,  0.5f,  0.5f,  1.0f, 0.0f,
        0.5f,  0.5f, -0.5f,  1.0f, 1.0f,
        0.5f, -0.5f, -0.5f,  0.0f, 1.0f,
        0.5f, -0.5f, -0.5f,  0.0f, 1.0f,
        0.5f, -0.5f,  0.5f,  0.0f, 0.0f,
        0.5f,  0.5f,  0.5f,  1.0f, 0.0f,
        -0.5f, -0.5f, -0.5f,  0.0f, 1.0f,
        0.5f, -0.5f, -0.5f,  1.0f, 1.0f,
        0.5f, -0.5f,  0.5f,  1.0f, 0.0f,
        0.5f, -0.5f,  0.5f,  1.0f, 0.0f,
        -0.5f, -0.5f,  0.5f,  0.0f, 0.0f,
        -0.5f, -0.5f, -0.5f,  0.0f, 1.0f,
        -0.5f,  0.5f, -0.5f,  0.0f, 1.0f,
        0.5f,  0.5f, -0.5f,  1.0f, 1.0f,
        0.5f,  0.5f,  0.5f,  1.0f, 0.0f,
        0.5f,  0.5f,  0.5f,  1.0f, 0.0f,
        -0.5f,  0.5f,  0.5f,  0.0f, 0.0f,
        -0.5f,  0.5f, -0.5f,  0.0f, 1.0f
    };
    GLuint VBO, VAO;
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);
    glBindVertexArray(VAO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid *)0);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid *)(3 * sizeof(GLfloat)));
    glEnableVertexAttribArray(2);
    glBindVertexArray(0); // Unbind VAO
    int width, height;
    unsigned char* image = SOIL_load_image("image1.jpg", &width, &height, 0, SOIL_LOAD_RGBA);
    if (image == nullptr)
        std::cerr << "Texture loading failed" << std::endl;
    glGenTextures(1, &m_texture);
    glBindTexture(GL_TEXTURE_2D, m_texture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image);
    glGenerateMipmap(GL_TEXTURE_2D);
    SOIL_free_image_data(image);
    glBindTexture(GL_TEXTURE_2D, 0);
    ///Object DEPTH_______________________
    glm::mat4 projection;
    projection = glm::perspective(45.0f, (GLfloat)WIDTH / (GLfloat)HEIGHT, 0.1f, 1000.0f);
    ///Object DEPTH_______________________
    while (true) {
        glClearColor(0.55f, 0.55f, 0.55f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        //Set Shader & texture
        glUseProgram(m_program);
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, m_texture);
        glUniform1i(glGetUniformLocation(m_program, "ourTexture"), 0);

        ///Object DEPTH_______________________
        glm::mat4 model, view;
        model = glm::rotate(model, (GLfloat)SDL_GetTicks() * 0.001f, glm::vec3(0.5f, 1.0f, 0.0f));
        view = glm::translate(view, glm::vec3(0.0f, 0.0f, -1.9f));
        GLint modelLoc = glGetUniformLocation(m_program, "model");
        GLint viewLoc = glGetUniformLocation(m_program, "view");
        GLint projLoc = glGetUniformLocation(m_program, "projection");
        glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
        glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
        glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection));
        glBindVertexArray(VAO);
        glDrawArrays(GL_TRIANGLES, 0, 36);
        glBindVertexArray(0);
        ///Object DEPTH_______________________
        SDL_GL_SwapWindow(m_window);
        SDL_Event e;
        while (SDL_PollEvent(&e)) {
            if (e.type == SDL_QUIT) {
                return EXIT_SUCCESS;
            }
        }
    }
    ///TRIANGEL SHADER_______________________
    glDeleteVertexArrays(1, &VAO);
    glDeleteBuffers(1, &VBO);
    ///TRIANGEL SHADER_______________________
    return EXIT_SUCCESS;
}

```

Reading on internet, I found out that faces can be placed to not let that happen... But I found out that the same happens with meshes imported from other places and those have no problem at the time of being rendered in other programs like Blender.

# Answer
This looks to me like a depth buffer issue. Do you have a depth attachment in your FBO? IF so, I don't see where you're setting it up, though I don't know SDL very well. You're enabling depth testing and clearing the depth buffer, but you never set the depth test. That's OK if you want the default. But if you don't have a depth buffer attached, it won't matter.

One other thing you can do is to turn on back-face culling. That will eliminate the need (in this example case) for a depth buffer, though you will generally want a depth buffer for more complex geometry.
> 0 votes

# Answer
It looks like lack of depth buffer or depth test disabled issue, as previous answer said. I'll try to elaborate on cause of that issue.

OpenGL is just triangle (or other primitive) rasterizer. It is drawing triangles in order you send them to it (stored in the buffer), so they are sometimes overlaping. To solve that problem OpenGL has depth testing feature, which before fragment shader kicks in it is testing if something is already written in curent fragment already. if it is, it test (compares depths) if its "closer" to camera than currently drawing fragment.If it is not, than discards it and fragment shader is not firing.

Also a common optimization technique is to sort your scene (usually every frame, and usually objects, not primitives, triangles etc.) front to back, so opengl is mostly drawing triangles that will be visible in the final frame, so you hahe less, what it's called, overflow. Also worth noting that for transparent geometries sorting order must be reversed (back to front) or depth test must be disabled.
> 0 votes

---
Tags: opengl, c++, rendering, glew
---


# Question
Title: move toward object and transition to circling around it.
While it's easy for me to get a object circle around another and move toward it, i've got a few problems I couldn't find a solution to, yet.

Ill go here as follows: I) description of scenario II) problems I currently have

I) Description: My setup consists of multiple things:

1) I have a solar system - basically some planets rotating around the sun in a fixed circular motion with the sun itself unmoving. This one works fine - I currently do it with rotateAround in Unity, but I read into force related methods and I think I'm able to get it designed with forces if needed.

2) Space ships. These ships are either circling around a planet (kind of "i'm stationed here") or moving toward another planet (to station them somewhere else) The movement towards a planet as well as the circling around the planet for itself is easy as far as im concerned.. just some move-toward-point stuff or rotateAround point again. I could those 2 implemented with forces too.

II) the problems I have.

1) I can't get my head around a smooth transition from flying toward a planet into the rotation. My first idea was to use some kind of states for the ships "CIRCLING" and "FLYING" and change the state as soon as the desired orbit height is reached. (btw: I use a 3d environment but for the gamelogic I only require the motion to happen on 2d x-z axis only, if this is important to you). The problem with this is, that it's kind of a 90° turn and really looks bad.

2) the next thing i had was to just add another "Transition" state, when I get close enough, which will handle the smooth movement into the circular motion, but I don't know how to do it.

3) Do I have to care for anything else because the target I want to rotate around is moving itself? (so it doesn't look like they speed up when moving around the planet in same direction of the planets movement, while seeming extra slow when moving against planets movement)? (I ask this, because currently I only work with static planets to get the ships movement correct)

So basically my question is: How can I implement this transition? (I don't care if it is a statebased approach with directly applied position changes (with relation to time for constant speed) or if I have to use rigidbodies and forces or if you come up with something else.)

and as an addition: I also need the ships to avoid planets when travelling somewhere - so I was thinking about using the steering behaviour for collision avoidance, which in my understanding would work well with a force based approach, but I didn't completely wrap my head around that yet. (I don't want an answer to this part here, but wanted to provide you with a more complete specification of problems, which has to be possible to mix into the approach without hacking something together badly ;)).

thanks for any help, advice, links to useful resources :) kind regards

# Answer
Instead of laying your approach vector on the line connecting the target to the current position, lay it along one of the **tangents to the desired orbit** from the current position. Than make just a speed change at the point of tangency.

This is actually quite similar to how real orbital mechanics is performed, so should feel quite natural in addition to being simple to implement.
> 4 votes

---
Tags: movement, steering-behaviors, motion, planet
---


# Question
Title: Is there is a way to mask sprites in Spriter?
I am very new to **Spriter**. I want a sprite to be only displayed when it is above particular sprite.

How can achieve this?

# Answer
> 3 votes
You can't, spriter has no masking. Back in 2013 it was said to be in consideration for future and in 2016 it was said that "There is no masking feature in Spriter" so either they decided not to implement it or it's still up for consideration.

https://steamcommunity.com/app/332360/discussions/0/208684375410361282/ https://brashmonkey.com/forum/index.php?/topic/3131-masking/

---
Tags: sprites
---


title: Moving camera in 3D - directX12

text:
# Question
Title: Moving camera in 3D - directX12
I begin to learn graphic programming on directx12. I try to make a camera wich can move dans rotate around the world.

I take this code as a basis: https://www.braynzarsoft.net/viewtutorial/q16390-transformations-and-world-view-projection-space-matrices

I try lot of method, but every time I finish on the same problem, my camera move and can rotate (on Y only for the moment). But when I move after the control still relative to my basis orientation than my new one.

I dunno if it come from how I handle movement (During waiting answer I will try to make my movement base on a target vector) Or how I multiply martix.

This is the actual point of my code. I use this source to not use LookAtLH(): https://www.3dgep.com/understanding-the-view-matrix/

```
void UpdateCamera() {

    XMVECTOR cUp = XMLoadFloat4(&cameraUp);

    if (GetAsyncKeyState('Z')) {

        cameraPosition.y += 0.001f;

    }
    else if (GetAsyncKeyState('S')) {
        cameraPosition.y -= 0.001f;
    }

    if (GetAsyncKeyState('Q')) {
        cameraPosition.x -= 0.001f;
    }
    else if (GetAsyncKeyState('D')) {
        cameraPosition.x += 0.001f;
    }
    if (GetAsyncKeyState('A')) {
        rotation += 0.0001f;

    }
    else if (GetAsyncKeyState('E')) {
        rotation -= 0.0001f;
    }

   if (GetAsyncKeyState('P')) {
        cameraPosition.z += 0.001f;

   }
    else if (GetAsyncKeyState('M')) {
        cameraPosition.z -= 0.001f;

    }
    XMMATRIX translationMat =     XMMatrixTranslationFromVector(XMLoadFloat4(&cameraPosition));
    /* XMMATRIX rotYMat = XMMatrixRotationAxis(cUp, rotation);*/

    float cosPitch = cos(0.0f);
    float sinPitch = sin(0.0f);
    float cosYaw = cos(rotation);
    float sinYaw = sin(rotation);

    XMFLOAT3 xaxis = { cosYaw, 0, -sinYaw };
    XMFLOAT3 yaxis = { sinYaw * sinPitch, cosPitch, cosYaw * sinPitch };
    XMFLOAT3 zaxis = { sinYaw * cosPitch, -sinPitch, cosPitch * cosYaw };

    XMVECTOR eye = XMLoadFloat4(&cameraPosition);

// Create a 4x4 view matrix from the right, up, forward and eye position vectors
    XMMATRIX viewMatrix = {
        xaxis.x,yaxis.x,zaxis.x,0.0f,
        xaxis.y,yaxis.y,zaxis.y,0.0f,
        xaxis.z,yaxis.z,zaxis.z,00.0f,
        -XMVectorGetX(XMVector3Dot(XMLoadFloat3(&xaxis), eye)), -XMVectorGetX(XMVector3Dot(XMLoadFloat3(&yaxis), eye)), -XMVectorGetX(XMVector3Dot(XMLoadFloat3(&zaxis), eye)), 1.0f
    };

    XMStoreFloat4x4(&cameraViewMat, viewMatrix);// XMMatrixInverse(nullptr, translationMat * rotXMat));

}

void Update()
{

    UpdateCamera();
     ///....

}

```

# Answer
> 0 votes
My hint was good, it's come from how I do the position update. There is the correct code. By this way I can keep the local coordonate with cUp, cTarg and cPos

```
void UpdateCamera() {

    // Get Datas
    XMMATRIX viewMatrix = XMLoadFloat4x4(&cameraViewMat);

    //Move Up and bottom
    if (GetAsyncKeyState('Z')) {
        viewMatrix *= XMMatrixTranslation(0.0f,-0.0001f,0.0f);
    }
    else if (GetAsyncKeyState('S')) {
        viewMatrix *= XMMatrixTranslation(0.0f, 0.0001f, 0.0f);
    }

    //Move Right and Left
    if (GetAsyncKeyState('Q')) {
        viewMatrix *= XMMatrixTranslation(0.0001f, 0.0f, 0.0f);
    }
    else if (GetAsyncKeyState('D')) {
        viewMatrix *= XMMatrixTranslation(-0.0001f, 0.0f, 0.0f);
    }

    //Move forward/Backward
    if (GetAsyncKeyState('P')) {
        viewMatrix *= XMMatrixTranslation(0.0f, 0.0f, -0.0001f);
    }
    else if (GetAsyncKeyState('M')) {
        viewMatrix *= XMMatrixTranslation(0.0f, 0.0f, 0.0001f);
    }

    //Rotate Y axis
    if (GetAsyncKeyState('A')) {
        viewMatrix *= XMMatrixRotationY(0.0001f);
    }
    else if (GetAsyncKeyState('E')) {
        viewMatrix *= XMMatrixRotationY(-0.0001f);
    }

    //Rotate X axis
    if (GetAsyncKeyState('R')) {
        viewMatrix *= XMMatrixRotationX(0.0001f);
    }
    else if (GetAsyncKeyState('T')) {
        viewMatrix *= XMMatrixRotationX(-0.0001f);
    }

    //Rotate Z axis
    if (GetAsyncKeyState('F')) {
        viewMatrix *= XMMatrixRotationZ(0.0001f);
    }
    else if (GetAsyncKeyState('G')) {
        viewMatrix *= XMMatrixRotationZ(-0.0001f);
    }

    //Update View Matrix of Camera
    XMStoreFloat4x4(&cameraViewMat, viewMatrix);
}

```

Link to the project : https://github.com/Zeldarck/TrainingDx12

---
Tags: directx, camera, rotation, transformation
---


# Question
Title: How do I discourage "loot from party members who are about to leave" behavior?
In my RPG, I have companion characters that can potentially leave the party. A behavior I have witnessed among testers is something that I think many RPGs deal with, namely that players will strip the party members of all equipment before they leave the party. For instance:

* One tester removed all gear from a companion, then talked to them and chose the "I want you to leave" dialogue option.
* Another tester saw that a companion was removed from the party via a scripted event, then loaded to an earlier save, stripped the gear from the companion, then re-played the scripted event.

I want to avoid this behavior because it encourages meta-gaming/save-scumming and breaks immersion. If this were a real life group of medieval adventurers, one of the group members wouldn't be ordered to strip down to their underwear moments before being ambushed and captured.

I don't want gear to be "stuck" on a character so that it can never be upgraded (I once played an RPG where I was frustrated that my companion had mediocre armor, but I wasn't permitted to swap it for superior armor I found later).

Is there any way that I can get the best of both worlds by allowing character equipment to be improved, while preventing (or at least limiting the incentive) to meta-game/save-scum and loot characters who are about to leave?

# Answer
As Charanor and Philipp point out in other comments & answers, there is a school of thought in game design (called "Love the Player" in my studio) that says if the player wants to do something that doesn't break the game for other players, err on the side of letting them do it. Players who see a kidnapping twist coming and strategically prepare for it get to feel smart, rather than powerless, and you avoid creating a situation where the player's one-of-a-kind ultra-rare gear can be lost forever without recourse, without needing to create extra systems to protect against this. That's a valid approach to this design problem.

There's another school of thought, articulated in Soren Johnson's article "Water Finds a Crack," that says that players are drawn to choices that give them a material benefit in games, even to the detriment of their own enjoyment. Players tend to undervalue their subjective experience and time investment relative to things they can quantify in a game, like the value of gear. This means that some players who would normally leave the gear on - for reasons of role-playing immersion, or just to avoid extra menu fiddling - can feel pressured to play differently because that's the "wrong" choice according to the numbers.

If this proves to be a concern for your target audience (validate this by polling testers on their subjective impressions - if they're engaging in gameplay you'd consider "wrong," but enjoying it all the same, then maybe it's not a problem for them), there are things we can do to address this dissonance.

The other answers do a great job covering several different approaches, so I want to suggest just one more: **narrow the gap between the player's reality and the character's.**

> If this were a real life group of medieval adventurers, one of the group members wouldn't be ordered to strip down to their underwear moments before being ambushed and captured.

Why not? What consequences lead the characters to make different decisions than players in this case? And how can we reintroduce those consequences into the player's view of the situation? Some thoughts:

* **Morality:** taking all your ally's stuff and leaving them to rot is a pretty dick move. It could sit poorly with a character's conscience or moral code (alignment system) or affect how likely other people are to trust them (reputation system) or possibly even invite retribution from the wronged party and their allies (revenge system)
* **Uncertainty:** the characters don't know when the ambush will happen, so they can't plan for it. Taking away useful gear on just the possibility that a character might get abducted means their utility and survivability in fights leading up to that event are greatly reduced. Set the abduction scene to happen sometime randomly within a gauntlet of several encounters with no save point in-between, and you put even a player with access to walkthroughs in a similar position. It's still possible to savescum it, but the increased difficulty/time investment can help players who aren't really there for the hyper-optimization to resist the temptation.
* **Future Payoff:** If I leave a companion with good gear, I can hope they'll survive long enough to meet & help me again. Or for them (or their next of kin) to repay my generosity in other ways. Make the gear the character left with matter in some way - maybe you play a short vignette mission as that character while they're separated from the group, so stripping them down before that actually makes this harder to proceed (just beware of trapping a hasty player in an unwinnable situation if they can't backtrack/reload to before the split). Or maybe you model the chance the character survives, or their prosperity while they're away from the group, based on a function of the gear they were left with. A sidekick let loose with good gear is more successful in developing their skills and is higher-level / has even better gear when you next meet them, for example.
> 92 votes

# Answer
There are multiple design constraints, each of which can be solved independently. It's up to you to decide how to solve each one, in a way that makes sense for your game.

> \[I want to discourage\] meta-gaming/save-scumming

The Quality of Life solution would be to automatically strip the companion's gear.

> Breaking immersion

If the departure was voluntary, this can be explained away as the gear being owned by the party, not the companion. Or just a line of dialog like "Take my gear, I don't need it anymore."

If the departure was involuntary, rewrite the event to explain why the companion had no gear - e.g. they were kidnapped in their sleep.

> Being naked

Most RPGs don't allow characters to be naked; they have a default set of clothes underneath the armor. Alternately you can keep them dressed in worthless clothes, nightgowns or the like, depending on how they left the party.

> I don't want gear to be "stuck" on a character so that it can never be upgraded

You have some alternatives to this:

* Character-specific gear. This reduces the impact of losing a companion's gear along with them, as it's worth much less without anyone to use the gear. Works even better if your game economy doesn't depend on selling gear.
* "Gear" as permanent upgrades. You mentioned not being upgradable as a negative, but that's not something you have to have. You can still upgrade your mediocre armor with superior armor, but whatever armor you equip cannot be taken off. This is easier to explain if instead of equipping "gear", your game is about teaching "skills".
> 29 votes

# Answer
This behavior is completely understandable. After all, nobody wants to lose an irreplaceable item forever because they made the mistake of having it on the wrong character at the wrong time.

There are several solutions I could think of:

* Instead of fighting against your player's drive to optimize the fun out of your game, just give them what they want. When a character leaves the party, put all their unique items into the party inventory and leave the character with their default gear. This is not all that unrealistic. After all, most of their gear was obtained with the resources of the party, so the party owns it. And the remaining party members are those who continue saving the universe, so they have far more use for that +10 Sword of Slaying Everything Except Squid.
* When that's not plausible (for example because the departure from the party comes as a surprise), make sure that it happens immediately after a difficult fight which would be next to impossible without having complete gear.
* When you really want to encourage players to let departing characters leave with powerful items and be happy about it, reward them for doing so. For example, characters currently swapped out of the active party could collect resources and progression points offscreen. The better their equipment, the more successful they are. This would work best if you allow players to re-recruit any characters they send away and micro-optimize this mechanic through strategic swapping of equipment between active-party and off-party characters.
> 19 votes

# Answer
**Fire Emblem: Genealogy of the Holy War** (never released outside of Japan) has a couple of mechanics to stop people from looting their party members.

1. Restrict trading.
Party members can only trade items with their lover (and possibly siblings). Other than that, the only way to trade is to sell the item, then have someone else buy it back. Each party member has their own purse, and trading money is not possible.
2. Characters return.
One of the characters who leave the party actually returns in a later chapter. When he does, he is isolated from the party and has to protect a potential new party member from enemies. He also returns with the same level, experience points, and inventory as when he left. Looting him (or not letting him gain experience) before he leaves makes it harder for him to survive until the party reaches him.
3. Items are inherited.
*Genealogy of the Holy War* is famous for spanning 2 generations. There is a relationship system, where male characters and female characters can fall in love with each other and become lovers. One of the benefits of that system allows you to recruit their children after they leave the party. The children inherit several things from their parents, including inventory. Most of the children start in a location that is isolated from the party, so inheriting proper gear may be critical to their survival (until they're recruited).
> 10 votes

# Answer
As as spin on @Chris's comment to @congusbongus's answer: Model your answer on real life Military or other similar organizations.

**Military, Police Units, Mercenary outfits**

As a military person myself - I "own" my uniform. My dress blues. My cammie jacket and boots. The government owns the M16, grenade launcher and body armor.

I got training in how to use an M16, grenades and have worked to get strong enough to use them in day-to-day situations... when I leave, that training and core strength is mine... The gear isn't.

If I leave the Military and go into a Mercenary unit... I wouldn't arrive with the weapons I used in the Military. I would arrive with my clothes and my skills - and the mercenary unit would provide the weapons and further training.

Thinking back at history... I would assume a Knights Templar would be in the same boat - the clothes, strength and skills are his. The plate armor and sword belongs to the Crown.

**That distinction could be carried to your game.**

Craft the gear such that the "company" (IE: The players party) owns the armor and weapons... the "companion" (IE: Trained Mercenaries) brings basic clothing (so they aren't naked when they arrive/leave), skills and strength...

During the course of adventuring, the companion gets paid, gets stronger and improves... but gear improvements are provided by the "Company" - and as such, stay when the companion leaves.

At that point, it's no longer a matter of question what belongs to who. There is "real world" precedence and expectations.

**The "organization" owns the gear and the "individual" gets stronger/smarter/better**

Same can be applied to scientists who use company microscopes, doctors who use the hospitals stethoscope and chefs who use company knives.
> 9 votes

# Answer
Rather then giving the player full inventory management over the companion, make gear sharing into a goodwill based trading system. You give items to the companion, which increases your goodwill with them based on how good the item is, and you request items from the companion and you will lose goodwill based on how good it is.

The NPC will just equip whatever gear it thinks is best out of the stuff it has, and might give you stuff back if it can't carry all the gear it has. It might even swap out gear dynamically based on the challenges it faces, which might even teach the player a thing or two about the world.

When the NPC leaves, pop up a dialog to trade with them one last time. Then you can spend whatever goodwill you still have with them to reclaim good items and they leave with the rest. You could even allow a gear-swap when they are kidnapped (maybe, if that breaks immersion too much, or would spoil the surprise, you can even do it in a flashback after the event ended. "Earlier that morning: 'Hm, I have a bad feeling about today. Want to do a gear check? We should do one, just to be sure.' ")

Of course, you could also earn goodwill for doing things that make the NPC happy and lose it if you do things to upset them. This means that if you treat the NPC well, they will happily give you all their stuff when they leave, and if you treat them like crap, all their gear will be locked in when they go. This might also increase immersion by getting players to consider their actions in terms of their companions.
> 8 votes

# Answer
If it's a situation where the character would realistically have time to change clothes before leaving, **automatically give back the gear**! The characters can just as easily demand the return of their gear as the player can.

However, the character likely wouldn't to willing to walk off naked. For the sake of realism, **have them reclaim the gear they joined the party with** (provided they still want it). If someone else is wearing it, they'll just have to give it back.

Ambush scenarios are a little different. If a character is suddenly dragged off, there's no time to change clothes... but you can relieve the pressure to savescum by making it immediately clear in the dialogue that you will be **getting that gear back**. (And be quick about giving the gear back to the player - even if the character remains kidnapped for the rest of the plot, the player can find the character's discarded gear at the end of a brief, unsuccessful rescue attempt.)

---

I saw the "automatically give back the gear" game mechanic recently in the game "World's End". They didn't get fancy with it - the game would give all the character's gear to the player immediately regardless of why the character left - but it worked well enough to prevent savescumming.
> 7 votes

# Answer
You could have NPCs value their own items, have limits on what they're willing to give up (and the state you're leaving them in - did you take what they need to get by without you?), and/or keep track of what they've given to the players, and ask for it (or some fair compensation) when they part ways from the players.

I'd recommend having it based on their value/attachment to different items, and perhaps also what else they've gained or lost, and their feelings for the player, so that their reaction is not unreasonable (*"how DARE you not give me back that rope!"*) but also there's a reasonable limit to how much the players can take from them.

It's the kind of thing that will interest some players and end up with them studying how the system works and posting about it. (So I'd add a bit of randomness, so it's not something players can calculate with ridiculous precision.) But if you do a nice job of it, you could earn some great respect.
> 4 votes

# Answer
I would expand on one point in @congusbongus' answer, namely the "gear as permanent upgrades" point. One way of going about this would be as an in-world interaction rather than a pure game mechanic. Make it so that the companion is not willing to simply give up certain types of gear, but is willing to exchange them:

> "I will not give you my sword, we all know the world's too dangerous to walk around unarmed. But I can swap it with you for a mace, if that's what you prefer."

You could have certain value/stat minima for each character, probably equal to their starting gear:

> "Do you take me for a fool? I am a valiant warrior and will never wield such a shoddy dagger instead of my fine waraxe!"

Some gear should still be "strippable" (probably consumables), potentially with a numerical limit or similar:

> "You can have some of my healing potions, but I will need at least three to feel safe."

This could be expanded if desired to things like some companions valueing weapons over armor, some hoarding scrolls, etc., to give them an individual touch of personality.

This way, the player can still optimise somewhat if they feel they want to (e.g. if their enjoyment is Challenge and they like being as best prepared as possible), but the gain is not big enough to make Fantasy seekers feel they're missing out by behaving realistically.
> 2 votes

# Answer
Instead of equipping the companions with "party gear" as if they were a permanent part of your party, why not make the distinction that they're outside of the core party and have the party choose to either give or lend them gear. This allows them to dump off items of little worth to the companions if they want to, or to give them powerful items for as long as they remain with the party.

So instead of having to anticipate a character leaving, or having to reload a save to deal with an impending party split, just have the character give back any lent items before they leave.

> "I'm sorry we have to part ways, allow me to return these borrowed items..."
> 2 votes

# Answer
Maybe you can give them something based on the gear the character left with. I for one always display the behaviour you just described, I never allow a character to leave with my best gear, specially if that gear was hard to get, otherwise I would feel shortchanged from the game and might even stop playing. But maybe if there is some sort of reward for letting the character go with his gear players might allow that to happen. Though signalling that to players might break immersion even more.
> 1 votes

---
Tags: game-design, rpg, npc
---


# Question
Title: Change shadervalues for different Meshes in Three.js
Hey I am writing a Shader for Three.js.

My goal is to have multiple objects with the same shader and each object should have a color set on the object that is then given to the shader. The goal is to have multiple "units" (think of an RTS game) each with the team color.

I red through a couple of documentation pages and am not really sure how to handle that. I looked into https://threejs.org/docs/#api/materials/ShaderMaterial.

I have tried:

* changing a `uniform` but from my limited knowledge and trial and error I came to the conclusion that I can not change a uniform value during a drawcycle.
* change the uniform in onBeforeRender which gave me an error that v was not defined

I am not sure how to go on now. In the ShaderMaterial Documentation is written:

> You're recommended to update custom Uniform values depending on object and camera in Object3D.onBeforeRender because Material can be shared among meshes, matrixWorld of Scene and Camera are updated in WebGLRenderer.render, and some effects(ex:VREffect) render a scene with private their own cameras.

So did I just change the values wrong and it actually works with a uniform that changes? In this Github issue someone wanted to draw meshes in different colors and got suggested to create different materials for each mesh (https://github.com/mrdoob/three.js/issues/1532). But that would kill the idea of having one shader per unit regardless of the team.

# Answer
Thanks to gman for the help:

> You would have one material per object you're drawing. In the page you linked the top screenshot shows 5 people in different colors so you'd have 5 materials, one for each person with that person's color settings. If you want to change the color of one person you just need to set that person's material colors. Each person would have a mesh. Each Mesh would use the same Geometry but that person's Material. 1 Geometry, 5 Materials, 5 Meshes

And here is the solution:

Prepare the different Materials with the same uniform names.

```
let team1knightUniforms = {
        textureKnight:
        {
            type: "t",
            value: THREE
                .ImageUtils
                .loadTexture("objects/customObjs/knight/Myknight.png")
        },
        teamcolor:
        {
            value: new THREE.Color(options.teamcolor1)
        }
    };

let team1KnightMaterial = new THREE.ShaderMaterial(
    {
        vertexShader:
            document
            .getElementById("teamcolorVertexShader")
            .textContent,
        fragmentShader:
            document
            .getElementById("teamcolorFragmentShader")
            .textContent,
        uniforms: team1knightUniforms
    }
);

let team2knightUniforms = {
        textureKnight:
        {
            type: "t",
            value: THREE
                .ImageUtils
                .loadTexture("objects/customObjs/knight/Myknight.png")
        },
        teamcolor:
        {
            value: new THREE.Color(options.teamcolor2)
        }
    };

let team2KnightMaterial = new THREE.ShaderMaterial(
    {
        vertexShader:
            document
            .getElementById("teamcolorVertexShader")
            .textContent,
        fragmentShader:
            document
            .getElementById("teamcolorFragmentShader")
            .textContent,
        uniforms: team2knightUniforms
    }
);

```

Then add the object twice and asign the different Materials. The Materials do have the Texture and uniform names in common:

```
let objFile = "objects/customObjs/knight/Myknight.obj";
let loader = new THREE.OBJLoader();
loader.load( objFile, function( object )
{
    object.children.forEach( function (obj, index)
    {
        obj.material = team1KnightMaterial;
        obj.position.x = 5;
        obj.position.z = 5;
        obj.teamNumber = 1;
        objects.push( obj );
    });

    shaderExampleScene.add(object);
});

loader.load( objFile, function( object )
{
    object.children.forEach( function (obj, index)
    {
        obj.material = team2KnightMaterial;
        obj.position.x = 5;
        obj.position.z = 10;
        obj.teamNumber = 2;
        objects.push( obj );
    });

    shaderExampleScene.add(object);
});

```

Finally the Fragmentshader picks up the uniform and mixes the color in where Alpha is getting transparent:

```
precision mediump float;
uniform sampler2D textureKnight;
uniform vec3 teamcolor;

varying vec2 vUv;

void main()
{
    vec4 fragColor = texture2D(textureKnight, vUv);
    fragColor.r = fragColor.r * fragColor.a + teamcolor.r * ( 1.0 - fragColor.a);
    fragColor.g = fragColor.g * fragColor.a + teamcolor.g * ( 1.0 - fragColor.a);
    fragColor.b = fragColor.b * fragColor.a + teamcolor.b * ( 1.0 - fragColor.a);
    gl_FragColor = fragColor;
}

```
> 1 votes

---
Tags: shaders, fragment-shader, webgl, three.js
---


# Question
Title: Create rotation in random direction from existing rotation
I am working on a game in Unity, and I currently have a game object (object A) located at the origin. I have a child of this game object (object B), that is 10 units back on the z-axis. When I rotate object A, it causes object B to orbit at 10 units from the origin.

With that being said, I have many game objects that orbit this same way. I want (at any point in time) to be able to spawn a new game object a certain distance away from object B. This certain distance is really going to be something like 60 degrees around the sphere in any random direction from object B. So when I create a new game object, I will create a new pivot point object (object C) and a new child of that pivot point (object D) at 10 units away on the z-axis.

I know I need to create a new rotation from the current rotation of object A, but this needs to be in a a random direction and the new rotation should be 60 degrees in that direction.

Let me know if that doesn't make sense, or if you need any other information.

I am not really sure how to even go about determining these rotations, but I am currently trying to use Unity's Quaternion class which I believe will work, but I think I need to step back and see if anyone else has a better way to go about this.

Appreciate the help!

# Answer
> 1 votes
For anyone who is curious, here is what I ended up doing.

I created a new rotation using `Quaternion.AngleAxis`:

```
Quaternion.AngleAxis(60f, Random.insideUnitCircle);

```

I get a random direction (axis) by using `Random.insideUnitCircle`. Then I pass how many degrees I'd like to rotate in that direction. This returns a new quaternion with the proper rotation.

The last thing I needed to do is combine the new rotation with the current rotation of object A so that the new rotation is "relative" to the rotation of object A. This is done by multiplying the two rotations:

```
var newRotation = objectA.transform.rotation * Quaternion.AngleAxis(60f, Random.insideUnitCircle);
objectC.transform.rotation = newRotation;

```

---
Tags: unity, rotation, quaternion, random, direction
---


# Question
Title: Correcting for a collision overlapping too much?
I have a TileMap with a TileMapCollider2D and a Sprite with a BoxCollider2D. I'm not using physics at all so I'm correcting for the collision on my own. Here's my attempt:

```
void FixedUpdate() {
    float h = Input.GetAxis("Horizontal") * Time.deltaTime * this.Speed;
    float v = Input.GetAxis("Vertical") * Time.deltaTime * this.Speed;
    Vector3 pos = this.transform.position;
    pos.x += h;
    pos.y += v;

    foreach (Tilemap map in this.Maps) {
        TilemapCollider2D mapc = map.GetComponent<TilemapCollider2D>();
        ColliderDistance2D dist = this.boxCollider.Distance(mapc);
        if (dist.isOverlapped && dist.isValid) {
            Debug.DrawLine(dist.pointB, dist.pointA, Color.white);
            Vector2 correction = dist.normal * dist.distance;
            pos += (Vector3)(correction);
        }
    }

    this.transform.position = pos;
}

```

This logic is on the blue square in this gif:

According to the documentation, `dist.normal * dist.distance` should be exactly the distance and direction required to make the two colliders touch. However you can see that I can push a few pixels into the red walls. When I release the button it takes several frames to back out of the wall. It goes a little haywire too when I go diagonally into the corner.

# Answer
The problem is that you are doing a hit test with the current position of the object, not the position of the object offset by the input. The simplest solution would be to set the position multiple times, once before doing hit testing and once after each tilemap. The reason it slides out over a few frames is likely due to input gravity.

```
void FixedUpdate() {
    float h = Input.GetAxis("Horizontal") * Time.deltaTime * this.Speed;
    float v = Input.GetAxis("Vertical") * Time.deltaTime * this.Speed;
    Vector3 pos = this.transform.position;
    pos.x += h;
    pos.y += v;

    //add this line or something similar
    this.transform.position = pos;

    foreach (Tilemap map in this.Maps) {
        TilemapCollider2D mapc = map.GetComponent<TilemapCollider2D>();
        ColliderDistance2D dist = this.boxCollider.Distance(mapc);
        if (dist.isOverlapped && dist.isValid) {
            Debug.DrawLine(dist.pointB, dist.pointA, Color.white);
            Vector2 correction = dist.normal * dist.distance;
            pos += (Vector3)(correction);
            //Need it here too
            this.transform.position = pos;
        }
    }
}

```

Note that you may need to use `Rigidbody2D.MovePosition` instead of setting `transform.position` for the hit testing to work correctly immediately.
> 2 votes

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


# Question
Title: Problem getting in adjust the image in drawable canvas
I am working on the game which i develop on android and i am just stuck on adjust the images. I want the spinning ball image in center where i targeted the red color on the given image and the both bottom left and right player images on yellow mark on the given images.

Here is the some code i used for dice and the player :-

Dice :-

```
dice.get(0).setPosition((gWidth + dice.get(0).getWidth()) / 300,
                    (gHeight + dice.get(0).getHeight()))

```

Player 1 and player 2 :-

```
male = BitmapFactory.decodeResource(getResources(), R.drawable.male);
    canvas.drawBitmap(male, 0, canvas.getHeight() - male.getHeight(), null);
    female = BitmapFactory.decodeResource(getResources(), R.drawable.female);
    canvas.drawBitmap(female, canvas.getWidth() - female.getWidth(), canvas.getHeight() - female.getHeight(), paint);

```

# Answer
> 1 votes
Drawing the ball in the middle should be pretty straight-forward. The pseudocode would look something like this:

```
// Center of your screen
float positionX = (canvas.getWidth() - ball.getWidth()) / 2f;
// 28% above the bottom of your screen. Should be almost correct.
// Change to whatever number works.
float positionY = canvas.getHeight() * 0.72f - ball.getHeight();
ball.setPosition(positionX, positionY);

```

That should place the ball in the middle and a bit above the bottom of your screen.

When placing the player images you just have to offset their x-position by their width. Something like this:

```
// All the way to the left
float maleX = 0;
// Same height as the ball
float maleY = canvas.getHeight() * 0.72f - male.getHeight();

// Offset by male width to place next to male
float femaleX = male.getWidth();
// Same height as male and ball
float femaleY = canvas.getHeight() * 0.72f - female.getHeight();

// Draw male and female
canvas.drawBitmap(male, maleX, maleY, null);
canvas.drawBitmap(female, femaleX, femaleY, null);

```

These code snippets are of course just pseudo code and you will have to manually change some numbers so that they work. I've also assumed a top-down y-coordinate system where the origin in the top left corner and the origin of the images is the bottom left corner because it seems like this is the case from your examples.

---
Tags: java, android, android-studio
---


# Question
Title: Orthographic Projection with variable FOV
We are building agame with orthographic view. The problem we face is the fact that with different resolution you can see different area of the game world. E.g. if you have higher resolution you can see more around you. To solve this we currently use a common scale factor that every model is scaled by, depending on resolution. But this has drawbacks when drawing shadows - I cannot set a higher view angle for the orthographic shadow camera, while when using the perspective shadow camera I get significantly worse shadow quality.

So the question is is there any way to controll FOV when using orthographic projection, or, more specifically, what is the easiest way to scale the world uniformly up or down with orthographic projection matrix?

I saw that in 3ds MAX you can control FOV for an orthographic camera I wonder how they implemented it.

# Answer
> 4 votes
In order to scale the projection generated by `glOrtho`, `glm::ortho` or any other framework, you just need to divide `left/right/top/bottom` or `width/height` by your scaling factor. So if for instance your code looks like this:

```
proj_matrix = glm::gtc::matrix_transform::ortho(-320, 320, -200, 200);

```

and you want a “fov” X times as large, you just need to use this instead:

```
proj_matrix = glm::gtc::matrix_transform::ortho(-320 * X, 320 * X, -200 * X, 200 * X);

```

Component-wise, this will *divide* the first two *diagonal terms* of the resulting matrix by X.

# Answer
> 2 votes
> Is there any way to control Field of View when using orthogonal projection ?

```
| 1/r 0        0       0     |
| 0   1/t      0       0     |
| 0   0    -2/(f-n) -f+n/f-n |
| 0   0        0       1     |

```

Looking at the orthographic (symmetric) projection matrix above it is a combination of scaling matrix and a translation matrix, and unfortunately doesn't define a field of view. Field of view is a feature for projections that simulate how a human being eye sees the world (e.g. perspective projection).

> What is the easiest way to scale the world uniformly up or down with orthogonal projection matrix?

Since you are already using an orthographic projection, which is technically a scaling matrix I would say changing the values of the orthographic matrix by multiplying/dividing the scaling components of the above matrix with some scaling factor. ( I am not assuming you are using a specific library).

> But this has drawbacks when drawing shadows ?

Depending on the shadow algorithm you are using, (I suspect shadow maps) maybe you can change the shadow map resolution depending on the screen resolution as to get more consistent quality.

# Answer
> 0 votes
Orthographic projection has no concept of a FOV, because by definition an orthographic viewing volume is cubic.

Increasing FOV modifies the viewing volume of perspective projection by "increasing the spread" of the view frustum (pyramid).

The FOV of an orthographic projection is actually 0, because the "pyramid" (cube, really) of an orthographic projection does not spread at all.

You need to mod your scaling factor as Sam said.

# Answer
> 0 votes
All answers here are great. Another explanation: Orthographic projection is the result of `lim(fov->0)` and `lim(d->infinity)`, where `d` is the view distance. Thus, you can think of the fov being fixed by the choice of this projection. That is why photographers sometimes prefer longer focal length (smaller fov) and increase the distance to the object: parallel lines stay more parallel with longer focal length.

---
Tags: matrix, projection
---


# Question
Title: Why can I not save preferences on Android?
I'm using the code in this tutorial (Full LibGDX game tutorial). The code to save the preferences works fine on Desktop but not on Android. Here's how I access and save my preferences:

```
public class AppPreferences {
private static final String PREF_MUSIC_VOLUME = "volume";
private static final String PREF_MUSIC_ENABLED = "music.enabled";
private static final String PREF_SOUND_ENABLED = "sound.enabled";
private static final String PREF_SOUND_VOL = "sound";
private static final String PREFS_NAME = "b2dtut";

protected Preferences getPrefs() {
    return Gdx.app.getPreferences(PREFS_NAME);
}

public boolean isSoundEffectsEnabled() {
    return getPrefs().getBoolean(PREF_SOUND_ENABLED, true);
}

public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
    getPrefs().putBoolean(PREF_SOUND_ENABLED, soundEffectsEnabled);
    getPrefs().flush();
}

public boolean isMusicEnabled() {
    return getPrefs().getBoolean(PREF_MUSIC_ENABLED, true);
}

public void setMusicEnabled(boolean musicEnabled) {
    getPrefs().putBoolean(PREF_MUSIC_ENABLED, musicEnabled);
    getPrefs().flush();
}

public float getMusicVolume() {
    return getPrefs().getFloat(PREF_MUSIC_VOLUME, 0.5f);
}

public void setMusicVolume(float volume) {
    getPrefs().putFloat(PREF_MUSIC_VOLUME, volume);
    getPrefs().flush();
}

public float getSoundVolume() {
    return getPrefs().getFloat(PREF_SOUND_VOL, 0.5f);
}

public void setSoundVolume(float volume) {
    getPrefs().putFloat(PREF_SOUND_VOL, volume);
    getPrefs().flush();
}
}

```

# Answer
On Android, *for some reason* you have to store the reference to the `Preferences` object instead of accessing it using `Gdx.app.getPreferences(PREFS_NAME)`. It probably has to do with how Android's built-in preferences work and how `getPreferences` interracts with it but I am unsure of the exact reason why. To solve this simply make this change:

```
private Preferences preferences;

protected Preferences getPrefs() {
    if (preferences == null)
        preferences = Gdx.app.getPreferences(PREFS_NAME);
    return preferences;
}

```
> 4 votes

---
Tags: libgdx
---


# Question
Title: Does scene2d(libGDX) know when an image is drawn out of the screen?
I mean, I want to make a tiled map using scene2d, so in the render method of my game...

```
@Override
public void render(float delta) {
    Gdx.gl.glClearColor(0.5f, 0.5f, 0.5f, 1f);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    gameStage.getCamera().position.set(player.getX(), player.getY(), 0);
    gameStage.act(Gdx.graphics.getDeltaTime());
    gameStage.getBatch().begin();
    for(int i=0;i<20;i++)
        for(int j=0;j<20;j++)
            gameStage.getBatch().draw(tile,i*tileSize,j*tileSize,tileSize,tileSize);
    gameStage.getBatch().end();
    gameStage.draw();
}

```

Does scene2d know if the tile is out of the screen view, so it does not draw it, or do I have to implement code to fix it?

Sorry for my English.

# Answer
> 2 votes
Scene2D already checks if an Actor is on your viewport or not. You don´t need to code that.

**Edit:** I´m searching on the Scene2D documentation about this, I can´t find it, but I know it is true, if someone can help me and link it, that would be nice :) I think it is necessary to add a reference to the documentation for this answer.

# Answer
> 1 votes
Yes, it does.

But in case you want to be sure, you can check it yourself using Frustrum to compare performances.

(If using Frustrum increases performance, then it Scene2D does not check if an actor is on screen or not, renders everything, but this won´t happen).

Frustum

# Answer
> 0 votes
Like the two other answers has said it does know when an `Actor` is outside its culling area.

**However** your `tile` is a Texture - **not** an Actor! Textures **will not** be automatically culled when drawn outside of the screen. You're also using a `SpriteBatch` to draw the tile, not a `Stage`. SpriteBatches does not have any built-in culling either.

So in conclusion your tile map will **not** be automatically culled when outside of the viewport area. This can, however, be implemented however using the built-in `ScissorStack` class as long as you remember to do it every time you move your camera.

```
Rectangle out = new Rectangle(); // Will be assigned by the function call
float viewportWidth = camera.viewportWidth;
float viewportHeight = camera.viewportHeight;
float viewportX = camera.position.x - viewportWidth /2f;
float viewportY = camera.position.y - viewportHeight /2f;

ScissorStack.calculateScissors(camera,
                               viewportX, viewportY,
                               viewportWidth, viewportHeight,
                               camera.combined,
                               new Rectangle(0, 0, viewportWidth, viewportHeight),
                               out);

ScissorStack.pushScissors(out); // Activate culling

// If you need to reset the culling you have to remove it first
ScissorStack.popScissors();

```

---
Tags: java, android, libgdx, tiles, spritebatch
---


# Question
Title: Make a background Image to fit multiple objects?
In the Hierarchy, I have a `GameObject` named "Buttons" to which I added an `Image` component.

I would like that the `ok` sprite to cover (be background of) all the buttons: `START GAME`, `OPTIONS`, `CREDIT` and `EXIT`.

But the `ok` sprite is somewhere in the top left corner behind the `START GAME` button on its left side and is very small. This happened when I clicked in the Inspector in `Image` on `Set Native Size`.

I want to make it big enough to cover all the buttons but I'm not sure how.

# Answer
You can simply stretch the image using anchor presets. Hold `alt` (important!) and click on the blue box in the bottom right corner. This will stretch the UI element so that it fills the entire area.
> 1 votes

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


# Question
Title: Do you need special permission to personify companies as characters?
in the *Hyperdimension Neptunia* series a number of human characters are personifications of games companies ie.

* Compa = Compile Heart
* Red = Red Entertainment
* Tekken = Namco
* Falcom = Nihon Falcom
* Cave = CAVE Interactive
* IF (Iffy) = Idea Factory
* Nippon Ichi-chan/Nisa = Nippon Ichi Software/Nippon Ichi Software America

I am wondering if the creators of *Hyperdimension Neptunia* had to get special permission/licences from companies to personify them in the game? (ie. a developer personifying Valve or Square in their own game)

# Answer
> 5 votes
**TL;DR:** When you have to ask anonymous strangers on the Internet about this because you can not afford a lawyer, you shouldn't do it.

---

Parody is a legal minefield where laws around the world differ a lot and where judges often have a lot of room for interpretation.

Generally, using the exact name of someone *can* be a trademark violation if you use that name to advertise the product and give the impression that your product is endorsed by whoever's name you use. That's why many parodies slightly change any brand names they parody.

Another thing you have to be careful about is that if you portray a brand too negatively, you might be hit with a defamation lawsuit.

And then there is copyright. If you use any intellectual property created by the subjects you portray in your game, you might be hit with a copyright violation lawsuit. You might have heard of something called Fair Use for use in parody, but 1. This is a law specific to the United States. If you are sued in some other jurisdiction, then there might not be an equivalent protection. And 2. What's parody and what isn't is for a court to decide. There is no clearly drawn line here.

All of these are lawsuits you *might* be able to win, depending on circumstances, and jurisdiction. But only if you are willing to invest some money into fighting them. Civil lawsuits are not just about who is right, it's about who is right and can afford the legal cost to prove it. There is no right to a free attorney in civil courts. You have to pay all your legal costs upfront. If you win the lawsuit you *might* get some of it back later, but only *if* you win. (Most civil lawsuits between companies end in a settlement between the parties, where paying the other side's legal cost is a subject of negotiation).

*Hyperdimension Neptunia* is developed and published by *Idea Factory Co., Ltd.*, a large and established game publisher in Japan. They most certainly have a legal department who advise the developers how far they can go and are ready to defend against any legal challenges. Anyone parodied by them knows IF *will* put up a fight, so they will think carefully if their case is really tight before filing it.

But when you are a low-budget independent developer, others know that you don't have the ability to defend yourself effectively, which makes you an easy target. They will slap you with a lawsuit which might not actually hold up in court when opposed by a good lawyer. But they know you can't afford one, so they will do it anyway. So you will fold, remove your game from the market, might even pay litigation and file for bankruptcy.

So if you are able and willing to invest in a good legal defense, then you can dare it. If not, stay away from parodying anyone with money.

---
Tags: legal
---


# Question
Title: Tips on how to architect your JavaScript game with classes
OK, so I'm creating a `<canvas>` game using JavaScript (ES6+) features like Classes. It's straight from the `vue-cli` and `webpack`.

So, I have these Classes with the following (and such) variables

```
class Player {
    this.x = 1;
    this.y = 5;
    this.name = 'Guy';
    this.stats = [];
}

class Map {
    this.level = 1;
    this.config = {};
    this.images = Image();
    this.canvas = null;
    this.context = null;
    this.board = []; // From a tileset
}

// POINT OF ENTRY STARTS HERE
// const game = new Game();
class Game {
    this.map = null;
    this.player = null;
    this.assets = Images();
}

```

The problem I'm having is that sometimes, I'm having to access a created object that was instantiated elsewhere.

For example, `this.player` was instantiated inside the `Game` class. But in the `Map` class, I have the `drawMouseSelection` method where it needs the current `Player`'s X and Y and `Map`'s board array of tiles.

For example, I pass the all of `board[2500]` to a static helper method in `UI` class to get the correct tile hovered on.

\** What I am doing\**

I just pass the whole object and deal with it as such. Am I passing too big of objects?

# Answer
In JavaScript, objects are references (and arrays are objects, so they are also references). So when you pass a huge object to a function, you don't create a copy of said object. The function operates on the original object. So passing objects to functions won't become a performance bottleneck, no matter how much data these objects include. So when `map.drawMouseSelection` needs the current player, then there is nothing wrong with passing the whole player-object to it.

If you have many more functions in `map` which require the current player, you can just pass the player to the map when you instantiate it and store it in a local variable. Or you can even go a step further and give `map` a reference to the `game` which instantiated it, so it can obtain the current player through it when needed.

But there are other ways to handle object dependencies in JavaScript.

The first thing you need to understand about JavaScript classes is that JavaScript actually has no classes. The new `class` keyword is a lie. JavaScript's object orientation is still prototype-based, not class-based. A class is just syntactic sugar for how JavaScript always worked. They are just regular object-constructor functions in global scope, and functions are yet another type of object. So when you only have one `Player`, one `Game` and one `Map` at once in your game, and the "classes" for them are objects in global scope anyway, there is nothing wrong with replacing them with literal global objects.

Another way to do this is to expose data with Getter-functions. For example, if the UI wants to know which tile is below the mouse cursor, it should call a function like `game.map.getTileAt(x, y)`. The map then returns the tile at those coordinates. The UI class doesn't need to know how the Map class accomplishes that. So if you later decide to replace the one-dimensional `board` with a 2d array, a spatial hashtable or an auto-balanced quadtree, the UI class doesn't need to be changed.
> 2 votes

---
Tags: javascript, architecture, design-patterns
---


# Question
Title: Make object face another object on a sphere
I have a game I'm working on in Unity where there are two objects on a sphere at random locations (and random rotations). I want one of the objects to always rotate so that if it were to fire a bullet (the end goal) that it would fire at the other object along the shortest arc around the sphere.

The problem I'm facing is that I don't know how to create a rotation for an object that is on the surface of a sphere, and have it point towards the other object.

I can also see an issue after this where I would need it to point towards the other object in the shortest distance because there will always be two directions it can point towards.

Has anyone done something like this? Definitely stuck on this one.

# Answer
This can be done more simply than it might appear.

We can think of this as an orientation that points our local y+ (up) axis directly outward from the sphere, so our local xz plane is tangent to the sphere at our position, and points our local z+ (forward) axis in the direction of the target projected onto this plane.

Unity already has a method to construct a rotation that matches one axis exactly, and the second as close as possible with the remaining degree of freedom: `Quaternion.LookRotation`. But it wants to point z+ exactly and y+ as close as possible, so we just need an extra twist to exchange the axes.

```
// Compute vectors from the center to each object.
Vector3 toMe = transform.position - sphereCenterPosition;
Vector3 toTarget = target.transform.position - sphereCenterPosition;

// Form a rotation that points z+ exactly out from the sphere,
// and y+ away from the target in the remaining degree of freedom.
Quaternion pointOut = Quaternion.LookRotation(toMe, -toTarget);

// Twist this rotation 90 degrees about the local x axis,
// so now y+ points out from the sphere, and z+ points toward
// the target within the remaining degree of freedom.
Quaternion pointOnShortestArc = pointOut * Quaternion.Euler(90, 0, 0);

```

I can't recall whether `LookRotation` gracefully handles the case where the two axes are parallel (meaning the targets are on the same/opposite poles and the direction we shoot doesn't matter, so we can pick one arbitrarily), but if it acts up we can detect this case and provide a fallback behaviour.
> 1 votes

---
Tags: unity, rotation, sphere, direction
---


# Question
Title: How does ESRB content rating work for new FREE content?
Very similair to my earlier question, however this deals with games that have new *free* content released later down the line, not paid DLC. Let's say, again like with the last question, you release new content that would push the game's rating to "Mature" when it was previously "Teen". The content is automatically added to the base game for free.

What would happen? Would the base game be pushed to the higher rating, since it now comes with more mature content, or will it not be updated at all? Or do I have to disclose the planned content to the ESRB in advance so they can already give me a higher rating than the base game would get? I don't want to hide anything, so I would give them that info if it was better in the long run.

# Answer
> 1 votes
The ESRB doesn't care about the price of the content. They also don't really care about the distinction between content that a customer can choose to install (free or not) and updates to the game that are automatically applied.

In both cases, the extra content package is treated the same way. The content only needs to be submitted if it would exceed the rating of the base game, otherwise it inherits the rating of the base game.

If the new content changes the rating, and the base game is otherwise made unavailable *without* the new content, then effectively yes - the base game's rating is changed.

---
Tags: content-rating, esrb
---


title: 3D camera - window resolution relation

text:
# Question
Title: 3D camera - window resolution relation
I'm having a bit of an issue when it comes to 3D- and 2D camera(s), in relation to a game's window resolution. I want to let the player choose from different window resolutions, either from a menu or by just resizing the window by dragging the window border, and can't get the scaling of the graphics to work properly. In games I've played, I can go into the options menu, choose a screen resolution and then the window resize itself and the graphic's, menu buttons etc just scales up to the correct sizes.

At the moment, I've tried two different window resolutions; 800x600 and 1280x720 (don't mind the different aspect ratios).

800x600

1280x720

As you can see, more of the game world can be seen (more stone tiles can be seen, if that makes sense) in the window with a resolution of 1280x720 and I want my 3D/2D game(s) to be resolution independent and that the same amount of the game world to be seen, independent of what window resolution the player chooses to use.

My camera class consist of:

* Camera matrix - used to translate and rotate my camera
* View matrix - the inverse of the camera matrix
* Perspective matrix - see code below
* View projection matrix - `view matrix * perspective matrix`
* Fov - 45.0f
* Aspect ratio - `camera width / camera height`

**Note: row-major matrices**

Perspective matrix:

```
const float Tangent     = 1.0f / tanf(DEGREES_TO_RADIANS(Fov * 0.5f));
const float NearToFar   = FarClip - NearClip;

PerspectiveMatrix(Identity);

PerspectiveMatrix[0]    = -Tangent / AspectRatio;
PerspectiveMatrix[5]    =  Tangent;
PerspectiveMatrix[10]   =  FarClip / NearToFar;
PerspectiveMatrix[11]   =  1.0f;
PerspectiveMatrix[14]   = (-NearClip * FarClip) / NearToFar;
PerspectiveMatrix[15]   =  0.0f;

```

At each update, I'm also setting the viewport by calling `glViewport(0, 0, CameraWidth, CameraHeight)`. This might change in the future if I decide to make two cameras in a game, for a splitscreen game for example.

How can I solve the window resolution independence issue?

I have though about creating a framebuffer the size I want, attach it to a quad and then render the quad the size of the window, which will scale up/down the framebuffer if the window is bigger/smaller than the framebuffer's original size, but if it's an easier way of doing it, I would gladly use that instead.

# Answer
> 1 votes
> don't mind the different aspect ratios

But that's the problem. If you use 2 windows with different sizes but the same aspect ratio you won't see this problem.

It looks like you're using the Field of View to represent the vertical field of view. As you can see, the vertical fields are the same. You see the same amount of ceiling and floor in both windows. But because the windows are different aspect ratios, that necessarily means that there will be a different field of view horizontally.

You have some options:

1. Use the field of view to represent the horizontal FOV instead of vertical. This will mean you get the same number of bricks horizontally, but will change the vertical view so in one case you see more ceiling and floor than the other.
2. Stretch things to fit the different aspect ratios - this will distort things but will give you the same horizontal and vertical fields of view in both cases. It is ugly and drives some users (like me) nuts. I don't recommend it.
3. Limit your various resolutions to the same aspect ratio. Some users will dislike this because "you're not using the full screen."
4. Leave it like it is now. This is what most games do, as far as I can tell. (Well this or #1 which has the same issue in reverse.) I've not heard many users complain about this because they don't often change screen aspect ratios over the course of playing a game (even between sessions).

---
Tags: opengl, 3d, camera, viewport, aspect-ratio
---


# Question
Title: Bullet direction incorrect around sphere
Here is a little background on how my game objects are set up, and how the rotations and firing bullets work. I am working on this game in Unity.

I have two game objects that orbit a sphere (for simplicity lets say the player is a space ship and the enemy is a UFO). The UFO shoots at the ship in a spherical manner around the surface of the sphere (my intention at least).

The ship and UFO both have a parent game object that is located at the center of the sphere, and each are moved back on the z-axis by 10 units. All of the movement rotations are applied to the parent pivot points which causes the two objects to orbit freely in any direction as the pivot points rotate.

In this previous question I received some help to get my bullets to fire from the UFO towards the ship. The solution provided works great, the UFO always fires bullets towards the ship as the ship flies around. Once both objects move to opposite side of the sphere (past 180 degrees from the original starting point) the direction to fire the bullet seems mirrored. As the ship flies around the, the bullets fly in a mirrored direction.

Here is how I am rotating the bullets (note: I use the same pivot point technique as stated above for the bullets as well):

When shooting a bullet I first I generate a direction vector like so:

```
var ufoSpoke = ufo.transform.position - Vector3.zero;
var shipSpoke = ship.transform.position - Vector3.zero;
var pointOut = Quaternion.LookRotation(ufoSpoke, -shipSpoke);
var pointOnShortestArc = pointOut * Quaternion.Euler(90f, 0, 0);
var direction = (pointOnShortestArc * Vector3.right).normalized * 50f;

```

Now within the update method for the bullet pivot point, I rotate the pivot object in this direction:

```
transform.Rotate(direction.y * Time.deltaTime, -direction.x * Time.deltaTime, 0f);

```

This all is working great, until the ship and UFO start moving around the sphere. Eventually the calculated bullet direction goes from just slightly off, to mirrored once on the backside of the sphere... If I fly the ship back to the original starting point, the bullet direction comes back properly.

Not quite sure what the issue seems to be, and I've admittedly been looking at this far too long haha. Thanks in advance for any help on this!

# Answer
`transform.Rotate(x, y, z)` rotates in local Euler angles. That means it applies a rotation of `y` degrees about the local y+ axis, then `x` degrees about the (resulting) local x+ axis, and finally `z` degrees about the (resulting) local z+ axis. It might look similar to rotating about the vector `(x, y, z)` for infinitesimal angles, but the compounding effects of each rotation changing the axes of the others can lead it to wander in unintuitive ways.

For this reason, I recommend using Euler angles in only two situations:

* you want to serialize an orientation to a human-readable format for storage/manual editing, or deserialize such a rotation and then work with it in some other format
* you're working in a latitude/longitude system, like a camera controller, where you control each axis completely, and don't have feedback of rotations compounding frame over frame

For most other situations, Quaternion, Matrix, or Angle-Axis representations tend to have more intuitive behaviour.

So we can use this overload instead:

```
transform.Rotate(
     direction,        // rotation axis
     degreesPerSecond * time.DeltaTime, // angle
     Space.World       // global coordinates
);

```

This ensures we're actually rotating about the axis we want.

(And you don't need to normalize the direction — Vector3.right is already a unit vector, and rotating it doesn't change its length — or scale it by 50. All we need from it is a direction)
> 1 votes

---
Tags: unity, rotation, sphere, direction
---


title: What should I do about a computer?

text:
# Question
Title: What should I do about a computer?
Hello my name is Joseph I'm trying to figure out what kinda of computer I should use for game development not gaming. Or should I build one and if I have to build one what should I use? Thank you

# Answer
Basically, you can develop games on every decent machine, I'm using an Asus laptop. As long as you have a decent graphics card that supports modern opengl versions I see no problem. I'll look more into development enviroment, for example I find it more easy to get started with development on unix based os than windows(I've tried both and apt/homebrew makes it really easy..unless you're choosing C#). Other than that, you're good to go!
> -6 votes

---
Tags: game-design
---