# Question
Title: Unity FPS - Joining players always take over the camera
I created a "network manager" and a "network manager hud" for the whole scene. My character is a simple capsule and has a camera, a weapon spawner and 3 weapons as children. I gave him a "network identity" and a "network transform", rewrote the "capsule controler" (attached to the capsule) and also the "mouse controller" (attached to the camera) and saved it as a prefab. I configured the network manager to take the prefab as spawn object and use the default settings of the network manager: localhost:7777.

Now my problem.

I have build an instance of the game, run the inline game as host (localhost:7777) and everything works. Then i run the external build (tried localhost and even local ip)

As soon as i join the game using the 2. instance, the second player take over the camera of the first player! And in the first instance it seems like both cameras are rendered in paralell.

If i dont attach cameras to the player, i can control them as expected :#

Now, finally my question: What am i doing wrong or do i miss?

Thank you

# Answer
> 1 votes
If anybody ran into the same issue, my setup was wrong. Dont attach a camera onto every player prefab. Create them without a camera but put a camera in the scene. Then when a player joins, he take the camera in his local instance of the game and make it a child of himself so it will follow him. This way there is always just a single camera in every instance.

I put a Gameobject (Empty) onto the prefab for that.

```
Camera.main.transform.position = this.transform.Find("Head").transform.position;
Camera.main.transform.LookAt(this.transform.position + this.transform.forward * 30);
Camera.main.transform.parent = this.transform;

```

# Answer
> 0 votes
You need a way of telling which instance owns which gameobject. Only the instance that "owns" the gameobject should be able to assume control on it.

You are looking for something like this:

```
public void Update()
{
    if(_thisInstance != _ownerInstance)
        return; // short-circuit if we are not the owner of this gameobject.

    /*
     *   normal control logic goes here
     */
}

```

---
Tags: unity, multiplayer
---


# Question
Title: Make a platform appear and disappear constantly
I am building a platformer. In this game, I need one of my platforms to constantly activate and deactivate.

Here is how I have tried to code this so far, but it causes Unity to freeze:

```
void Update(){
    for (i = 0; i <= 2; i++) {
        platform.SetActive (false);
        if (i >= 1 ) {
            i--;
            platform.SetActive (true);
        }
    }
}

```

# Answer
Two things to remember:

1. Unity C# scripts like Update or coroutine methods run synchronously, on the main thread.

They're not running in parallel/in the background while the scene is drawn and redrawn each frame. Everything else the engine wants to do - all the other update scripts and all the rendering - has to wait for its turn, after we exit the method in one of three ways:

* We reach the final curly brace `}` at the end of the method
    * We hit a `return` statement
    * In a coroutine, we hit a `yield` statement that passes control back to the engine

Until one of these three things happens, we stay in the method, and nothing else has a chance to update or draw. So if you have a loop in your method (without a `yield` inside), then that loop has to run all the way to completion before the frame can be drawn.

If you have a loop that never exits (an infinite loop), then the game will hang/crash, because it can never finish drawing the current frame or move on to the next one.
2. You can check the behaviour of your code - including spotting infinite loops - by walking through it one instruction at a time, just the same way the processor would when it executes your code.

So, let's walk through this line by line:

1. `for (i = 0; i <= 2; i++) {`

We initialize the variable `i` to zero.

Since zero is less than or equal to two, we pass the loop condition and proceed inside.
2. `platform.SetActive (false);`

We disable/hide the platform.
3. `if (i >= 1 ) {`

`i` is still zero, so we fail this test and skip to the end of the inner `if` block.
4. `}`

We've reached the end of the loop, so we cycle back up to the top.
5. `for (i = 0; i <= 2; i++) {`

We increment `i` by 1 (`i++`), so now it holds a value of one.

One is still less than or equal to two, so we pass the loop condition and proceed into the body of the loop again.
6. `platform.SetActive (false);`

We disable the platform again. It was already disabled though, so this is redundant.
7. `if (i >= 1 ) {`

This time, `i` holds a value of one, which *is* greater than or equal to one. So we step inside the `if` block.
8. `i--;`

We decrement `i` by one, so it's back to zero again.
9. `platform.SetActive (true);`

We activate the platform.
10. `}}`

We reach the end of the `if` block, and the end of the loop, so we return again to the top.
11. `for (i = 0; i <= 2; i++) {`

We increment `i` by 1, so now it holds a value of one again.

Uh-oh... we've been here before. This is exactly the state we were in at step 5!

So now we can clearly see that this loop continues repeating steps 5-10 forever: incrementing `i` to one, then decrementing it back down to zero, so it never reaches a value of three that lets it exit the loop.

The whole game is stuck on hold while this infinite loop runs.

So, how can we alternate a platform off and on, while letting the engine actually keep running other updates and drawing the frame? Something like this would work:

```
public class ActiveAlternator : MonoBehaviour {

    [Tooltip("Target object to turn on/off (NOT this object or its parents!")]
    public GameObject target;

    [Tooltip("Seconds to wait between activating / deactivating the object")]
    public float interval = 1f;

    // IEnumerator makes this run as a coroutine we can suspend & resume with yield.
    IEnumerator Start() {
         if(target == gameObject)
             Debug.LogError("ActiveAlternator cannot target itself and still re-activate");

        // Infinite loop! But it's OK, because we'll tell it to take breaks.
        while(true) {

            // This passes control back to the engine so it can draw the frame,
            // and asks to resume this method on the next line after some time.
            yield return new WaitForSeconds(interval);

            // If the object was active, set it inactive, and vice versa.
            target.SetActive(!target.activeSelf);

            // Then loop to wait, and alternate again, forever.
        }

    }
}

```
> 2 votes

# Answer
Coroutines should do the trick:

```
float blinkInterval = 1.0f; // Turn on/off every second

void Start() {
    StartCoroutine("Blink");
}

IEnumerator Blink() {
    while(true) {
        platform.SetActive(true);
        yield return new WaitForSeconds(blinkInterval / 2f);
        platform.SetActive(false);
        yield return new WaitForSeconds(blinkInterval / 2f);
    }
}

```
> 1 votes

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


# Question
Title: Efficient algorithm for simultaneously updating game objects which need to be updated
I have a grid of objects like this:

```
 1
      +
 F

```

`1` is equal to the constant `1`, `F` flickers between 0 and 1 each tick, and `+` is equal to the sum of the `1` and the `F`.

I want to update these values as described above. The `1` won't change, the `F` will change from 0 to 1 and vice-versa, and the `+` will change to the sum.

I could just do a loop:

```
for node in nodes {
    if(node.type == '+') {
        node.value = node.input1.value + node.input2.value;
    }
    if(node.type == '1') { ... }
    if(node.type == 'F') { ... }
}

```

but the problem is that this will depend on the order of iteration. If the `F` is iterated on first, then it will be set to 1 from an initial value of 0, then the `+` would equal `1 + 1`, i.e. 2. But if the `+` was first, the result would be `1 + 0 = 0` and the NEXT tick would be `1 + 1 = 2`.

I want to do this simultaneously. So I thought I could have a map of new values:

```
global map = new HashMap<Node, double>();
...
map.clear();
for node in nodes {
    if(node.type == '1') {}
    if(node.type == 'F') {
        map.set(node, node.value == 1 ? 0 : 1);
    }
    if(node.type == '+') {
        map.set(node, node.input1.value + node.input2.value);
    }
}
map.forEach(k, v -> k.value = v);

```

but this is probably inefficient as all values have to be looped over and entries in the map must be created for each node (node count is expected to be alot, around 10,000).

How do I do this? I probably need a list of "update required" nodes but I'm not sure what to do exactly, especially to do it simultaneously.

Examples:

```
1
 \
  == + === + === + == (flickers between 6 and 7 starting at 6 due to F flickering)
 /        /     /
F        3     2

// Nodes can be created by the player

1 => + <= 2
     |
     |
     (equals 3)

// Player creates a node:

1 => + <= 2
     |
     |
     (factorial) ===> (equals 6)

```

There can be multiple of these connected nodes at a time:

```
1 => + <= 2
     |
     |
     (equals 3)

2 => + <= 3
     |
     |
     (equals 5)

// If the player chooses, they can connect these 2 together:

1 => + <= 2
     |
     |
     -===========
                |
2 => + <= 3     |
     |          + =====> (equals 8)
     |          |
     -===========

```

Nodes can be inputs to themselves, or have no inputs (in which case the inputs default to 0):

```
     =====> (starts at 1 in the first tick, then keeps incrementing.)
     |
1 => + <==
     |   |
     =====

```

# Answer
I'd recommend ordering your nodes based on their dependencies, into a sequence of generations. You can store the nodes of each generation as a list, and your generations collection is a list of lists.

* A node with no inputs (other than its own state) is in generation 0

+ A constant node is a special case of generation 0 that needs no updates at all. You can store them in a separate list to skip re-processing them each tick.
* A node with one input (other than its own state) is in generation `node.input.generation + 1`
* A node with multiple inputs (other than its own state) is in generation `max(node.input[i].generation) + 1`, where we've taken the maximum generation out of all of its inputs.

Now you can process your nodes in a single pass, one generation at a time.

* If you start at generation zero and work up to the last generation, then each node's value reflects the latest values of its inputs, so a change at the leaf of the tree propagates all the way to the root in one pass.
* If you start at the last generation and work down to generation zero, then each node's value reflects the values of its inputs in the previous tick, similar to your `map` solution, so a change in a leaf value advances one generation further in each tick.

When you change a node's inputs, you'll need to re-evaluate the generation it belongs in. If it changes generations, then you'll need to re-evaluate the generation of any nodes that use it as an input. Order within a single generation list doesn't matter, so you can use swapping to insert/remove nodes efficiently, or even have multiple threads working on separate chunks of a single generation in parallel if you have thousands or millions to update.
> 1 votes

---
Tags: algorithm
---


title: Collision Detection in Direction (SFML)

text:
# Question
Title: Collision Detection in Direction (SFML)
I am experiencing a problem with collision detection, an efficiency problem. Right now I want to make it so that my player square stops traveling in the direction of collision into the static object. I followed what a guy did in a tutorial when he checked this type of collision but it's long and hard to understand let alone read. Is there an easier way to tackle this issue?

```
sf::RectangleShape player;
player.setSize(sf::Vector2f(50, 50));
player.setFillColor(sf::Color::Cyan);
player.setPosition(width / 2, height / 2);

sf::RectangleShape object;
object.setSize(sf::Vector2f(100, 100));
object.setFillColor(sf::Color::Green);
object.setPosition((width / 2) - 200, (height / 2) - 120);

sf::Vector2f velocity(0, 0);
float gravity = .1;

bool jumping = true;

sf::Event event;
while (window.isOpen())
{
    while (window.pollEvent(event))
    {
        if (event.type == sf::Event::Closed)
            window.close();

        if (event.type == sf::Event::KeyPressed)
        {
            if (event.key.code == sf::Keyboard::Space)
            {
                if (jumping == false)
                {
                    velocity.y = -3.5;
                    jumping = true;
                }
            }
            else if (event.key.code == sf::Keyboard::Right)
            {
                velocity.x = 3;
            }
            else if (event.key.code == sf::Keyboard::Left)
            {
                velocity.x = -3;
            }
        }
    }

    //Move the player
    player.move(velocity);

    //Gravity

    if (player.getPosition().y < height / 2)
    {
        velocity.y += gravity;
    }
    else if (player.getPosition().y >= height / 2)
    {
        player.setPosition(player.getPosition().x, height / 2);
        jumping = false;
    }

    //Check collision with object
    sf::FloatRect player_boundingBox = player.getGlobalBounds();

    if (player_boundingBox.intersects(object.getGlobalBounds()) && player.getPosition().y + 50 < object.getPosition().y + 5 && player.getPosition().y + 50 > object.getPosition().y && player.getPosition().y < object.getPosition().y)
    {
        player.setPosition(player.getPosition().x, object.getPosition().y - 50);
    }
    else if (player_boundingBox.intersects(object.getGlobalBounds()) && player.getPosition().x > object.getPosition().x + 90 && player.getPosition().x < object.getPosition().x + 99)
    {
        player.setPosition(object.getPosition().x + 100, player.getPosition().y);
        velocity.x = 0;
    }
    else if (player_boundingBox.intersects(object.getGlobalBounds()) && player.getPosition().x + 50 < object.getPosition().x + 10 && player.getPosition().x + 50 > object.getPosition().x)
    {
        player.setPosition(object.getPosition().x - 50, player.getPosition().y);
        velocity.x = 0;
    }
    else if (player_boundingBox.intersects(object.getGlobalBounds()) && player.getPosition().y > object.getPosition().y + 97 && player.getPosition().y < object.getPosition().y + 99)
    {
        player.setPosition(player.getPosition().x, object.getPosition().y + 100);
        velocity.y = 0;
    }

    window.clear(sf::Color::White); //Clear

    window.draw(player);
    window.draw(object);

    window.display(); //Display
}

```

# Answer
> 0 votes
I see you are checking for intersection in every `if` and `else if`. So you are asking the same question four times in worst case. I recommend to make this

```
if (player_bounds.intersect(object_bounds))
{
    //Other conditions
}

```

For the rest of the condition. Depending on your game, you should be able to precalculate as possible as you can before you reach the `if`s.

Hope this help.

# Answer
> 1 votes
So for starters the only part of the code that is collision detecting is:

```
//Check collision with object
sf::FloatRect player_boundingBox = player.getGlobalBounds();

if (player_boundingBox.intersects(object.getGlobalBounds()) && player.getPosition().y + 50 < object.getPosition().y + 5 && player.getPosition().y + 50 > object.getPosition().y && player.getPosition().y < object.getPosition().y)
{
    player.setPosition(player.getPosition().x, object.getPosition().y - 50);
}
else if (player_boundingBox.intersects(object.getGlobalBounds()) && player.getPosition().x > object.getPosition().x + 90 && player.getPosition().x < object.getPosition().x + 99)
{
    player.setPosition(object.getPosition().x + 100, player.getPosition().y);
    velocity.x = 0;
}
else if (player_boundingBox.intersects(object.getGlobalBounds()) && player.getPosition().x + 50 < object.getPosition().x + 10 && player.getPosition().x + 50 > object.getPosition().x)
{
    player.setPosition(object.getPosition().x - 50, player.getPosition().y);
    velocity.x = 0;
}
else if (player_boundingBox.intersects(object.getGlobalBounds()) && player.getPosition().y > object.getPosition().y + 97 && player.getPosition().y < object.getPosition().y + 99)
{
    player.setPosition(player.getPosition().x, object.getPosition().y + 100);
    velocity.y = 0;
}

```

What its doing is check if the players "box" aka bounds (The area around the player that you want to collide with something else) is intersecting with another objects "box". In this case the object is a rectangle defined at the top:

```
sf::RectangleShape object;

```

If the players "box" is past the objects "box" it pushes places the player back.

---
Tags: c++, collision-detection, sfml
---


title: How to store relations between NPCs?

text:
# Question
Title: How to store relations between NPCs?
For an RPG I want to generate a world with lots of NPCs, and the NPCs all have relations to eachother. They can be eachothers parents, children, siblings, friends, bosses, lovers, lieges, vassals, etc. And they have an opinion of eachother between -100 (hate) and +100 (love). If person A is close, like the child or lover, of person B that gives a bonus (say, +50) to B's opinion of A, etc.

This system is closely inspired by how relationships between all the characters in Crusader Kings 2 work. It can also be compared to The Sims.

## Ideas

I am wondering what would be the sensible way to store this kind of data? Here are the three main approaches I can think of.

**1. Object oriented:** In the object oriented approach I make a Character class and a Relation class. An instance of the Relation class has pointers to two different Character instances and information about the relation between them. I have to store an array of Characters and an array of Relations. Probably also each Character instance should have an array of pointers to the Relations she has (maybe the global array of Relations is not necessary then?). A Relation instance does not necessarily need to exist between two characters that does not know eachother (as opposed to Crusader Kings, where *every* character has an opinion of *everyone*), but I can add new Relations if two NPCs starts to interact.

```
# Pseudocode concept of what a Relation instance could contain
Relation:
    chars = [charA, charB]
    opinions = 50, 60
    relations = ["child", "parent"]

```

**2. Normalized database:** Have a Character table and a Relations table. The Relations table must have two columns, charA\_id, charB\_id, which references two unique Characters. This approach is quite similar to the object oriented one, just that each Character and Relation is a row in their respective tables instead of instances of a class.

**3. Matrix:** The Characters can be either class instaces or a database, but the Relations are stored in a big n\*n matrix, where n is the number of Characters that exists. In this approach every NPC would have an opinion of every other, whether or not they actually know them. This will store an abundance of information, but in a very simple format. With a few 100s of NPC the size of matrix will be in the 10000s. This could work well if I just wanted a simple opinion number for eachother, but as I also want to store the nature of the relation (parent, lover, vassal, etc.) that can be clumsy to put in a matrix.

## What it is

I'm not making a video game. This system is a tool to generate a world for tabletop RPGs like Dungeons & Dragons. The goal is to be able to quickly populate a fictive world with lots of procedurally generated characters to give the game master a rough slate from which to flesh out more details. If this project is successful it could be very useful for grand campaigns with lots of social interactions. The game master could plop down a new city full of people for the players to interact with in a matter of minutes.

Since it is not a game per se, the way of storing the information and having a good way to view it is the most important. The benefit of making a database is that I can perform queries like "Give me all the blacksmiths in city X" or "Give me all the female family members of person Y". The object oriented approach has the benefit of being more powerful in that it is very flexible in what kind of information I can put in a class, and I can make functions, like generateChild(personA, personB). I might go for a hybrid approach. Even if I make the system object oriented I could still convert it into a database to query against.

The final result will be

1. A program that can generate (and change) chunks of new Characters and Relations and store them to file(s) in some format.
2. An interface to search through and view the data.

## Question

My question is what would be the sensible way to store this kind of data? Which of my ideas are good/bad? Do you have other suggestions?

Are there other games than Crusader Kings and The Sims that does something like this? How is it typically done? Relations between Factions can also be a thing, not just between individual Characters.

## Example

I made an object oriented prototype that can generate random characters like these. Each character has their relations listed under them (not all the relations make logical sense at the moment).

```
name: Pupyq
age: 79
gender: female
lifestyle: wretched
alignment: neutral neutral
  niece/nephew: Tesemakebi (31)
  cousin: Tesemakebi (52)

name: Hyp
age: 37
gender: male
lifestyle: modest
alignment: neutral evil
  cousin: Nyle (-69)
  employee: Agegixuku (-86)
  parent: Qogilatyji (95)

name: Agegixuku
age: 21
gender: male
lifestyle: poor
alignment: lawful neutral
  employee: Zizewib (48)
  employer: Hyp (-41)
  employee: Hagimiqox (72)
  child: Imibimataz (-85)

name: Qogilatyji
age: 80
gender: female
lifestyle: squalid
alignment: neutral good
  aunt/uncle: Zizewib (-14)
  child: Hyp (81)

name: Tesemakebi
age: 53
gender: female
lifestyle: poor
alignment: neutral good
  aunt/uncle: Pupyq (29)
  liege: Ovi (95)
  employer: Zizewib (-43)
  cousin: Pupyq (79)

name: Ovi
age: 74
gender: male
lifestyle: squalid
alignment: neutral neutral
  vassal: Tesemakebi (100)
  aunt/uncle: Hagimiqox (-82)

name: Hagimiqox
age: 37
gender: male
lifestyle: wretched
alignment: neutral evil
  employer: Agegixuku (36)
  niece/nephew: Ovi (-41)

name: Imibimataz
age: 76
gender: male
lifestyle: comfortable
alignment: neutral neutral
  parent: Agegixuku (-100)

name: Nyle
age: 68
gender: male
lifestyle: wretched
alignment: chaotic neutral
  cousin: Hyp (-65)

name: Zizewib
age: 34
gender: female
lifestyle: wealthy
alignment: lawful neutral
  niece/nephew: Qogilatyji (-36)
  employer: Agegixuku (30)
  employee: Tesemakebi (-52)

name: Ile
age: 16
gender: male
lifestyle: wretched
alignment: chaotic good
  sibling: Pocohyjep (12)
  aunt/uncle: Qegalydu (45)
  employer: Pocohyjep (-29)

name: Qehiqiqej
age: 69
gender: male
lifestyle: poor
alignment: lawful good
  spouse: Qegalydu (87)

name: Omux
age: 72
gender: female
lifestyle: modest
alignment: neutral evil

name: Qegalydu
age: 15
gender: male
lifestyle: aristocratic
alignment: chaotic good
  spouse: Qehiqiqej (58)
  child: Pocohyjep (68)
  niece/nephew: Ile (4)

name: Pocohyjep
age: 63
gender: male
lifestyle: wealthy
alignment: neutral evil
  sibling: Ile (-8)
  parent: Qegalydu (75)
  employee: Ile (-6)

```

# Answer
> 1 votes
Mostly it comes down to how you expect people to interact with your data.

**Database approach**
The database approach is best suited to situations with an emphasis on querying. Will the DM often want to see "all the NPCs that are evil, living in poverty and have a 2nd degree or stronger relationship to Duke Gettenrobbed?" Databases are ideal for this, so it makes sense to use this format. There's a variety of database applications that provide UI support for adding, removing, editing, and querying the data. As such you can focus more on your core development (generating interesting data sets) and not get bogged down developing UI.

**OO approach**
The OO approach makes more sense if the users don't need or want the complexity of a data base application. For instance, if the data set is modest enough to handle comfortably in a text editor. That said, I would strongly encourage you to present the data in format that is both human readable and follows a standardized format such as JSON or YAML. Using a stock data interchange format instead of something homemade has some advantages:

* there's usually libraries already available
* it's easier for others to deal with your data
* less time focused on data format means more time for core development

This is the route I used for entity data in a project. I didn't have a ton of entities to keep track of and I want something that I could quickly edit by hand. I like YAML since it supports comments and is a super-set of JSON, but in my opinion JSON seems to be more popular and thus have more support in terms of tools and libraries. Here's an example where I took your data & tweaked it a bit to fit the format I was using:

```
---
Version: 1.20.3
Date: 1-02-1997
Data:
  - Person:
      ID: 001
      Name: Pupyq
      Age: 79
      Gender: female
      Lifestyle: wretched
      Alignment: neutral neutral
      Relationships:
        - PersonID: 002
          Flow: Equal
          Type: Family
          Time: Current
          Phrase: spouse of
          Opinion : 90
        - PersonID: 003
          Flow: Lesser
          Type: Work
          Time: Past
          Phrase: purchase goods from
          opinion : dislike
  - Person:
      ID: 002
      Name: Hyp
      Age: 37
      Gender: male
      Lifestyle: modest
      Alignment: neutral evil
      Relationships:
        - PersonID: 001
          Flow: Equal
          Type: Family
          Time: Current
          Phrase: spouse of
          Feeling: love
        - PersonID: 003
          Flow: Equal
          Type: Social
          Time: Present
          Phrase: plays cards with
          Feeling: 30
...

```

Note: in my system, relationship are either equal or directional. For instance, the worker / employer relationship is directional and I designate it as flowing from the employer to the employee. Including this directly as a field simplified a lot of code for phrase generation. Similarly, including unique identifiers (rather than relying on names) simplified things for me. And I wanted to support previous relationships that have since ended (former employees, lovers, etc), so there's a field for that too. If these features help you too, great; if not, drop them.

One final note: while you could use XML, I find it to be too tag heavy to be easily dealt with by hand.

**Matrix approach**
In most respects, I find the matrix option is the weakest. Unless you go through the trouble of using a sparce matrix, most of the entries are wasted space. For the computer, this is only a problem if your data set is truly huge. However it's still a problem for the human user; reading a massive, sprawling matrix is unwieldy.

The human usability factor gets even worse if you have multi-dimensional data. You counter some of that by breaking the data across multiple, more narrowly focused matrices (social networks, employment networks, etc). That said, matrices are nice if you're dealing with printed hard copy and want to quickly cross reference things. For instance, if the data were to be printed out as a supplement for a play session.

# Answer
> 1 votes
First of all im not very versed in Database structures. I know how they work, what they are there for, and since Uni never had to touch them again.

As a DnD player myself, i see some problems with the pure numbers approach. Many relations depend on the history of the two characters, family members of them or even guild members or just pure gossiping. And what does a +21 relation mean between brothers in comparison two people that barely know each other. If you know how do rate those numbers, that good, but i certainly would expand on it.

To your ideas:

* **Object oriented**
This approach should deliver the most in-depth information about relations, characters and their standings. If you only work offline, the size of those relation classes shouldn't be a problem and you could even add the option to store information about why their relationship is so bad. Maybe add an 'incidents' class to store those moments which changed their standings with important information. The OO approach is definitely the most flexible and even in a sample size of 100 people this should be around 4950 relationships at max.
* **Normalized DB**
A database is the best method to store the simple relationships, as you can basically use Person A relation to Person B as a composite key (So A,B would be the key and the relationship the value). As stated before im not quite sure if it is easy to handle changes in the system itself, adding new tables or new foreign keys.
Problem would be, that you would have to save more complex in other ways, e.g. Pictures. Also im not quite sure how easy it is to store larger text like descriptions or longer quotes.
You can add families, general relationship modificators shaded by a familie towards another familie etc.
* **Matrix**
The pure number maxtrix is basically a map of Person A to a map of Person B to a number. Every important information is missing. But if you map Person B to a relation class instance, than that should be the best OO for quick relation access, but worst if you want query results.

So depending on the stored informations a DB should be the best. Everything you need in addition the simple DB functions you can add with small container classes (like for pictures).

# Answer
> 1 votes
I'd say this is very similar to some old (non-game related) projects in which I worked. What worked there, and I'd say is a sensible solution, is to code the logic in your programming language of choice (our user interface was an Intranet page) and then store the all the information in a database. I am not sure how you are coding your tool, but a number of programming languages have libraries to offer support/integration to DB systems (we used Java, at the time).

As a note, remember that a Relationship table might include additional information about itself. To give an example, you can have a column called active (0 or 1) which would easily enable you to query "give me a list of former associates of X". Or, instead of 1 and 0, you could have an Event\_ID, which would be a table storing the information of what happened. Then you could present/report/save this information through an user interface programmed in Python/Java/Binary or whatever you are most comfortable with :)

---
Tags: architecture, rpg, data-structure, character, data
---


# Question
Title: Implementing game synchronization between clients and server
I'm creating a small online multiplayer game where I have multiple thin clients and an authoritative server. Both the client and the server have a fixed game loop.

Now I have a game entity with the following properties:

* X position: float
* Y position: float
* Direction: float

In the client, the entity is in constant velocity changing its direction based on user input and sends an input event to the server.

* `[LEFT, PRESSED]`: Entity moves to the left
* `[LEFT, RELEASED]`: Entity moves to the right

Every event is queued on the server, and simulated the same way as on the client (calculating the new properties based on trigonometric functions) and the event is send to other players in the room. The other players apply the same simulation to that particular entity (keeping track of what key is pressed for each entity).

Now after some time playing, the position and direction start to drift and stop being in sync. I suspect this has to do with floating-point arithmetic(?)

1. Is this implementation correct, rather than sending its position and direction every step?
2. How would I solve this problem? I think I need to make the server the single source of truth and send regular state snapshots to the the clients to correct possible mistakes/drifting? What would be a good interval to keep the clients up to date?
3. At the moment, I'm broadcasting an event to every player in the room. What would be a nice approach to only send events to players near the entity? Would a quadtree work here (the same I'm using for my collision detection)?

# Answer
> 3 votes
The server, as you probably know, is the one source of the truth in a game architecture like you're creating. The server is calculating "the truth" of position based on input to the clients, then communicating that data back to each client.

Every time the server sends an update, each client should set positions of objects to what the server has shown. In other words, the server's new position data should completely overwrite the client's position data.

Then to keep things looking smooth on each client between server updates, the simulation on the client side should only be there to keep movement rendering smooth. So if the server were providing updates every 10 frames, it's up to the client to simulate the anticipated movement for the frames between each update.

With this approach, there is no drift on the client side, or if there is, it's very brief as it's only happening on the between-update frames.

It's not exactly an answer, but you might find this post somewhat relates to your question -\> Lag compensation with networked 2D games

---
Tags: networking, client-server, synchronization
---


title: Moving a dynamically spawned object

text:
# Question
Title: Moving a dynamically spawned object
I would like to create an object dynamically when the player presses `Q` and use this object in `Instantiate` and in `transform.Translate`.

The problem is that the translation must be outside the `if` that checks for the `Q` press, but it applies to the cube that I created inside the `if`.

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

public class instancier_new_object : MonoBehaviour {

    public float moveSpeed=5f;

    void Update () {
        if (Input.GetKeyDown (KeyCode.Q)) {
            GameObject objet = new GameObject ("objet");
            GameObject cube = new GameObject ("cube");

            cube = Instantiate(
                       objet,
                       new Vector3(1, 2, 3),
                       Quaternion.identity
            );
        }

        cube.transform.Translate(
                 Time.deltaTime*moveSpeed,
                 0,
                -Time.deltaTime*moveSpeed,
                 Space.Self
        );
    }
}

```

# Answer
> 1 votes
If you want to refer to the object outside of the `if` so that it moves even on frames when you're not pressing `Q`, then you need to store it in a member variable that can remember it between frames, from one invocation of `Update` to another.

While we're at it, we can also remove some redundant instantiation:

```
public class CreateObject : MonoBehaviour {

    public float moveSpeed = 5f;

    // Member variable to hold onto our spawned object.
    Transform _spawnedObject;

    void Update () {
        if (Input.GetKeyDown (KeyCode.Q)) {
            GameObject myObject = new GameObject("object");

            // Store the transform of the object to refer to it again later.
            _spawnedObject = myObject.transform;
            _spawnedObject.position = new Vector3(1, 2, 3);
        }

        // Check that we have a spawned object before trying to move it.
        if(_spawnedObject != null) {
            Vector3 step = new Vector3(1, 0, -1) * moveSpeed * Time.deltaTime;
            _spawnedObject.Translate(step, Space.Self);
        }
    }
}

```

This is very much the same as I've shown you in previous answers, so I encourage you to study them in more detail.

We can make this even cleaner though, by doing as I've recommended to you previously and *separating the spawning logic from the moving logic*.

Our movement logic can be very simple then:

```
public class TranslateOverTime : MonoBehaviour {

    public Vector3 velocity = new Vector3(1, 0, -1);

    void Update() {
        transform.Translate(velocity * Time.deltaTime, Space.Self);
    }
}

```

And our spawner stays simple too:

```
public class CreateMovingObject : MonoBehaviour {

    public float moveSpeed = 5f;

    void Update () {
        if (Input.GetKeyDown (KeyCode.Q)) {
            // Create the new object where we want it to be.
            GameObject myObject = new GameObject("object");
            myObject.transform.position = new Vector3(1, 2, 3);

            // Attach the movement behaviour to it, and configure its motion.
            var mover = myObject.AddComponent<TranslateOverTime>();
            mover.velocity = new Vector3(1, 0, -1) * moveSpeed;
        }
    }
}

```

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


# Question
Title: Why can't I export an APK from my project in Game Maker?
I'm already extremely tired, it's already hours and more hours seeing tutorials and none of my problem is minimally solved.

I have already set everything in global game settings (I believe there may be some mistake):

The keystore is okay:

There is the android sdk manager:

But when I'm going to create the application:

Compile window:

```
Create started: 21:14:15
"D:\Usuários\Boneco Sinforoso\Desktop\Downloads\GameMaker Studio Master Collection 1.4.1760\GameMaker-Studio\GMAssetCompiler.exe" /fU="D:\Usuários\Boneco Sinforoso\AppData\Local\gm_ttt_79013\a84237.txt" /c /m=android   /config="Default" /tgt=8 /obob=True /obpp=False /obru=True /obes=False /i=3 /j=4 /cvm /tp=1024 /mv=1 /iv=0 /rv=0 /bv=1760 /gn="5im" /td="D:\Usuários\Boneco Sinforoso\AppData\Local" /cd="D:\Usuários\Boneco Sinforoso\Documents\GameMaker\Cache" /sh=True /dbgp="6502" /hip="192.168.25.5" /hprt="51268" /optionsini="D:\Usuários\Boneco Sinforoso\AppData\Local\gm_ttt_79013\gm_ttt_37812\5im.ini" /o="D:\Usuários\Boneco Sinforoso\AppData\Local\gm_ttt_79013\gm_ttt_37812" "D:\Usuários\Boneco Sinforoso\Desktop\Genesys Generation\Projetos\Projeto Jogos\Projeto 5im\5im.gmx\5im.project.gmx"

Reading project file....finished.
Compile Constants...finished.
Remove DnD...finished.
Compile Scripts...finished.
Compile Objects...finished.
Compile Timelines...finished.
Compile Triggers...finished.
Compile Rooms...finished.
Compile Extensions...finished.
Global scripts...finished.
Final Compile...finished.
Saving IFF file... D:\Usu�rios\Boneco Sinforoso\AppData\Local\gm_ttt_79013\gm_ttt_37812\5im.droid
Writing Chunk... GEN8
Writing Chunk... OPTN
Writing Chunk... LANG
Writing Chunk... EXTN
Writing Chunk... SOND
Writing Chunk... AGRP
Writing Chunk... SPRT
Writing Chunk... BGND
Writing Chunk... PATH
Writing Chunk... SCPT
Writing Chunk... GLOB
Writing Chunk... SHDR
Writing Chunk... FONT
Writing Chunk... TMLN
Writing Chunk... OBJT
Writing Chunk... ROOM
Writing Chunk... DAFL
Writing Chunk... TPAGE
Writing Chunk... CODE
Writing Chunk... VARI
Writing Chunk... FUNC
Writing Chunk... STRG
Writing Chunk... TXTR
0 Compressing texture... writing texture texture_0.png...
Writing Chunk... AUDO
Writing Chunk... SCPT
Writing Chunk... DBGI
Writing Chunk... INST
Writing Chunk... LOCL
Writing Chunk... STRG
Stats : GMA : Elapsed=1359
Stats : GMA : sp=22,au=0,bk=1,pt=0,sc=0,sh=0,fo=0,tl=0,ob=2,ro=2,da=0,ex=0,ma=2,fm=0xC100060
cmd /c "subst Z: "D:\Usuários\Boneco Sinforoso\Documents\GameMaker\Cache\5im\Android\Default" && Z: && cd \com.GG.S5in && "D:\Usuários\Boneco Sinforoso\Desktop\Downloads\GameMaker Studio Master Collection 1.4.1760\GameMaker-Studio\Android\runner\gradle\gradlew"  assembleRelease lint "

Observed package id 'add-ons;addon-google_apis-google-24' in inconsistent location 'c:\Android\sdk\add-ons\addon-google_apis-google-24-1' (Expected 'c:\Android\sdk\add-ons\addon-google_apis-google-24')
Already observed package id 'add-ons;addon-google_apis-google-24' in 'c:\Android\sdk\add-ons\addon-google_apis-google-24'. Skipping duplicate at 'c:\Android\sdk\add-ons\addon-google_apis-google-24-1'
Incremental java compilation is an incubating feature.
:com.GG.S5in:preBuild UP-TO-DATE
:com.GG.S5in:preReleaseBuild UP-TO-DATE
:com.GG.S5in:checkReleaseManifest
:com.GG.S5in:preDebugBuild UP-TO-DATE
:com.GG.S5in:prepareComAndroidSupportMultidex101Library UP-TO-DATE
:com.GG.S5in:prepareComAndroidSupportSupportV42311Library UP-TO-DATE
:com.GG.S5in:prepareReleaseDependencies
:com.GG.S5in:compileReleaseAidl UP-TO-DATE
:com.GG.S5in:compileReleaseRenderscript UP-TO-DATE
:com.GG.S5in:generateReleaseBuildConfig UP-TO-DATE
:com.GG.S5in:mergeReleaseShaders UP-TO-DATE
:com.GG.S5in:compileReleaseShaders UP-TO-DATE
:com.GG.S5in:generateReleaseAssets UP-TO-DATE
:com.GG.S5in:mergeReleaseAssets
:com.GG.S5in:generateReleaseResValues UP-TO-DATE
:com.GG.S5in:generateReleaseResources UP-TO-DATE
:com.GG.S5in:mergeReleaseResources UP-TO-DATE
:com.GG.S5in:processArmeabi-v7aReleaseManifest UP-TO-DATE
:com.GG.S5in:processArmeabi-v7aReleaseResources
:com.GG.S5in:processArmeabiReleaseManifest UP-TO-DATE
:com.GG.S5in:processArmeabiReleaseResources
:com.GG.S5in:processMipsReleaseManifest UP-TO-DATE
:com.GG.S5in:processMipsReleaseResources
:com.GG.S5in:processUniversalReleaseManifest UP-TO-DATE
:com.GG.S5in:processUniversalReleaseResources
:com.GG.S5in:processX86ReleaseManifest UP-TO-DATE
:com.GG.S5in:processX86ReleaseResources
:com.GG.S5in:generateReleaseSources
:com.GG.S5in:incrementalReleaseJavaCompilationSafeguard UP-TO-DATE
:com.GG.S5in:compileReleaseJavaWithJavac UP-TO-DATE
:com.GG.S5in:prePackageMarkerForRelease
:com.GG.S5in:transformClassesWithJarMergingForRelease UP-TO-DATE
:com.GG.S5in:collectReleaseMultiDexComponents UP-TO-DATE
:com.GG.S5in:transformClassesWithMultidexlistForRelease UP-TO-DATE
:com.GG.S5in:transformClassesWithDexForRelease UP-TO-DATE
:com.GG.S5in:compileReleaseNdk UP-TO-DATE
:com.GG.S5in:mergeReleaseJniLibFolders UP-TO-DATE
:com.GG.S5in:transformNative_libsWithMergeJniLibsForRelease UP-TO-DATE
:com.GG.S5in:processReleaseJavaRes UP-TO-DATE
:com.GG.S5in:transformResourcesWithMergeJavaResForRelease UP-TO-DATE
:com.GG.S5in:validateReleaseSigning FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':com.GG.S5in:validateReleaseSigning'.
> Keystore file D:\Usu?rios\Boneco Sinforoso\AppData\Local\gamemaker_studio\keystore.keystore not found for signing config 'release'.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 6.136 secs
cmd /c "subst /d Z:"

Lint Build report available at D:\Usuários\Boneco Sinforoso\Documents\GameMaker\Cache\5im\Android\Default\com.GG.S5in\build\outputs\lint-results.html
Create finished: 21:14:25

```

I do not know what else to do. I have already changed the target sdk, min sdk, compile sdk, and nothing. I do not know where else to go, and yoyogames does not give me any really useful information, anyway ... I'm sorry for the bad english.

# Answer
As I mentioned in a comment in the question itself, the problem happened because of the **keystore directory**.

In the preferences I changed the directory to one that is practically in the root (**C:\Android\sdk\myKeystore**). So that way I avoid directories that contain words with accents, spaces, or invalid characters.

With this I was able to successfully export the APK.
> 0 votes

# Answer
Your Support lib must be the same level as the target SDK, so if you target SDK 25 your support library must be the latest related to 25, say 25.0.0 or other similar like 25.0.1

Also the name of the app in the package name must be the same from Display name
> 1 votes

---
Tags: android, game-maker
---


# Question
Title: Simplest way to make a car follow a route
To get the cars to follow the circuit, I mapped the circuits to several points. And using the `move_towards_point` function I make everything happen correctly.

In addition, I use two objects: **object 1 / pink square** =\> to be followed by the cars, **object 2 \ green square** =\> to reset the car collision with object 1 (**so that the collision with object 1 only happens once**).

Sometimes I have to make an adjustment in the position of object 2, because it has to be in the path between two objects 1, otherwise it will not clear the collision.

I thought there would be another solution considering that I've seen in video tutorials a platform games function (usually used on villains so they do not fall into the void).

If I am not mistaken, it is as if at any moment the object throws a particle, and if it did not reach anything until a certain moment or height (y), the object would turn around and run in the opposite direction.

I imagine there is a function similar to this to use in my case. So that you detect the circuit object and do not let the car get out of it.

It's *hard* enough to have to put up points, then move the position of each of them to the code (I had to do this, because I preferred to create only one object and keep repeating it all over the circuit, I could have created several. **Ex =\>** *point 1*, *point 2*, ...).

Not wanting to plagiarize, but an example of what I want for my game, is this game:

*Game*: https://play.google.com/store/apps/details?id=com.moz.flracing2016.pro&hl=pt\_BR

*Video of game*: https://www.youtube.com/watch?v=knZRQZI25Fo

# Answer
> 0 votes
Through the comment from site member Juanpa, I got a simpler way of doing what I wanted at first.

The GameMaker has a feature called **path**.

By clicking on the path, you can choose a room as the background (the room is already with the circuit drawing, so I can draw the path above the circuit drawing):

You click at any point to start the path:

After setting the starting position of the maze, the next point will be the next location of the path to be followed (see that with 3 or more points the path closes, this is because the **closed option** is selected):

Path completed:

Below is a link that will help you use some of the important features of this feature:

https://docs.yoyogames.com/source/dadiospice/001\_advanced%20use/004\_paths.html

---
Tags: movement, game-maker
---


# Question
Title: Shortcut Not Found (installing game created in GameMaker)
I tested the game I created on 4 computers (ALL Windows 7) and had the following problem at installation time.

The shortcut created by the installer itself came like this:

When I click the following message appears:

Clicking in search appears this:

By clicking the application Bet on Man the shortcut would work correctly. However, not that the players have that task.

# Answer
With the help of **Dmi7ry** and **Juanpa** who commented on my question, I was able to solve this problem.

When creating an application, just switch from **Windows NSIS Installer** to **Single runtime executable**:
> 0 votes

---
Tags: game-maker, installer
---


# Question
Title: Dividing properties between RigidBody and Collider
I am currently making a physics engine in Rust.

The 2 main data structures concerning collision detection are:

1. RigidBody: Physics-related aspects of the body. Contains a reference to a Collider structure.
2. Collider: Shape and structural-related aspects

However, I am unsure as to which data structure should store the instance fields:

1. mass (or inverse mass)
2. inertia (or inverse inertia)
3. angle of orientation
4. restitution

The reason for this absolute segregation is that during collision detection, only references to the concerning Colliders will be passed.

Could someone please advise me on the matter?

# Answer
> 0 votes
The breakdown I'm most used to seeing is like this:

**Rigid Body** \- responsible for the simulation dynamics of an object that can move:

* Mass
* Inertia
* Position of the body as a whole
* Orientation of the body as a whole

Static collision objects that don't move - like unbreakable walls - don't need these properties, so it makes sense to not reproduce them on the Collider type.

**Collider** \- responsible for the shape & surface other physics interact with:

* Shape & dimensions
* Physics material
    + Restitution / elasticity / bounciness
    + Coefficients of friction
    + Rules for combining these values with those of the other colliding surface
* Position of the collider (within the body)
* Orientation of the collider (within the body)
* Reference to the parent body, if any
* Density (helps calculate mass & inertia of the body, if used)

The semi-duplication of position & orientation here helps if you ever want to allow bodies with compound collision representations, made up of several distinct colliders, where each can be precisely positioned & oriented to match the shape of the game object they represent.

# Answer
> 0 votes
Typically a Collider is repurposed for Triggers, if that helps you think about the separation. It would have a null or special physics material.

---
Tags: collision-detection, physics-engine, rigidbody
---


# Question
Title: How can I prevent/balance waiting and turtling as a response to cooldown mechanics
I'm working on a turn-based RPG with classes. I want one of the spellcaster classes to have standard magic points, but another to have abilities with time limitations, one or more of

* Use ability every N minutes of real time
* Use ability every N turns of combat
* Use ability once or N times per day (sleep to restore, or wait out day-night cycle)

There would be restorative items that could restore your "charge". These abilities would be more powerful than regular spells but constrained. This spellcasting class is a burster: gives you big hits but infrequently because of the limitations. The party carries them along as baggage until they get in a jam or run into a boss, then unleashes the hammer. I like it as an option to add depth, and it has interesting speedrun possibilities.

The last one is easy enough to balance if the party has to trek back to town and sleep to recharge, but I have a day-night cycle. Here are the problems as I see it:

### Real time / N times per day

Player can just wait. I can make the duration punishing, but then it greatly reduces the utility. It also means that the player is not *playing the game*, this is after all supposed to be about entertainment. No fun.

### Every N turns in combat

Player can just have every character defend/heal every round until the burster unleashes another round of big damage. I actually want this to be viable, but I don't want it to become the obviously best strategy for battles. So far it doesn't seem to be a huge issue as the caster just cycles through lesser powers until the big bang recharges. It's rough in the early game, but that's part of the balancing. The problem is that I'm having trouble getting it to be not so OP'd as to be obviously the best while still remaining good enough to be useful.

Any suggestion on how to balance these mechanics to mitigate camping/turtling?

# Answer
> 25 votes
The reason turtling is attractive in this case is because there's no or little incentive to do anything risky during the character's downtime. It's not risk-reward, it's wait-reward. To counter this, you have to incentivize risk. The periods of burst should be buffered with active preparation for their next explosive turn.

There's plenty of ways to do this, but the ones that come to mind are:

**Resource generation**

Your character's burst spells could require a resource that is generated by casting weaker spells. If the character doesn't cast these spells, the resource either generates very slowly or not at all. You could even have a few variants of these resource generation spells that have different risk-reward ratios.

**Preparation spells**

Have "mark" spells that do minimal damage, but are consumed for big damage when your burst spell goes off. Your mage could stack these marks on the target and then trigger it, or navigate around the map applying them before nuking all the targets at once. The big spell wouldn't even need a cooldown in this case, as it would be a wet noodle unless the potency has been amplified by marks.

**Positioning spells**

Maybe your mage does damage in an area of effect, and has displacement spells that do minimal damage. The rest of the team, as well as the mage, could focus their efforts into clumping the enemy so that the burst is more effective. I think this one is the most fun with your resource regeneration items, as the mage could use those to deal heavy damage multiple times before the enemy has a chance to scatter.

---

As others have mentioned, an alternative or addition to rewarding active play is discouraging passive play. This is less specific to the burst mage character and more about turtling in general. My favorites from other answers are:

**Short fights give better rewards**

DrakaSAN suggested decaying rewards for a won fight. You specifically asked that the turtle strategy be viable but not optimal, so perhaps the reward isn't so punishing that it makes future encounters harder (no XP reduction), but maybe something that doesn't *actually* impact gameplay, like some additional dialog after the fight or an achievement if the encounter is beaten in less than X turns.

**The game doesn't just wait for you**

Dronz suggested keeping the game in motion while you wait. This is my favorite, as it allows you do sprinkle lore where turn-based RPGs usually lack it. If you never showed up, the villains would just continue their villainy. If you plan on sitting in a corner, then they may as well stick to their plans as well. BBEG can keep arming his doomsday device, his battle droid factory can keep making more battle droids, and he can polish off that potion of buffing. It'd be neat if these outcomes changed the story of the game in some way.

The time crunch doesn't have to be lore related either. The arena can be flooding with water, the volcano can be close to eruption, the encroaching circle of battle royale can be creeping in, etc.

**The enemies also like breaks**

Dronz also suggested letting the enemy enjoy cooldown time. This means your fights take MUCH longer if you just wait around, or you have a harder time winning because the NPCs have shorter cooldowns and a bigger inventory of items.

# Answer
> 5 votes
**Use ability every N minutes of real time**

Since it is a turn-based game, the player can just wait for the ability to be available again.

**Use ability once or N times per day (sleep to restore, or wait out day-night cycle)**

This works well in the *The Elder Scrolls* serie because you cannot rest if ennemies are nearby. Meaning, if you are in a dungeon for example, you can probably only use it once for the entire dungeon (not saying it cannot be abused, of course).

If you plan to implement this in a turn-based game, just make sure that the player cannot rest whenever, which would make negate the interest of the reloading time.

**Use ability every N turns of combat**

In most game, there are often mechanics tied to resource management. For example, your more classical mana-using mage have to manage its mana pool, so he has to make choices about what spell to use. This is interesting for the player.

Your "*Use ability every N turns of combat*" mage however, doens't have to make those choices, since each spell use its own resource, so to speak. Therefore, the only question the player has to ask himself is "*should I keep this spell for later in the fight or use it right now?*" (since I assume every cooldown is reset when the fight is over).

I believe this is a less interesting choice, because for example, if you decide to heal an ally for 50 HP when he has 50/100 HP left or 10/100 HP left does not make a difference on the result of the fight.

You mentioned items to restore the cooldown of the spells. They are analogous to mana potions in this case. Therefore, I don't think it solves the issue of your cooldown-based mage being less interesting than a mana-based mage.

**Side note**

Have you played pen and paper RPG already? Most of the times, those games include spellcaster classes with different resources mechanics. Take a look at *Pathfinder* classes for example, maybe this could be interesting?

# Answer
> 3 votes
If you make your game a dynamic game world, where things happen as time progresses, and adversary positions, actions, and their own "recharging" effects are also tracked, then you can get a game with natural trade-off consequences from resting without doing anything, because it costs:

* opportunities to take action before the situation changes will be lost if/while the player(s) do nothing but rest
* adversaries can be taking actions the players don't want to happen, while they rest, and other events can happen in the game world
* adversaries can be resting wounds and recharging their own abilities while the players recharge theirs

# Answer
> 2 votes
As Wazpoodle noticed, the problem is mainly that defending for a long time do not have any other drawback than time.

All the propositions revolve around giving the player other things to do during the waiting time, but in combination to those, you may also privilege fights that end quickly.

For example, a fight that is finished in the first 3 turn may give a additional bonus (XP, money...), that degrade slowly over the duration of the combat.

If the player want to turtle, he will receive a reduced / no bonus.

This would incentivize this class (the burst attack may be enough to end the combat on the first turn), while also pushing the player to act now and make do if the burst is not enough.

# Answer
> 2 votes
A very useful way to think of balancing combat is that you have exactly one goal:

> Reduce the damage done to the party

"Heal" is the most obvious way of achieving that goal: it simply erases the damage done.

"Defend" is another direct means of doing so, via diminishing the effectiveness of enemy attacks.

"Attack" is also a means of reducing the damage done to the party: if a player does enough damage to an enemy so that it dies one turn sooner, then that player has achieved the effect of sparing the party from an entire turn's worth of damage.

If you don't want it to be optimal for players to usually choose "defend" rather than "attack", then the trick is to adjust the numbers so that attacking saves more damage than defending does. I think the best way to do this is to look at the figures

* Determine what percentage of a turn's worth of damage the player mitigates by choosing "defend". Take care to account properly: for example, if "defend" only reduces the damage that specific player takes, then choosing that action only has any effect on those turns when that player gets attacked.
* Estimate the entire party's average rate of damage per turn, and compare that to the amount of damage the player can do by choosing "attack". This should let you measure, in turns, how much faster combat will end by making that choice.

---

Note that to get the effect you want to achieve, you probably need the average damage per turn your "burster" class does to be rather low.

This means that you will have to design encounters so that the timing of damage is a valuable thing. For example, if an encounter has three identical enemies, damage done near the beginning of a fight is three times more valuable than damage done near the end of a fight — the former reduces the amount of time you spend with all three enemies damaging you, whereas the latter only reduces the amount of time you spend with a single enemy damaging you.

# Answer
> 2 votes
Fundamentally, the options are to make the undesired player behavior less attractive, to make desired alternatives more attractive, or some combination of the two.

In terms of implementation, it might be worth considering non-linear solutions. You've already identified some disincentives, but I noticed that they all happen to be linear. For instance, limiting an ability to once every X time units. An example of a non-linear approach would be to use a limit of `X+N` where N is the number of times used thus far. Conceptually, you would apply this to something where you find yourself thinking "a little is good, some is fine, but increasingly less so". In terms of theme, this maps on to the idea of diminishing returns.

You can also include more complex formulas. For instance, instead of a strictly increasing value for N, you could include a formula allowing it to gradually ease back over time. Or you could make it more aggressive, `1.5*N`, `3*N`, `N^2`, etc.

While this can give you extra flexibility to your design, there are some trade-offs to consider:

* it creates more parameters to balance
* it can create more obvious 'sweet spots' leading to more average play strategies
    + not necessarily bad, but you need to consider if it detracts from the experience

Non-linearity can also be applied to incentives. For instance, one of the Ascension deck builder expansions has a enemy with a reward of `X+N` where N is the number of times this enemy has been defeated so far. Conceptually, you would apply this to something where you find yourself thinking "a little is okay, more is better & increasingly so". In terms of theme, this maps onto the idea of compounded returns, reaping rewards for early investment.

Again, you can use more complex formulas. A common variant is to include a cap, for instance a reward of `X+min(N,C)` where N is the number of times, C is the cap and the `min` function gives you the smaller of the two.

As before, there are some trade-offs:

* it creates more parameters to balance
* it can create run away leader (aka snowball) effects leading to more extreme, all-in play strategies
    + not necessarily bad, but you need to consider how it impacts the design

# Answer
> 1 votes
A potential solution could have the burst damage be enabled by other skills, such as debuffs, self buffs, and the like. In MMOs this is called a rotation - it's been awhile, but IIRC WoW has a good example with the fire warlock, who has a spell that does a ton of damage, but with limited CDs and a bunch of pre-requisites for getting the most out of the spell.

# Answer
> 1 votes
How about making the abilities recharge from enemy kills? If there's a boss every, say, 10 enemies, and each kill recharges 10% of the power needed, the optimal strategy is, indeed, to use your other abilities to take out the normal enemies, then fire the big guns at the boss.

Path of Exile uses this structure for both flasks (which instantly recharge in town) and Vaal skills (which only recharge in battle).

If you're dead-set on having this be time/turn based, then you need a mechanism in place that punishes taking a long time. For example, enemy monsters can have the same mechanics; if you take too long killing them, they start unleashing dangerous moves. Or reward taking a short time; you get bonus xp or resources if you can quickly kill the enemies.

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


# Question
Title: Character rotation according to camera causes rapid flipping when game starts
When I load my scene, my character rotates +90 and -90 on the X axis very fast about 4 or 5 times, and then he stops at -90 on X axis (lays back down).

When I move the character, the rotations are just the way I want them, but I need to fix that weird bug at the beginning of the game.

Here's my character's movement logic. It's based on the rotation of the camera, which is a child of my character object.

```
void Update() {
    Vector2 vec = new Vector2(horizontal, vertical);
    vec = Vector2.ClampMagnitude(vec, 1);

    Vector3 camF = cam.transform.forward;
    Vector3 camR = cam.transform.right;

    camF.y = 0;
    camR.y = 0;
    camF = camF.normalized;
    camR = camR.normalized;

    transform.position += (camF * vec.y + camR * vec.x) * Time.deltaTime * MoveSpeed;

    Vector3 deltaPosition = transform.position - prevPosition;

    if (deltaPosition != Vector3.zero)
    {
        transform.forward = deltaPosition;
    }

    prevPosition = transform.position;
}

```

# Answer
> 1 votes
> "camera is child object of my character"

Yup, there's your problem. Let's walk through what happens:

1. We use the camera's forward to compute a new position for the character
2. We use the new position to compute a new forward direction for the character
3. The camera is a child of the character, so rotating the character changes the camera's forward
4. But back in point 1, our calculation was based on the camera's forward!

So now the next time we do that calculation, with a different forward, we get a different result...
5. ...which computes a different forward direction for the character
6. ...which changes the forward direction of the camera...

...so on and so on in a feedback loop, which creates the flickering rotation that you observe.

So, easy fix: **don't make your camera a child of the character** if you intend to use the camera to set the character's rotation. This avoids unintended feedback between the two sets of transformation logic.

You'll also want to ensure that your `prevPosition` is initialized and your `horizontal` and `vertical` inputs are populated correctly (we can't see that part of your code - don't hide so much from us if you want deep & useful help!), and you may also want to add a larger tolerance on the `if (deltaPosition != Vector3.zero)` line - possibly comparing `deltaPosition.sqrMagnitude > 0.1 * Time.deltaTime * Time.deltaTime` or somesuch.

---
Tags: unity, c#, rotation, transformation
---


# Question
Title: How to stop my cube collider when it hits another collider using Transform.Translate?
As we know, `Transform.Translate()` ignores collisions. What functionality do I need to add to my code so that when my collider hits something, the physics system makes it stop?

Here is what I'm doing now:

```
void FixedUpdate()
{
    foreach (Touch touch in Input.touches)
    {
        if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
        {
            Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;
            Vector2 pos = touchDeltaPosition;
            pos.x = touchDeltaPosition.x * speed;
            pos.y = touchDeltaPosition.y * speed;
            transform.Translate(pos.x,pos.y,0);

            Ray ray = Camera.main.ScreenPointToRay(touch.position);
            RaycastHit hit;

            if (Physics.Raycast(ray, out hit, 1000))
            {
                if (hit.collider.tag=="Environment")
                {
                    Cubecall();
                }
            }
        }
    }
}
void Cubecall()
{
    anim.enabled = true;
}

```

# Answer
The very easiest and most consistent way is to keep the object in control of the physics system at all times. That way, it can handle the collisions and physics responses internally.

Your code could then look something like this:

```
Rigidbody body;

void Start() {
    body = GetComponent<Rigidbody>();
}

void FixedUpdate() {
    if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
    {
        var touch = Input.GetTouch(0);
        var touchVelocity = touch.deltaPosition/touch.deltaTime;
        var targetVelocity = touchVelocity * speedMultiplier;

        body.velocity = targetVelocity;
    }
}

```

I've removed the `foreach` because you weren't actually using the results of the additional touches - touch 0 was the only one your code ever read, it just applied touch 0 repeatedly if there were other touches present.

I also simplified the multiplication by `speed` (you don't need to do it one component at a time) and renamed the varaible to `speedMultiplier` to convey that it's a magnification/minification factor on the speed of the touch itself. I adjusted the touch `deltaPosition` by its `deltaTime` so that you get consistent results independent of the relative timing/sampling frequency of touch updates and `FixedUpdate`.

---

Or, if you want to move using `transform.Translate` then you should "look before you leap": do your physics query *first* to check how far you can move, and then move only that far.

```
Vector3 direction = targetVelocity.normalized;
float maxTravelThisFrame = targetVelocity.magnitude * Time.deltaTime;

RaycastHit hit;
if ( Physics.BoxCast(
         transform.position,  // Where our cube is now.
         halfExtents,         // How big is our cube, measured from the center out?
         direction,          // Which direction do we want the cube to go?
         out hit,             // Capture information about what we hit.
         transform.rotation,  // How is our cube oriented?
         maxTravelThisFrame   // Where to stop our query?
)) {
    // Moving a hair less than we're allowed leaves us some padding,
    // helping to avoid kissing contacts & unintended tunneling.
    maxTravelThisFrame = Mathf.Max(0, hit.distance - 0.001f);
}

transform.Translate(maxTravelThisFrame * direction, Space.World);

```

---

Lastly, I've noticed in your previous versions of this question, you were using a mix of 2D and 3D physics types. These are processed by completely separate physics engines in Unity, so a 3D Rigidbody or BoxCast will not respond to collisions with a BoxCollider2D. Be sure you're using one regime - 2D or 3D - consistently, with all physics components and callback methods you want to interact together.
> 0 votes

---
Tags: unity, c#, 2d, physics
---


title: (SFML) Moving in one direction a time

text:
# Question
Title: (SFML) Moving in one direction a time
so i've been making a pathfinder on a grid. I've succesfuly implemented the A\* algorithm so the next step is making the AI follow a path. I got it to move to the desired destination but the thing is it moves diagonally and I dont want it to. I want to move vertically or horizontally. this is my current code:

```
void AIEnemy::AutoMotion(Gridspot& grid)

{

std::pair<int, int> ecn = getNodePosition();

sf::Time deltaTime = clock.getElapsedTime();

std::reverse(grid.Path.begin(), grid.Path.end());

for (auto path : grid.Path)

{

float rectx = rect.getPosition().x + rect.getOrigin().x / 2,

        `recty = rect.getPosition().y + rect.getOrigin().y / 2;`
bool firm= true;

if (ecn.first == path.node.first && top >= path.rectCenter.y)

{

rect.move(0, -2);

}

if (ecn.second == path.node.second && left >= path.rectCenter.x)

{

rect.move(-2 , 0);

}

}

}

```

before i had a bool set that will ring true it is already in motion to so that it couldn't move in the x-axis in conjunction to th y. that didn't work, i also used if and elseif is before ut that didn't do anything. essentially I want it to move like pacman ghosts

# Answer
What you need to do is, once you begin moving in one direction, make it impossible to to move in another direction until you complete the movement. It would look something like this in psuedocode:

```
if (!moveableObject.isMoving()) {
    if (pathIsOpenUp()) {
        moveableObject.setTrajectoryUp();
    }
    else if (pathIsOpenLeft()) {
        moveableObject.setTrajectoryLeft();
    }
    // Repeat for bottom and right
}

```

Now your trajectory function needs to persist between frames and your `isMoving()` flag needs to be cleared and trajectory zero'd out when the end of a path is reached.
> 1 votes

---
Tags: c++, sfml, grid
---


# Question
Title: Switch from left click to right click to make character walk in the Top Down Example, in UE4?
When creating a new project in the Unreal Engine 4, you can choose to create a project already with some added features and things (**Top Down Example**):

This project has a character (which I changed its appearance) and it moves around the map when I click the left mouse button:

I looked at the blueprints of the project, but I did not identify where the command is that makes the character walk, so I'd like it to walk when I right-click.

Alls blueprints of project:

**M\_Cursor\_Decal:**

**TopDownCharacter:**

**TopDownController:**

**TopDownGameMode:**

The circled blocks of reds are the ones I suspected could be where I should make the modification, but no information on them gave me the certainty that that was where I was supposed to change.

I still do not create projects in C ++ programming mode, because I do not have Visual Studio 2017.

Some links from websites where I spent before coming here and that can help you to help me:

https://docs.unrealengine.com/en-us/Engine/Blueprints

https://www.youtube.com/watch?v=EFXMW\_UEDco

***The video is 2015, so although it's good, I did not take it so well, because I know that with all this time that has already happened, a lot is different.***

Sorry for any translation errors, I'm not English speaker.

# Answer
> 0 votes
Go to Edit =\> ProjectSettings =\> Engine =\> Input =\> Action Mappings:

1 = Project settings

2 = Input

3 = Action Mappings

4 = Right mouse button (That's where the modification is made)

Link that helped me:

https://docs.unrealengine.com/en-US/Gameplay/Input

---
Tags: unreal-4, blueprints
---


title: Modular weapon in UE4 editor

text:
# Question
Title: Modular weapon in UE4 editor
I want to create a modular weapon system. I already got most of it working, but I wonder how to make an improvement.

Weapons in my game have different firing modes (semi and auto) and "bullet" modes (projectile and hitscan). Each weapon is it's own blueprint, and there I can select proper one in editor, so for example an Uzi would be auto / histcan, while a rocket launcher would be semi / projectile. (the firing mode actor gets created at spawn from the class selected in editor).

I want to make it easier to edit by giving the weapon some variables, like spread and projectile blueprint. But not all of the variables apply to all the types of weapon...

TLDR: Can I create / show different variables in the editor, depending on other variables? If I choose projectile type of weapon, can I also select the projectile type, but not show the option if I chose hitscan?

# Answer
> 0 votes
Yes you can, Take a look at EditCondition meta specifier in UPROPERTY.

for example:

```
UPROPERTY( Category=Location, EditAnywhere )
uint32 bUseOffset:1;

UPROPERTY( Category=Location, EditAnywhere, meta=(EditCondition="bUseOffset") )
FVector Offset;

```

In this case the `Offset` will be editable only if `bUseOffset` is true.

Please also refer to: UE4 documentatoon

---
Tags: unreal-4
---


title: UE4 - UMG button polymorphism

text:
# Question
Title: UE4 - UMG button polymorphism
I want to make a menu with a bunch of buttons. I want them all to look the same and be easier to edit, so I decided to make one "Button Parent" widget, insert it few times and give it a different "on click" action.

I can't access the "on click" event in the main menu widget, also I apparently can't create a button child. My only idea left is to make a public variable for the button, and then do a different action depending on the variable once I set it in the main widget.

Is there a better / easier way to do this?

# Answer
> 1 votes
There are many ways to achieve it... you can use delegates - to delegate the onClickEvent. You can pass a pointer to your baseParentWidget and call its functions (interface or whatever).

You can use latent actions (there will be a plugin enabling this for BP soon in marketplace)

---
Tags: unreal-4
---


# Question
Title: Creating a real loading screen between levels in Unreal Engine 4
I'm trying to create a loading screen to pop up between levels in Unreal Engine 4. I want to have a traditional loading screen such as the loading screen in Skyrim, where the player presses play and text alongside a small model pops up until the game is finished loading.

However, the only information I have found on the internet is related to level streaming which is definitely not what I want. The game I'm working on has very big levels with different gamemodes in each of them, which level streaming can't handle. Also I've found some obsolete plugins to do this which no longer works on the latest UE versions. I've also found some "hacks" that are pretty much display an icon on the main menu while waiting for the "Open Level" blueprint function ends up loading the level, yet I'm skeptical if this technique will work when the level to load is quite big and complex.

How can I create this loading screen? where I can find information on the topic?

# Answer
Your best bet is to look at MoviePlayer API, You can use a MoviePlayer, despite the name it can also draw widgets, UMG/Slate widgets.

It requires some little C++ knowledge to achieve it. You have a tutorial here: https://forums.unrealengine.com/community/community-content-tools-and-tutorials/67244-seamless-proper-loading-screens-play-movies-audio-animated-widgets
> 1 votes

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


title: TArrray<FColor> to Texture2D in Unreal

text:
# Question
Title: TArrray<FColor> to Texture2D in Unreal
I have a TArray of type FColor (I got it from the viewport) and I want to change that to a Texture2D object I can't find anything in the API's and I'm new to Unreal.

Thanks

# Answer
It is possible with C++

Then you should lock its data Memcpy the data And update resources.

Here is a code snippet I am using currently:

    static UTexture2D* CreateTextureFromBGRA(FColor* data, int width, int height)
    {
        UTexture2D* Texture;

        Texture = UTexture2D::CreateTransient(width, height, PF_B8G8R8A8);
        if(!Texture)
        {
            return nullptr;
        }

#if WITH_EDITORONLY_DATA
        Texture->MipGenSettings = TMGS_NoMipmaps;
#endif
        Texture->NeverStream = true;

        Texture->SRGB = 0;

        FTexture2DMipMap& Mip = Texture->PlatformData->Mips[0];
        void* Data = Mip.BulkData.Lock(LOCK_READ_WRITE);

        FMemory::Memcpy(Data, data, width * height * 4);
        Mip.BulkData.Unlock();
        Texture->UpdateResource();

        return Texture;
    }

    static UTexture2D* CreateTextureFromDXT5(uint8* data, int width, int height)
    {
        UTexture2D* Texture;
        Texture = UTexture2D::CreateTransient(width, height, PF_DXT5);

        if (!Texture)
        {
            return nullptr;
        }

#if WITH_EDITORONLY_DATA
        Texture->MipGenSettings = TMGS_NoMipmaps;
#endif
        Texture->NeverStream = true;
        Texture->SRGB = 0;

        FTexture2DMipMap& Mip = Texture->PlatformData->Mips[0];
        void* Data = Mip.BulkData.Lock(LOCK_READ_WRITE);

        int32 NumBlocksX = width / GPixelFormats[PF_DXT5].BlockSizeX;
        int32 NumBlocksY = height / GPixelFormats[PF_DXT5].BlockSizeY;

        FMemory::Memcpy(Data, data, NumBlocksX * NumBlocksY * GPixelFormats[PF_DXT5].BlockBytes);

        Mip.BulkData.Unlock();
        Texture->UpdateResource();

        return Texture;
    }
```

> 1 votes

---
Tags: unreal-4
---


title: Unreal Engine Size on Disk

text:
# Question
Title: Unreal Engine Size on Disk
I want to install Unreal Engine 4 from the epic game launcher but I have the following problem: If I want to install the engine after about 50% it says I don't have enough space on my disk, and if I look up how much space the folder took it says 75 GB is that normal?

# Answer
> 1 votes
No it is way too much! I have three engines installed and they take around ~80+gb

---
Tags: unreal-4, installer
---


title: Texture Glitches When Drawn to Quad

text:
# Question
Title: Texture Glitches When Drawn to Quad
Recently been trying to implement volumetric lighting. The alphaness texture comes out perfectly on Renderdoc, however a strange glitch occurs whenever I either try to directly render the texture through a quad to the screen, or through multiplying the alphaness component with my regular texture. A strange static pattern (as shown in the image below) appears on the texture. The texture also periodically turns completely black, and in some frames the image comes out perfectly.

The volumetric lighting texture is rendered to a framebuffer with the settings below:

```
' Configure God Rays Buffer
' -------------------------
godRaysFramebuffer = GL.GenFramebuffer()

' Create color buffers
GL.BindFramebuffer(FramebufferTarget.Framebuffer, godRaysFramebuffer)
currentFrameTex = GL.GenTexture()
GL.ActiveTexture(TextureUnit.Texture0)
GL.BindTexture(TextureTarget.Texture2D, currentFrameTex)
GL.PixelStore(PixelStoreParameter.UnpackAlignment, 1)
GL.TexParameterI(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, All.MirroredRepeat)
GL.TexParameterI(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, All.MirroredRepeat)
GL.TexParameterI(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, All.Nearest)
GL.TexParameterI(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, All.Nearest)
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.R16f, resolutionWidth,
              resolutionHeight, 0, PixelFormat.Red, PixelType.Float, IntPtr.Zero)
GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0,
                        TextureTarget.Texture2D, currentFrameTex, 0)

Dim attachments() As Integer = {FramebufferAttachment.ColorAttachment0}
GL.DrawBuffers(attachments.Length, attachments)

```

The alphaness texture, from Renderdoc, is shown below:

The fragment shader which samples from the god rays texture (my HDR shader) is shown below. When I comment out the `* texture(godRaysTex, TexCoords).r` it renders perfectly, however without the god rays.

```
#version 440 core

out vec4 out_color;

in vec2 TexCoords;
in vec3 vPos;

uniform sampler2D hdrBuffer;
uniform sampler2D godRaysTex;

uniform float exposure;

void main() {
    const float gamma = 1.8;
    vec3 hdrColor = texture(hdrBuffer, TexCoords).rgb * texture(godRaysTex, TexCoords).r;

    // Exposure tone mapping
    vec3 mapped = vec3(1.0) - exp(-hdrColor * exposure);
    // Gamma correction
    mapped = pow(mapped, vec3(1.0 / gamma));

    out_color = vec4(mapped, 1.0);
}

```

Here is my volumetric lighting shader:

```
#version 440 core

uniform vec2 lightPositionOnScreen;
uniform sampler2D occlusionTex;

const int NUM_SAMPLES = 100;

const float exposure = 0.45;
const float decay = 0.98;
const float density = 0.9;
const float weight = 0.07;

in vec2 TexCoords;
in vec3 vPos;

layout (location = 0) out vec4 FragColor;

void main() {
    vec2 textureCoords = TexCoords;
    vec2 deltaTexCoords = vec2(textureCoords.xy - lightPositionOnScreen.xy);
    deltaTexCoords *= 1.0 /  float(NUM_SAMPLES) * density;
    float illuminationDecay = 1.0;

    // Evaluate summation from Equation 3 ( see https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch13.html) NUM_SAMPLES iterations.
    for(int i = 0; i < NUM_SAMPLES; ++i) {
            textureCoords.x = clamp(textureCoords.x, 0.0, 1.0);
            textureCoords.y = clamp(textureCoords.y, 0.0, 1.0);

            textureCoords -= deltaTexCoords;
            vec4 occlusionSample = texture(occlusionTex, textureCoords);
            float alpha = occlusionSample.r;
            occlusionSample.r = 0.0;
            occlusionSample.a = alpha;

            occlusionSample *= illuminationDecay * weight;

            FragColor += occlusionSample;

            illuminationDecay *= decay;
    }

    FragColor *= exposure;
    float alpha = clamp(1.0 - FragColor.a, 0.0, 1.0);
    FragColor.a = 0.0;
    FragColor.r = alpha;
}

```

# Answer
Through trial and error I spotted the issue. I was using the output variable `FragColor` in my god rays shader to perform the calculations. As a result, OpenGL probably would think a fragment was finished being written to on its first assignment, while it was in fact in the process of a calculation in the loop.

Changing `FragColor += occlusionSample;` into `color += occlusionSample;`, where `color` is a `vec4` defined in the scope of the `main()` and then setting `FragColor = color` at the end of the calculations solved the issue.
> 0 votes

---
Tags: opengl, glsl, frame-buffer, volumetric-light
---


# Question
Title: How to properly handle sending arrow-key movement data to a authoritative server?
I've made a little C# server which receives UDP packets and shows me the incoming information. I want to make an authoritative server in C# which simulates character movement and interaction in a 2D real-time world and sends information back to a Unity game client where the information is then represented.

**My question is:** How does my server know how long a button is pressed in real-time (example: right arrow key to move character right)?

**My guess** is that the client would send a UDP packet to the server on-key-press saying *move-this-direction*. The server would then simulate the character moving and new positional information is constantly sent back. When the Client releases the key a new UDP packet is sent to the server saying the movement key has been released thus *stop-moving-this-direction*. **BUT** the problem is UDP unreliability and the lag between letting the key press up, and the server knowing that the key press is up; which would make the character keep moving for a period of time after letting go of the key - is this solved with proper movement interpolation?.

Any ideas or information sources how to properly handle sending arrow key movement data to a authoratative server?

# Answer
If you're using UDP then, as you say, you don't get reliability from your transport layer, so you'll need to build it into your game layer instead.

In addition to the TCP style of detecting a missed packet and requesting it be re-transmitted, there are two common ways realtime games implement reliability:

* Don't. Just have every agent spam you with their current state constantly, and if you miss one it's no big deal, the next state update will arrive faster than requesting a re-transmission anyway. Just skip it and move on, using interpolation to cover the gap. This works well for states like position that can be interpolated smoothly.
* Pack the last few updates together into each packet. That way if one of the past updates was dropped, it can be corrected on the net update without requesting & waiting for re-transmission. This works well for changes that need to be integrated in order, like your keypresses.

You'll of course also want to send some type of time information with the key down/up information: "Key Down at time XX:XX" or "Key Down at Tick XX"

This lets your server compensate for (variability in) latency, and simulate the commands in the right order/timing to get the same result as the client. Two considerations here:

* To prevent cheating, you should only accept timestamps in a "reasonable" range given the observed network latency to this client.

If someone says "oh yeah, five seconds ago I totally dodged that bullet" then either the network is way too slow to support realtime play with this client, or they're fudging numbers. Either way, it's a sign you should probably drop this client.
* Correctly simulating these discrete events can require rewinding the game state to the stamped time, applying the change, then re-simulating forward from there.

This is more complicated than applying the change at the time of receipt, but it helps you get faithful replication of the simulation, since the net result of a button-down & -up pair is so highly dependent on the timing of & between the events.

If this is too complicated, you can synchronize positions instead, rather than keypresses, but that can make it harder to detect certain forms of cheating.
> 4 votes

---
Tags: networking, movement, client-server, udp
---


# Question
Title: Need instructions for my AI racing car game
I'm having a school project to create an 2D AI racing car game, but nobody know where is the destination, and the map is randomly generated. But to avoid the dead end, we must teach the car not to move to that path again. I wonder if there were any algorithms or methods to store the dead end which was passed. I have searched the A\* algorithm but I think that algorithm doesn't help me in this case.

The map should look like this:

And this is the road:

# Answer
Do you generate the whole map at once or do you only generate in increments?

---

If you generate the whole map at once, then you generate the goal and thus you could use A\* or similar algorithm without any modifications.

If you just do not know where the goal is, A\* still works. A\* will exhaust all paths until it finds the goal or fails. However, you may lack a good heuristic because you do not know where the goal is, so you could tweak A\* to work without it (or use Dijkstra's algorithm).

---

On the other hand, if you generate in increments, the goal might not be in the map yet. This means that you need two different behaviors:

* Explore
* Go to the goal

To "store were any algorithms or methods to store the dead end which was passed" you use influence maps. It is a structure that mimics (or is attached to) the actual map where you store what have been visited. You could have an influence map per agent, or multiple agents can share a single influence map, that depends on what you want.

Now, exploring is easy: pick a known open path or unexplored area (usually something at the edge of what you have explored), set it as target and go there. This should reveal/generate more parts of the world. You continue to do this until you run out of areas to explore or you find the goal. Which place do you pick to explore? You probably want to pick the closest to the agent, however picking at random should still work. I would like to encourage experimentation.

And of course, once you have discovered your goal you can try going there... there is a chance that you found the goal, but not the path to it. No problem, A\* will find a way... you just need to know the following: each frame/turn you just need to decide on what direction to move, not the whole path. So, if you set a maximum number of iterations for A\* per frame/turn, or let it run until you exhaust some percentage of your time budget for the current frame, you can pick the best of the paths it found (you have an admissible heuristic, right?) and follow that one.

I'll plug here my answer to Java Game Loop Efficiency, you could find it useful.

---

What I said above should be enough to solve the problem. If you are looking for something different keep reading.

If all else forms of searching fails, there is good old breadth-first search, which should explore without any information of the goal. You might also be interested in D\* Lite.

If you want a more general solution, you might look into Q-Learning or SARSA. You could feed an admissible heuristic as reward for it. It does not require knowledge of the world (so no influence map, and no location of the goal), instead it uses table that relate actions and probable outcomes.

See the lecture MIT 6.S094: Deep Reinforcement Learning for Motion Planning video (1 hour 27 minutes 29 seconds) for a detailed explanation of Q-Learning.

---

## Addendum

Given the nature of the mazes, a randomized recursive back-tracker is a good solution. Why? Because that is likely how the maze were created in the first place. A maze generation algorithm based on this fills the map, has no large rooms - only corridors and intersection - has no disconnected areas, has no loop, lots of dead ends and no large scale structure.

How to solve a maze with a randomized recursive back-tracker?

At every moment you look at the paths you could take (excluding those where you have already been) and if there is only one path, you go that way, if there are many you pick at random, if there is none, you backtrack (meaning you go back from where you came).

To know your path, you store a stack of the positions you have been, so you can push to the stack every step you make, and pop when you backtrack. However you do not want to go down the same path you went last time (you know it is a dead end), so you need to also keep a list of visited positions (or given that the map is on a grid, you can have an array of bool where you set true to mean visited).

This algorithm is guaranteed to visit the whole map. However, it is unaware of the goal. If we know where the goal is - and since it is randomized - we can tweak it with a heuristic based on the location of the goal. Instead of going at random, we pick the direction that moves closer to the goal.

---

Similarly you can use this algorithm to create a maze. At the start you could go in any direction, however, since you will not step where you visited, you will eventually get to a dead end (trapped by your previous path) at which point you backtrack, and then branch at some earlier point, and keep doing this until the whole available are has been carved to a maze (you know you finished because you should backtrack but there is no more to backtrack, you are where you started).

Visualization.

---

## Notes

If you do not know the location of the goal, but you know the size of the maze and that the goal is likely away from the start, you can create a heuristic based on how far you have moved from your starting position. Remember that heuristic in path finding use an estimations of the distance to the goal... so you could take the diameter of the maze and subtract how far from the start you are. However be aware that this would not be considered an admissible heuristic because it can over estimate the distance (if your teacher sets the goal close to the start, it becomes a bad heuristic). If your algorithm is guaranteed to explore the whole map, using a not admissible heuristic will not prevent getting to the goal, but it will be very inefficient.

Also, remember that your map knowledge representation (influence map et.al.) does not have to match the world one to one. Working with a coarser representation can make the code run faster even if that means it is less precise. I do not know with how much resolution you can steer the car, however, as far as path finding is concerned the road could be made of line segments or a very large grid compared to the car. In fact, in some cases, we use multiple representations at different levels of resolution.
> 0 votes

---
Tags: java, ai, car
---


# Question
Title: Understanding the "gradient" in Perlin Noise
If I didn't get it wrong from the wikipedia, the word "gradient" should represents either the derivative for continuous functions, or the differential for discrete functions.
To rebuild the original function, I would integrate the gradient function, or calculate the partial sum of them.
Dot production between a unit vector and a gradient vector represents the slope/change-rate along the direciton of the unit vector.

But perlin noise seems unable to be explained. We calculate 4 gradient productions between related positions and random generated gradients in 4 corners, then simply interpolate them resulting the final value.

Is there something I've missed? How to understand operations on gradient vectors for perlin noise?

# Answer
> 1 votes
Perlin noise's gradient vectors are exactly what you describe: the vector derivative of the continuous noise function.

Specifically, each gradient is the derivative of the noise function *at one corner of the underlying integer grid*.

Perlin noise is set up so that at each integer point in its domain, it is "locally flat," like a straight line or plane with a particular slope given by that corner's pseudorandomly-selected gradient vector, passing through a value of zero at the corner point itself.

In this diagram of 1D Perlin noise from Scratchapixel, we can see how Perlin noise is constructed by choosing a gradient at each integer coordinate along the X-axis, giving us the slope of a line crossing through that point (the blue arrows).

Very close to this point, the noise function behaves like that straight line, with exact equality in both value and derivative at the integer points themselves (this is what ensures we don't get seams between adjacent blocks of Perlin noise)

In-between these integer points, we blend between these lines/planes through the \\$2^n\\$ closest integer points in the domain. The dot product of our offset from the integer point with the gradient at that point gives us the value we should have if we continued the flat line/plane through that point out further. Interpolating these \\$2^n\\$ planar points gives us a compromise value that's generally not on any of the corner planes, but can smoothly bend from one to the other as we move around the domain.

In this in-between region, the gradient of our function is no longer the gradient at any of the corners, but a blend between them that we can calculate the same way we do for the value.

---
Tags: mathematics, perlin-noise, noise
---


# Question
Title: Directx9 - Generate mesh from vertex and index buffer
I've got a single vertex buffer and an index buffer for a cube in Directx9. I now want to generate a LPD3DXMESH object from them, so that I can manage mouse picking and other stuff with the cube model. How can I achieve this? Here's the code of my vertex and index buffers:

```
CUSTOMVERTEX vertices[] =
{
    { -3.0f, 3.0f, -3.0f, D3DCOLOR_XRGB(0, 0, 0), },
    { 3.0f, 3.0f, -3.0f, D3DCOLOR_XRGB(0, 0, 0), },
    { -3.0f, -3.0f, -3.0f, D3DCOLOR_XRGB(0, 0, 0), },
    { 3.0f, -3.0f, -3.0f, D3DCOLOR_XRGB(0, 0, 0), },
    { -3.0f, 3.0f, 3.0f, D3DCOLOR_XRGB(0, 0, 0), },
    { 3.0f, 3.0f, 3.0f, D3DCOLOR_XRGB(0, 0, 0), },
    { -3.0f, -3.0f, 3.0f, D3DCOLOR_XRGB(0, 0, 0), },
    { 3.0f, -3.0f, 3.0f, D3DCOLOR_XRGB(0, 0, 0), },
};

d3ddev->CreateVertexBuffer(8 * sizeof(CUSTOMVERTEX),
                           0,
                           CUSTOMFVF,
                           D3DPOOL_MANAGED,
                           &vertex_buffer,
                           NULL);

VOID* pVoid;
vertex_buffer->Lock(0, 0, (void**)&pVoid, 0);
memcpy(pVoid, vertices, sizeof(vertices));
vertex_buffer->Unlock();

short indices[] =
{
    0, 1, 2,
    2, 1, 3,
    4, 0, 6,
    6, 0, 2,
    7, 5, 6,
    6, 5, 4,
    3, 1, 7,
    7, 1, 5,
    4, 5, 0,
    0, 5, 1,
    3, 7, 2,
    2, 7, 6,
};

d3ddev->CreateIndexBuffer(36 * sizeof(short),
                          0,
                          D3DFMT_INDEX16,
                          D3DPOOL_MANAGED,
                          &index_buffer,
                          NULL);

index_buffer->Lock(0, 0, (void**)&pVoid, 0);
memcpy(pVoid, indices, sizeof(indices));
index_buffer->Unlock();

```

# Answer
You can't, as far as I recall, create a mesh directly from vertex or index buffers (as the mesh object wants to maintain those buffers itself). You can create it from the vertex and index data you already have though:

1. Create the mesh using `D3DXCreateMeshFVF`, providing the appropriate vertex format information and the correct face and index counts.
2. Use `LockVertexBuffer` and `LockIndexBuffer` on the resulting mesh (they are both base class methods) to get pointers to the buffer content.
3. Copy your data into the resulting pointers.
4. Unlock the buffers.

With this method you don't need to call `CreateVertexBuffer` or `CreateIndexBuffer` yourself, as the mesh will do so. Make sure you pass the correct flags to the mesh-creation function to ensure the underlying buffers are created in the (managed) pool you expect them to be in.
> 3 votes

---
Tags: directx9
---