# Question
Title: Is it possible for Minecraft to use time-dependent in-game progression rather than current tick-dependent?
I see the problem of the current tick-dependent approach to propel the in-game progression. The drawback of this tick-dependent approach is that if a computer running the game is not powerful enough, or there is so many entity to be ticked, the TPS will drop and overall in-game progress will be slowed down, which will negatively impact the in-game experience and immersion.

If the game used time-dependent approach instead, behavior and progression of any entity in a world will be based only on time, which increments regardless of how fast the computer is.

Imagine of projectile motion. The position of a projectile can be readily calculated by the simple formula which is a function of time, without the need of "repeatedly ticking" the object to the new position.

Also this can apply to any redstone circuits, which has exact operation time for each component. Given a serial connection of redstone repeaters, which, for some given time, can be finded out that which repeater is activated.

I wonder that this approach can be apply to Minecraft (or other video games)?

# Answer
Yes, up to a point. In practice, no.

This is due to the butterfly effect. In a system with enough interacting elements, there is not one simple formula that will predict its state \\$t\\$ seconds from now. The system starts to exhibit what's called chaotic behaviour, where small perturbations in the state (like from a tiny integration error or rounding of an intermediate result) lead to large deviations in its future trajectory.

This is easy to see when we consider huge timesteps. Could the computer simulate in one tick what your Minecraft world would look like a full year from now? Obviously not - there's too much that could occur in that timespan. So any prediction we make in a single tick is likely to contain errors. That same argument applies, in diminishing degrees, to every timestep longer than a single tick.

The further you move something in a single step (to account for more time passed), the greater the chance that you skip over and miss a collision that should have happened along the way, a physics glitch we call "tunnelling". There are more expensive ways to reduce missed collisions, but even they don't guarantee you'll get exactly the same results at any time interval — even just rounding to a finite precision for storage is enough to break this.

That means you could load the same Minecraft save on a fast computer and on a slow computer, sit there without affecting the system in any way, and see two different sequences of events play out. Players get different gameplay outcomes depending on their hardware!

The only way to guarantee you get consistent results is to run your simulation consistently: using the same step size/frequency.

This is why many games implement what's called a fixed timestep (equivalent to a standardized simulation tick) - to ensure that no matter how fast or how slow your computer runs, you still get the same gameplay behaviour, so players on all kinds of hardware can play and be treated fairly (even if players on slower machines get choppier performance - at least they're playing the same game with the same eventual simulation results).
> 0 votes

---
Tags: minecraft-modding
---


# Question
Title: Find point along x axis where yz plane flips to back facing after perspective projection. Have a solution but don't know why it works
I am trying to find the point along the x axis where a plane with normal pointing along the x axis would flip to back facing after perspective projection. Essentially the red line in this image.

My first attempt to find it I just sampled along the x axis checking if a triangle there was back facing after projection. This only gave me an approximation but I could make the approximation as accurate as I wanted by just sampling more planes so I used this as a baseline to verify other solutions.

I then tried the following:

```
vec4 center = projection.inverse()*vec4(0,0,0,1);
center /= center.w;
float d = dot(center.xyz, vec3(1,0,0));
vec3 point = vec3(1,0,0)*d;

```

But this did not work, it was close but not right. See this image, the red line is the sampled point and the blue is the one calculated from that.

I then tried changing the calculation for center to `projection.inverse()*vec4(0,0,-1,1)` to see what that would look like. With the the sampled point in red, the blue line being the previous version and the green the new version. I got the following image which as you can see is still not correct.

But I noticed that the green was always directly between the blue and the red so I tried the following.

```
vec4 c1 = projection.inverse()*vec4(0,0,0,1);
c1 /= c1.w;
float d1 = dot(c1.xyz, vec3(1,0,0));
vec4 c2 = projection.inverse()*vec4(0,0,-1,1);
c2 /= c2.w;
float d2 = dot(c2.xyz, vec3(1,0,0));
float d = (d2-d1)*2 + d1;
vec3 point = vec3(1,0,0)*d;

```

Which seems to be correct but I have no idea why that works. It is always extremely close to the sampled point so I assume it is correct.

My question is why does this work?

# Answer
Essentially you have to project worldspace camera position on line. The position of projection would be the point where normals flip.

Having arbitrary point on line, normalized line direction and camera pos you can do following:

```
float d = dot(CamPos.xyz - LinePos.xyz, NrmLineDir.xyz);
vec3 point = LinePos.xyz + NrmLineDir.xyz * d;

```

I think what you did was overcomplicated solution of what I wrote here, so removing some of the code would result in same solution.
> 0 votes

---
Tags: graphics, linear-algebra
---


title: Multithreaded callback

text:
# Question
Title: Multithreaded callback
I'm making a multiplayer game where players fight in vehicles, and I am doubting my server architecture. As it will be physics, network and AI intensive I would like to split these 3 topics into their own thread. Perhaps even one thread per AI.

**The physics thread** will run at a fixed time-step and do the same loop over and over.

1. Integrate gamestate at fixed timestep of 0,005s (200Hz)
2. Solve gamestate for constraints and collisions
One such constraint is a vehicle controller, which is a `struct` consisting of throttle, steer, brake etc. is applied to a single vehicle.
3. Callback
    1. The network is called every 6 physics frames, thus the networking runs at ~33Hz
    2. The AI is also called every 6 frames.
    Note: network and AI can be called in lockstep

**The AI threads** will calculate the next move on a need-by-need basis.

1. Copy gamestate into private memory
2. Calculate next move
3. Update their vehicle controller in the game state

**The network thread** will

1. Listen for incoming UDP packets, handle them, apply changes to gamestate such as player's vehicle controller, bullet spawn
2. When called for, broadcast the new gamestate to clients
    1. Copy gamestate into private buffer
    2. Create array of differences from last state
        1. Vehicle parts removed/added
        2. Vehicle parts moved/rotated
        3. Players joined/left
        4. Projectile impacts and damages
    3. Pack the differences together and broadcast.
3. When a new player joins:
    1. grab the last private game state buffer and send it whole
    2. Change gamestate by spawning a vehicle and allocating a controller

# What I'm having trouble with:

1. Creating threads on the fly has overhead, so I would like to avoid it by pre-creating and "parking" the threads, and calling them when needed. Once called, they do their duty, such as calculate the next move for the AI to make. Then the threads "hibernate". Note that I **don't** want the threads to wait in a busy loop and read some shared memory for "activation".
2. The AI and Network threads need to make private copies of the game state, because the physics run so fast the game state might be changed mid-read.
    1. Mitigation 1: swapping game state buffers. Still no guarantee.
    2. Mitigation 2: locking the gamestate. This is a bad idea because the physics should not be held up.

How can I achieve this in C++? Does x86 offer actual interrupts for this? How about other architectures, or are there libraries that do this for me?

Or should I do it another way?

# Answer
1. a `std::condition_variable` will let you `wait_for` the `event_queue.has_event()` when pushing an event you can `notify_one` to wake up the waiting thread. However the downside of this is that you are depending on the scheduler to actually wake up the thread. However scheduler resolution can be larger than you'd expect.
2. it's better if only 1 thread is doing the manipulation of the game state. So instead of your AI thread doing updates directly it instead sends message tot he physics thread of how the AI struct should be updated. Similarly with networking.

You can take read-only snapshots of the gamestate to make AI decisions. This can be made easier with double buffering.

The AI thread has 2 buffers it uses: reading from the last state and writing to the new state. Then when the update is done it sets the newly written state as the latest. And the other 2 threads can read-lock the latest buffer to make their decisions. Make sure you have enough that there is always a unused buffer to allocate for the next written to. In your case you'll need 5 gamestate buffers, 2 for the networking thread doing a diff, 1 for the AI, and 2 for the updater thread.
> 1 votes

---
Tags: c++, physics, multiplayer, multithreading
---


# Question
Title: How to deal with race conditions on a game server between network and physics update loops?
I am new to game networking.

In various articles on the internet, I found that there are usually two loops on the server: one for physics updates and the other for sending snapshots to the client (network updates). As I understand, loops can run in parallel, which makes me think they should run on different threads.

Now, in terms of concurrency, physics thread is the *writer* and the network thread is the *reader*. Given that the threads can run concurrently, there can be race conditions: reader thread can read inconsistent game state if the writer thread is currently modifying it.

How to deal with this race condition? The crude approach would be just to use lock on the game state, but it seems to me that this will introduce delays. For some reason I can't find anything on the web.

# Answer
> 1 votes
One option is to copy the state to a buffer after each simulation step. This operation is typically not *that* time consuming when compared to performing the step per se. The network thread then consumes this static buffer instead of the main game state.

Given that the simulation step is done 3 times more often than the network step, one could think about only performing the "copy-to-buffer" step only once every three step. Although this could save some time in performing the copy, you could get introduced delays when the network thread waits for a fresh version of the state buffer. You'll need to experiment with your setup to see if the delay introduced by the thread waiting is ultimately more expensive than the delay introduced by copying the state every frame.

---
Tags: networking, client-server, game-state
---


# Question
Title: How would a turn based RPG game store move information in a reusable way?
Suppose I create a turn based RPG in the veins of Pokémon, with a lot of moves and abilities, that would have elements of hand made code, in cases for special effects after a successful attack or status effect, for example, a status buff every turn, or an automatic attack every turn (think rollout or outrage from Pokémon).

```
def move_name():
    do_primary_effect()//damage, status effect
    do_secondary_effect()//on hit effects, side-effects,
    //delayed buffs/debuffs, setting next move, i.e. rollout, etc.
    set_flags()//flags like invulnerability from moves like dig, fly, etc.

```

Now suppose I wanted to make this game open source and allowed people to make their own builds/rebuilds or online versions, where they might use a different language. How can I program my moves/abilities in such a way that it can be interpreted by any compiler, regardless of language, so that there is no re-coding moves for different languages?

tldr; how would I go about a format for moves/abilities such that it is compiler independent(might be the wrong word, but means can be read and translated). Now I'm not asking for a direct answer, though those are greatly appreciated, I'm talking mostly about how such a format would look like, so real life examples for existing videogames are greatly appreciated. I've heard my friend say that Pokémon does this with a data structure, so data structures are also appreciated.

# Answer
> 3 votes
It looks like what you would essentially like to do is create a game engine (like RPG Maker) or a game with some modding tools with the ability to create custom semi-defined object (like Skyrim).

**Game Engine Approach**
Typically when people make their own engine, their own program will include a compiler that reads another scripting language (typically LUA but Unity for example reads Unity Script and C# even though its core was written in C++). Normally this is a really difficult approach but if you want to make a fully open Game Engine then this is the route for you. Just bear in mind it is again, really difficult and probably way out of the scope of what your really want.

**Data Driven Approach**
When creating the ability to mod in new existing concepts in your game (items, moves, characters, stories, etc.) you can do this by creating a generic classes that represent these concepts (Item.cs, Move.cs, Npc.cs, Dialog.cs, etc.) and setting variables within them using data read from external files. These files can be stored anywhere, but to make things easy you should probably place them in your StreamingAssets folder. Typically this approach can be a bit limited but it allows players to build on your game, or make their own custom game without varying too much from the core gameplay you designed. You can find many examples of systems like (such as Pokemon like your friend suggested), but I will give you a quick untested sample of how you might make something like this:

--- Game Classes ---

```
public enum EffectType
{
    Damage,
    Debuff,
    // etc.
}

public enum CharacterAttribute
{
    Health,
    Magic,
    Accuracy,
    Mood
}

public enum TargetType
{
    Self,
    Friend,
    Foe,
    PropaneAndPropaneAccessorySalesmen
}

// If you don't want to do one mega super class for status effects you could
// switch to using a StatusEffect abstract class or IStatusEffect interface
// and create child classes for each effect type. This can greatly improve
// organization for really big projects but for simplicity I took the
// mega-monster-too-big-to-easily-debug option.
public class StatusEffect
{
    EffectType effectType = EffectType.Damage;
    CharacterAttribute targetAttribute = CharacterAttribute.Health;
    TargetType targetType = TargetType.Foe;
    int duration = -1; // amount of turns this lasts. -1 if permanent
    float value; // amount of whatever this does, hp lost, accuracy down, etc.

    public bool DoEffect(Character sourceCharacter, Character targetCharacter)
    {
        bool successful = true;
        // put effect logic here, probably a switch statement
        return successful;
    }

    public bool StopEffect(Character sourceCharacter, Character targetCharacter)
    {
        bool successful = true;
        // put logic here to stop effect if possible
        return successful;
    }
}

public class PlayerMove
{
    public List<StatusEffect> effects = new List<StatusEffect>();
    public int chargeTurns = 0; // player should check if this many turns have passed before doing move.
    public int reapplyTurns = 0; // player should retrigger this effect for this many turns.

    public bool DoMove(Character player, Character target)
    {
        int successCount = 0;
        foreach (StatusEffect effect in effects)
        {
            successCount += effect.DoEffect(player, target) ? 1 : 0;
        }
        return successCount == effects.Count; // put whatever metric for a successful you want (all effects succeed or maybe just 1 is enough)
    }
}

```

--- XML Data File ---

```
<PlayerMoveDatabase>
    <!-- Define Moves Here -->
    <PlayerMove name="Pocket Sand" turnsToCharge="0" turnsToReapply="0">
        <Data>
            <Description>
                An attack worthy of Rusty Shackleford.
            </Description>
            <LearnedBy>
                <Player id="0" requiredLevel="10"/>
                <Player id="1" requiredLevel="10"/>
                <Player id="5" requiredLevel="0"/>
           </LearnedBy>
        </Data>
        <Effects>
            <StatusEffect target="foe" type="debuff" attribute="accuracy" dur="4">60</StatusEffect> <!-- lowers accuracy 60% -->
            <StatusEffect target="foe" type="damage" attribute="mood" dur="-1">20</StatusEffect> <!-- Makes targets 20 points angrier. -->
        </Effects>
    </PlayerMove>
</PlayerMoveDatabase>

```

# Answer
> 1 votes
What I would do is to separate the moves into "building blocks" of sorts, a bit like a scripting language like others proposed but simpler, more akin to opcodes - I think the actual Pokémon games use something similar. Each block will have a type and a set of parameters.

You could have "blocks" like "deal X damage of Y type", "apply status effect X for Y turns", "if X has status effect Y skip next Z actions".

To store these in a file, you would store something like this per move:

* Name
* Cost
* Conditions (if you have those)
* Blocks: amount of blocks
    + Block 1, type A, params X, Y
    + Block 2, type B, no params
    + Block 3, type C, params X

You would then need a base class (or interface) for such a block so when a move is executed, it just goes thru blocks 1 by 1 and calls their common Execute method.

When reading a move's file, each block will be fed into a factory class which will then reconstitute to the proper block type - I recommend using strings here because they're a lot more human readable and future proof.

So in your factory class you would basically have a huge switch with something like (pseudocode!)

```
case "damage_direct":
    return new DamageBlock(param 1, param 2)
case "status_effect":
    return new StatusEffectBlock(param 1, param 2)
etc......

```

You would obviously have to implement each of these in your code or in a new language's code, but the actual moves will be just the data you input.

So in short, cut up moves into blocks, implement each block, have a factory class that creates appropriate type of a block for its type.

---
Tags: game-mechanics, rpg, file-format
---


title: Player angle following camera

text:
# Question
Title: Player angle following camera
I'm creating a third-person game. I want the player-model to follow the rotation of the camera. I do that with this :

```
var camRotation = new Quaternion(cam.rotation.x, cam.rotation.y, cam.rotation.z, cam.rotation.w);
transform.rotation = camRotation;

```

The horizontal axis works fine, and the model turns with my camera, but the mode vertical axis also tilts up and down, which i do not want.

I've tried zeroing out the rotation.y and z, but this has some strange effects when I do.

# Answer
> 0 votes
Take the camera's forward direction, and flatten it into the plane of rotation you want.

Then form a quaternion looking in that direction.

```
var flatForward = camera transform.forward;
flatForward.y = 0;

transform.rotation = Quaternion.LookRotation{flatForward);

```

Here I assume you want the world horizontal plane, but we can also make this work with the plane of the ground under the player.

---
Tags: unity
---


# Question
Title: Opengl in 500 lines barycentric calculation question
https://github.com/ssloy/tinyrenderer/wiki/Lesson-2-Triangle-rasterization-and-back-face-culling

I cannot figure out how we go from uAB-vector + vAC-vector + PA-vector = 0 to the linear system with those subscripts x and y? Is there another way of explaining how we take three vectors, split them into x and y type vectors, and produce a cross-product that can be used to find the barycentric coords (u, v, w)?

Also, I am not sure why there is a division by the z component of the cross product in last line of the barycentric function. Maybe the answer to my first question will make this more obvious.

Below is a picture of the section of the tutorial where I am stuck. Link to full page is above.

# Answer
I think I understand now what is going on with the cross-product of the two vectors with three values. In the triangle ABC with point P given, lying somewhere inside or outside of the triangle, the author determines what the u, v, and 1-u-v values are (barycentric coordinates). They act like weights on the triangle to determine P, and if any are less than 0, the point is outside the triangle. This relies on three cross products. The cross product of two vectors divided by two gives us the area of a triangle and that is key for figuring out where P lies in the triangle. First and second vectors are calculated by determining the area of the sub-triangles for (AC and AP) and (AB and AP). Crossing vectors AB and vector AP, then another cross product for vector AC and vector AP. The third vector is for vector AB and vector AC. In the last line of the barycentric function you can see the three sub-area values divided by the total area of the triangle to get the barycentric values.

I think I had trouble with this because the variables u, and v, and x, y, z are used in different contexts in the code than what I am used to from what I see when googling barycentric coordinates. Also, other sources wouldn't put the three cross product calculations into one larger cross product. I just needed more time to unpackage this part of the tutorial. I still don't understand how the author of this tutorial explains what he is doing, but from looking at other sources and looking at his code, I believe I understand well enough how barycentric coordinates work to find u,v,w while having P, or the other way around.
> 0 votes

---
Tags: graphics, graphics-programming, rasterization, triangulation, barycentric-coordinates
---


# Question
Title: ScriptableObjects events execution order?
Given the code:

```
[CreateAssetMenu(fileName = "newGameManagerInstance", menuName = "Game/Game Manager Instance")]
public class GameManagerSO : ScriptableObject
{
    private GameManager instance;

    public GameManager Instance { get { return instance; } set { instance = value; } }

    private void Awake()
    {
        Debug.Log("1");
    }

    private void OnEnable()
    {
        Debug.Log("2");
    }

    private void OnDisable()
    {
        Debug.Log("3");
    }

    private void OnDestroy()
    {
        Debug.Log("4");
    }
}

```

I have two questions:

1. **Why the output in console when I enter play mode is "3" and then "2"?** Shouldn't `OnDisable` be executed after `OnEnable`?
2. I'm using this scriptable object to hold an object reference only (I don't have the need to serialize the object, it's just a handy way I found to pass that reference through scenes without committing to singletons); **can I code all initialization code for the object in `OnEnable` method?** Can I assume it will always execute before any `MonoBehaviour` read it?

Also

# Answer
A `ScriptableObject`'s `Awake` and `OnEnable` methods are called (in that order) as soon as the object is loaded.

This occurs when...

* Loading a scene that contains a reference to the object (including in the editor)
* Reloading recently referenced `ScriptableObjects` after a code change
* Clicking on the object in the Project window or reference selector widget

That means if you're testing a scene that contains a reference to this `ScriptableObject`, it's *already enabled* before you click the Play Mode button.

To match the event flow you observe in a built game, Unity starts-up the object from scratch when entering Play Mode. (Imagine you were using your `OnEnable` method to generate a random seed for a roguelike's procedural dungeon generation - if it didn't do this, you'd always get the same dungeon when testing in the editor)

But since the object was already started-up, in order to re-start it we have to shut it down first. That means calling `OnDisable` on it.

So the order of events you see when entering play mode is `OnDisable` -\> `OnEnable`, but only because we've narrowed our view too far. If we step back and look at the wider timeline we'll see something like this:

1. Launch Unity editor and open a scene referencing the object, or select the object in the inspector

`Awake` -\> `OnEnable`
2. Enter Play Mode

-\> `OnDisable` -\> `OnEnable`
3. Load a different scene that does not reference this object

-\> `OnDisable`

So it is true that `OnDisable` occurs after `OnEnable`. Specifically, the `OnDisable` in (2) occurs after the `OnEnable` in (1), just like the `OnDisable` in (3) follows the `OnEnable` in (2).

> Can I code all initialization code for the object in the `OnEnable` method? Can I assume it will always execute before any `MonoBehaviour` can read it?

Yes. That is exactly the purpose of these methods.
> 7 votes

---
Tags: unity, c#, scriptable-object
---


# Question
Title: How do I show only the level in monogame?
How do I remove the blue background shown here So that only the level is visible without making the sprites/map larger or the window smaller?

# Answer
> 2 votes
What you want is to dynamically scale the camera so you can only see the map. This can be done by passing a different projection matrix to the `SpriteBatch`:

```
var graphics = /* your GraphicsDeviceManager */;
var width = graphics.PreferredBackBufferWidth;
var height = graphics.PreferredBackBufferHeight;

var windowSize = new Vector2(width, height);
var gameSize = new Vector2(someWidth, someHeight); // e.g. your mapWidth and mapHeight
var matrix = Matrix.CreateScale(new Vector3(windowSize / gameSize, 1));

spriteBatch.Begin(
    // All of these need to be here :(
    SpriteSortMode.Deferred,
    samplerState: SamplerState.PointClamp,
    effect: null,
    blendState: null,
    rasterizerState: null,
    depthStencilState: null,
    // THIS!
    transformationMatrix: matrix,
);
// draw stuff
spriteBatch.End();

```

You can also multiply matrices to combine their effects:

```
// Just to show you the types :) gotta find the values yourself!
int windowWidth;
int windowHeight;
Vector2 position;
Vector2 windowSize = new Vector2(windowWidth, windowHeight);
Vector2 worldSize;

var translation = Matrix.CreateTranslation(new Vector3(-position, 0));
var scale = Matrix.CreateScale(new Vector3(windowSize / worldSize * Zoom, 1));
var centerTranslation = Matrix.CreateTranslation(windowWidth / 2, windowHeight / 2, 0);
var view = Matrix.CreateLookAt(position, Vector3.Forward, Vector3.Up)

// use matrix with SpriteBatch like my previous example
var matrix = translation * scale * centerTranslation * view;

```

The above code would scale the camera and center it on `position`.

# Answer
> 0 votes
The blue background technically is 'nothing', but it's blue by default. I assume that's so it works better for sprites with black outlines.

If you want to change the blue color to black, it's color is initialised in the `Draw()` method of game1. Either removing that color, or changing it to black will give you the black background.

Otherwise, you'll need to resize/set the window's width/height if you only want the level to be visible.

# Answer
> 0 votes
What you most likely want is that instead of iterating over the map to render it, you iterate over the viewport (sorta) which slides over your map.

Pad that out by a few tiles so that you can have smooth scrolling.

Keep track of the viewport position (you can pin that to your character, but the important part is that it is specifically the viewport you track and not something that mostly, but not always corresponds, like your character's X/Y).

Based on the viewport position, render tiles, however big your viewport is, offset by its position. For example, if your viewport's top left corner is at the top left corner of the map like in your screenshot, you then (probably with a for loop with X and Y) render all tiles starting from map's 0,0 and to the coordinates corresponding to the far right and bottom of your screen. For every tile you check if it's in the map first - if it is, you render whatever the tile is, otherwise (outside of bounds) - you render a border tile (like rocks or trees or water or whatever). Pokémon games used this technique and their border tile was actually made out of 2x2 regular ones to allow for tall trees and such - you can emulate this by keeping track whether you are drawing an odd or even row/column.

---
Tags: c#, xna, monogame, software-engineering
---


# Question
Title: Java Game: A* Algorithm (searching only cells in front of character)
Game Type: grid tile map that is turned based

Directions allowed: Left, Forward, Right (to reverse directions you must either use two lefts or two rights) - both left and right moves diagonal but change the face of the ship depending on original face)

Slots: Depending on ship size there are a certain number of slots for that particular ship for user to enter to allow the ship to move that many spots per turn (ie. 3 slots == 3 moves per turn)

Example:

Start Position: 2,2

Start face: North

Move Placed: Left

End Result: Position: 1,3 ; Face: West

---

Problem: algorithm uses all 8 tiles for path finding; but should only look for the tiles that are in front (depends on ship face)

Node class:

```
public class AStarNode {

    public Position position;
    public VesselFace face;
    public AStarNode parent;
    public double fCost, gCost, hCost;

    public AStarNode(Position position, VesselFace face, AStarNode parent, double gCost, double hCost) {
        this.position = position;
        this.face = face;
        this.parent = parent;
        this.gCost = gCost;
        this.hCost = hCost;
        this.fCost = this.gCost + this.hCost;
    }

}

```

Pathfinding calculation:

```
    private Comparator<AStarNode> nodeSorter = new Comparator<AStarNode>() {

        @Override
        public int compare(AStarNode n0, AStarNode n1) {
            if(n1.fCost < n0.fCost) return 1;
            if(n1.fCost > n0.fCost) return -1;
            return 0;
        }

    };

    public List<AStarNode> findPath(Position start, Position goal){
        List<AStarNode> openList = new ArrayList<AStarNode>();
        List<AStarNode> closedList = new ArrayList<AStarNode>();
        AStarNode current = new AStarNode(start, null, 0, start.distance(goal));
        openList.add(current);
        while(openList.size() > 0) {
            Collections.sort(openList, nodeSorter);
            current = openList.get(0);
            if(current.position.equals(goal)) {
                List<AStarNode> path = new ArrayList<AStarNode>();
                while(current.parent != null) {
                    path.add(current);
                    current = current.parent;
                }
                openList.clear();
                closedList.clear();
                return path;
            }
            openList.remove(current);
            closedList.add(current);
            for(int i = 0; i < 9; i++) {
                if (i == 4)continue;
                int x = current.position.getX();
                int y = current.position.getY();
                int xi = (i % 3) - 1;
                int yi = (i / 3) - 1;
                int at = context.getMap().getTile(x + xi, y + yi);
                if(at == 1 || at == 2) continue; // ignore rocks
                Position a = new Position(x + xi, y + yi);
                double gCost = current.gCost + current.position.distance(a);
                double hCost = a.distance(goal);
                AStarNode node = new AStarNode(a, current, gCost, hCost);
                if(positionInList(closedList, a) && gCost >= node.gCost) continue;
                if(!positionInList(openList, a) || gCost < node.gCost) openList.add(node);
            }
        }
        closedList.clear();
        return null;
    }

    private boolean positionInList(List<AStarNode> list, Position position) {
        for(AStarNode n : list) {
            if(n.position.equals(position)) return true;
        }
        return false;
    }

```

Implementation:

```
@Override
    public void calculateRoute() {
        Position destination = new Position(3,3); // replace with cluster
        if(this.equals(destination)) {
            return;
        }based
        path = context.getPlayerManager().findPath(this, destination);
        VesselFace face = getFace();
        if(path != null) {
            if(path.size() > 0) {
                int numberOfMoves = getVessel().has3Moves() ? 3 : 4;
                Position currentPosition = this.copy();
                for(int slot = 0; slot <= numberOfMoves; slot++) { //moves to enter
                    int positionIndex = (path.size() - 1) - (slot); //subtract slot to allow multiple moves
                    if(positionIndex < 0 || path.size() < slot) { // make sure it doesn't count too far
                        return;
                    }
                    Position pos = path.get(positionIndex).position;
                    Position left = MoveType.LEFT.getFinalPosition(currentPosition, face);
                    Position right = MoveType.RIGHT.getFinalPosition(currentPosition, face);
                    Position forward = MoveType.FORWARD.getFinalPosition(currentPosition, face);
                    if(left.equals(pos)) {
                        currentPosition.add(left.getX() - getX(), left.getY() - getY());
                        getMoves().setMove(slot, MoveType.LEFT);
                        switch(face) {
                            case NORTH:
                                face = VesselFace.WEST;
                                break;
                            case SOUTH:
                                face = VesselFace.EAST;
                                break;
                            case WEST:
                                face = VesselFace.SOUTH;
                                break;
                            case EAST:
                                face = VesselFace.NORTH;
                                break;
                        }
                    }else if(right.equals(pos)) {
                        currentPosition.add(right.getX() - getX(), right.getY() - getY());
                        getMoves().setMove(slot, MoveType.RIGHT);
                        switch(face) {
                            case NORTH:
                                face = VesselFace.EAST;
                                break;
                            case SOUTH:
                                face = VesselFace.WEST;
                                break;
                            case WEST:
                                face = VesselFace.NORTH;
                                break;
                            case EAST:
                                face = VesselFace.SOUTH;
                                break;
                        }
                    }else if(forward.equals(pos)){
                        currentPosition.add(forward.getX() - getX(), forward.getY() - getY());
                        getMoves().setMove(slot, MoveType.FORWARD);
                        switch(face) {
                            case NORTH:
                                face = VesselFace.NORTH;
                                break;
                            case SOUTH:
                                face = VesselFace.SOUTH;
                                break;
                            case WEST:
                                face = VesselFace.WEST;
                                break;
                            case EAST:
                                face = VesselFace.EAST;
                                break;
                        }
                    }
                }
            }
        }
    }

```

I use the switch statement and currentPosition.add() method so that when you place 3 moves for that particular turn; it knows where it should end up. Probably not best practice.

Statement that adds a move to the particular slot

```
getMoves().setMove(slot, MoveType.FORWARD);

```

Tiles that should be checked every turn based on ship face:

# Answer
> 0 votes
This is only a partial attempt, giving more details for the comment I made.

A\* searches over a graph of nodes that contain the "state" of the ship. In most tutorials (including mine, sorry) the state is only the position. But in your case I think the state is both the position and the facing direction. You need to know the facing direction to calculate the three positions in front of it. And then after the move, you'll have both a position and a new facing direction.

`Node` currently has a position; change it to have both `position` and `facing`. Here's a rough version of the `for(int i = 0; i < 9; i++)` loop to find the neighbors. Instead of going through 9 neighbors, each of the 4 directions will have exactly 3 neighbors. (Yes, there are 12, not 8! because it depends on which direction you were facing before)

```
    int x = current.position.getX();
    int y = current.position.getY();
    List<Node> neighbors = new ArrayList<Node>();
    switch (current.facing) {
        case NORTH:
            neighbors.add(new Node(new Position(x-1, y-1), WEST, …));
            neighbors.add(new Node(new Position(x, y-1), NORTH, …));
            neighbors.add(new Node(new Position(x+1, y-1), EAST, …));
            break;
        case EAST:
            neighbors.add(new Node(new Position(x+1, y-1), NORTH, …));
            neighbors.add(new Node(new Position(x+1, y), EAST, …));
            neighbors.add(new Node(new Position(x+1, y+1), SOUTH, …));
            break;
        case SOUTH:
            neighbors.add(new Node(new Position(x-1, y+1), WEST, …));
            neighbors.add(new Node(new Position(x, y+1), SOUTH, …));
            neighbors.add(new Node(new Position(x+1, y+1), EAST, …));
            break;
        case WEST:
            neighbors.add(new Node(new Position(x-1, y-1), NORTH, …));
            neighbors.add(new Node(new Position(x-1, y), WEST, …));
            neighbors.add(new Node(new Position(x-1, y+1), SOUTH, …));
            break;
    }

    /* for each of the nodes in the neighbors list, use the same
       logic you already have:
       1. check if it's a rock, and ignore if it is
       2. calculate g cost, store it in the node
       3. calculate h cost, store it in the node
       4. consider adding the node to openList
    */

```

---
Tags: java, path-finding, game-mechanics
---


# Question
Title: Object to reach height depending on its gravity and mass
A mathematician will probably think this was a silly question, but I'm not one and I'm in need of help :D

I'm working in Godot and with its `RigidBody2D`s (objects that have automated physics behaviour).
I want to create a spring of type `RigidBody2D` (the 'springiness' is not the only function of this object).

I'm at the point in code where this spring and another `RigidBody2D` collide so I have all information about the two bodies at the moment of collision.

My goal is to make any body that touches the spring reach a certain height (from the spring), and move by certain speed horizontally, as you can see in the picture

So, the information about both bodies I have is: position, velocity, gravity scale, mass, weight.
What I want to achieve is constant line of movement of any object (that may have different properties I mentioned above) by applying a certain force to the colliding object.
I can stop the body before applying new force to it, that is, at the time of collision.

Rotation, friction, absorption and similar properties don't need to be counted on as the game I'm making is a simple one. With this I'm trying to make a predictable movement for the player to count on. I also plan to disable collision briefly at the time of collision so that the colliding object can touch the spring from any angle and the collision result would be the same.

EDIT: Here's some of my testing

Stones have random mass from 1 to 50, in this case 45.748413, 41.445225, 24.259401 and 37.189552 and all have same gravity scale (GS), that is: 2. The slime has GS of 5 and mass of 1.

I bothered to make a seamless gif, so you can only see the two jumps here. Because the spring has circular shape they fall apart after i think 10 bounces.

From this test I see that mass doesn't matter when I use @Sergio's method, so that's a step foreward. Thanks @Sergio!

```
func _on_body_entered(body):
    if body is RigidBody2D:
        body.set_linear_velocity(Vector2(0, -50 * body.gravity_scale))

```

Now, even though they don't reach the same height, they have same timing - from first touching the spring (yeah, i know, it doesn't look like a spring), to falling back. So that's also a step foreward, but I still don't have an idea how to get them all to get to the same height.

# Answer
Try setting velocity of the object with `set_linear_velocity(vel)` on rigidbody, in that case object mass doesn't matter (unless you have strangely configured engine settings).
> 1 votes

---
Tags: 2d, physics, mathematics
---


# Question
Title: Moving non-local player from local player with Mirror Networking
i am using mirror networking which is based on UNet. I can move non local objects easly by assigning their authority to the local player and move them, but i can't assign/remove authority for other player's in the game, therefore i can't directly change their velocity. Any ideas how can i change other non local player's velocity from local player ?

# Answer
> 0 votes
Well, i don't know if this is the proper way but i have managed to solved this by sending message to server and server sending that message back to the clients. Clients can act (move in my case) upon that.

---
Tags: unity, multiplayer, unet, mirror-networking
---


# Question
Title: Get black bars with framebuffer and glViewport
I have read several tutorials and answers regarding framebuffers and glViewport, but I can't seem to resolve this issue I have. I want to take a low resolution framebuffer (400x225) and place it in a 1280x720 window at the position 100x100 (from bottom-left);

1. Load a 400x225 png image in a framebuffer with the same size

```
glGenFramebuffers(1, &m_framebuffer);
glBindFramebuffer(GL_FRAMEBUFFER, m_framebuffer);

glGenTextures(1, &m_textureColorbuffer);
glBindTexture(GL_TEXTURE_2D, m_textureColorbuffer);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 400, 225, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_textureColorbuffer, 0);

glGenRenderbuffers(1, &m_renderBuffer);
glBindRenderbuffer(GL_RENDERBUFFER, m_renderBuffer);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, screenW, screenH); stencil buffer.
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, m_renderBuffer);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
    printf("ERROR::FRAMEBUFFER:: Framebuffer is not complete!");
glBindFramebuffer(GL_FRAMEBUFFER, 0);

```
2. Generate the quad for the framebuffer:

```
    float quadVertices[] = { // vertex attributes for a quad that fills the entire screen in Normalized Device Coordinates.
    // positions   // texCoords
    -1.0f,  1.0f,  0.0f, 1.0f,
    -1.0f, -1.0f,  0.0f, 0.0f,
     1.0f, -1.0f,  1.0f, 0.0f,

    -1.0f,  1.0f,  0.0f, 1.0f,
     1.0f, -1.0f,  1.0f, 0.0f,
     1.0f,  1.0f,  1.0f, 1.0f
    };

    unsigned int quadVBO;
    glGenVertexArrays(1, &m_quadVAO);
    glGenBuffers(1, &quadVBO);
    glBindVertexArray(m_quadVAO);
    glBindBuffer(GL_ARRAY_BUFFER, quadVBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(quadVertices), &quadVertices, GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)(2 * sizeof(float)));

```
3. Create an orthographic projection matrix with the framebuffer size:

```
glm::mat4 bgProjection = glm::ortho(0.0f, static_cast<float>(400), static_cast<float>(225), 0.0f, -1.0f, 1.0f);

```
4. Set the `glViewport`:

```
glViewport(0, 0, 400, 225);

```
5. Bind the framebuffer

```
glBindFramebuffer(GL_FRAMEBUFFER, m_framebuffer);

```
6. Draw the sprite:

```
    shader->use();
    glm::mat4 model = glm::mat4(1.0f);
    model = glm::translate(model, glm::vec3(position, 0.0f));  // first translate (transformations are: scale happens first, then rotation, and then final translation happens; reversed order)

    model = glm::translate(model, glm::vec3(0.5f * size.x, 0.5f * size.y, 0.0f)); // move origin of rotation to center of quad
    model = glm::rotate(model, glm::radians(rotate), glm::vec3(0.0f, 0.0f, 1.0f)); // then rotate
    model = glm::translate(model, glm::vec3(-0.5f * size.x, -0.5f * size.y, 0.0f)); // move origin back

    model = glm::scale(model, glm::vec3(size, 1.0f)); // last scale

    shader->setMat4("model", model);
    shader->setMat4("projection", projection);

    shader->setVec3("Colour", color);

    glBindVertexArray(this->quadVAO);
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
    glBindVertexArray(0);

```
7. Unbind the framebuffer:

```
glBindFramebuffer(GL_FRAMEBUFFER, 0);

```
8. Finally render the framebuffer:

```
    shader.use();
    glBindVertexArray(m_quadVAO);
    glBindTexture(GL_TEXTURE_2D, m_textureColorbuffer); // use the color attachment texture as the texture of the quad plane
    glDrawArrays(GL_TRIANGLES, 0, 6);

```

---

This is the output I get when `glViewport(0, 0, 400, 225);`

But when I set the `glViewport(100, 100, 400, 225);` I get these black borders:

As you can see, the `glViewport` has moved to 100x100, but it has also created a 100x100 gap in the viewport. I have tried adjusting the projection matrix and framebuffer, but it seems like I am doing something incorrect with `glViewport`. Thank you.

# Answer
Your viewport is taken into account 2 times: before drawing the sprite and before rendering the framebuffer. I suggest keeping current `glViewport(0, 0, 400, 225);` as it is and adding one more `glViewport` right before drawing the framebuffer. In this seccond `glViewport` you can set up needed offset.
> 0 votes

---
Tags: opengl, c++, graphics-programming, frame-buffer
---


# Question
Title: How can I add a trigger variable negation in Animation machine's transition in Unity?
How can I add a trigger variable negation in Animation machine's transition in Unity?

I have two transitions.

First happens if `jump == false && grounded == true && duck == false && shoot`, second happens if `jump == false && grounded == true && duck == false && run == false`. I want to change the second to the `jump == false && grounded == true && duck == false && run == false && !shoot`, i.e. add the trigger variable negation in the end.

How can I achieve this?

First

Second

# Answer
Declare another Boolean and store the value of the trigger in that Boolean and then use it in the animator.
> 1 votes

---
Tags: unity, animation
---


# Question
Title: Java A* Algorithm: going to a specific tile that moves you to another tile
I have my AI to where it only looks at the 3 tiles in front of it for pathfinding which depends on the direction. However during pathfinding it may check a tile that is a action tile.

An action tile is one that moves you to another tile (changes your position).

The player ships can only go in 3 directions (Forward, Left, Right): the left and right turns move the ship diagonally on the grid.

Basic movement example:

Start:

* Ship position: (4,3)
* Face: North
* Move placed: Forward

End result:

* Ship position: (4,4)
* Face: North

---

Action movement example: (Action tile at location 4,4)

Start:

* Ship position: (4,3)
* Face: North
* Move placed: Forward

End result:

* Ship position: (4,5) // as shown moves player an extra space
* Face: North

---

The method to find the next position based on the action tile is given as `context.getMap().getNextActionTilePositionForTile(position, tile);`: tile - type of action tile; position - current position

How would I make my algorithm account for the action tiles that change position when calculating a path?

Pathfinding Class:

```
public class AStarSearch {

    private ServerContext context;
    private List<AStarNode> openList;
    private List<AStarNode> closedList;

    public AStarSearch(ServerContext context) {
        this.context = context;
    }

    private Comparator<AStarNode> nodeSorter = new Comparator<AStarNode>() {

        @Override
        public int compare(AStarNode n0, AStarNode n1) {
            if(n1.fCost < n0.fCost) return 1;
            if(n1.fCost > n0.fCost) return -1;
            return 0;
        }

    };

    public List<AStarNode> findPath(VesselFace startFace, Position start, Position goal){
        openList = new ArrayList<AStarNode>();
        closedList = new ArrayList<AStarNode>();
        List<AStarNode> neighbors = new ArrayList<AStarNode>();
        AStarNode current = new AStarNode(start, startFace, null, 0, start.distance(goal));
        openList.add(current);
        while(openList.size() > 0) {
            Collections.sort(openList, nodeSorter);
            current = openList.get(0);
            if(current.position.equals(goal)) {
                List<AStarNode> path = new ArrayList<AStarNode>();
                while(current.parent != null) {
                    path.add(current);
                    current = current.parent;
                }
                openList.clear();
                closedList.clear();
                return path;
            }
            openList.remove(current);
            closedList.add(current);

            int x = current.position.getX();
            int y = current.position.getY();
            switch (current.face) {
                case NORTH:
                    neighbors.add(new AStarNode(new Position(x-1, y+1), VesselFace.WEST,current,0,0));
                    neighbors.add(new AStarNode(new Position(x, y+1), VesselFace.NORTH,current,0,0));
                    neighbors.add(new AStarNode(new Position(x+1, y+1), VesselFace.EAST,current,0,0));
                    break;
                case EAST:
                    neighbors.add(new AStarNode(new Position(x+1, y+1), VesselFace.NORTH,current,0,0));
                    neighbors.add(new AStarNode(new Position(x+1, y), VesselFace.EAST,current,0,0));
                    neighbors.add(new AStarNode(new Position(x+1, y-1), VesselFace.SOUTH,current,0,0));
                    break;
                case SOUTH:
                    neighbors.add(new AStarNode(new Position(x-1, y-1), VesselFace.WEST,current,0,0));
                    neighbors.add(new AStarNode(new Position(x, y-1), VesselFace.SOUTH,current,0,0));
                    neighbors.add(new AStarNode(new Position(x+1, y-1), VesselFace.EAST,current,0,0));
                    break;
                case WEST:
                    neighbors.add(new AStarNode(new Position(x-1, y+1), VesselFace.NORTH,current,0,0));
                    neighbors.add(new AStarNode(new Position(x-1, y), VesselFace.WEST,current,0,0));
                    neighbors.add(new AStarNode(new Position(x-1, y-1), VesselFace.SOUTH,current,0,0));
                    break;
            }
            for(AStarNode neighborNode : neighbors) {
                int at = context.getMap().getTile(neighborNode.position.getX(), neighborNode.position.getY());
                if(at > 2){ // special action tiles
                    //TODO - allow ship to navigate through action tiles by looking ahead
//                  neighborNode.position = context.getMap().getNextActionTilePositionForTile(neighborNode.position, at);
                }
                if(at == 1 || at == 2) continue; // ignore rocks
                double gCost = current.gCost + current.position.distance(neighborNode.position);
                double hCost = neighborNode.position.distance(goal);
                AStarNode node = new AStarNode(neighborNode.position, neighborNode.face, current, gCost, hCost);
                if(positionInList(closedList, neighborNode.position) && gCost >= node.gCost) continue;
                if(!positionInList(openList, neighborNode.position) || gCost < node.gCost) openList.add(node);
            }
        }
        closedList.clear();
        return null;
    }

    private boolean positionInList(List<AStarNode> list, Position position) {
        for(AStarNode n : list) {
            if(n.position.equals(position)) return true;
        }
        return false;
    }

}

```

Node class:

public class AStarNode {

    public Position position;
    public VesselFace face;
    public AStarNode parent;
    public double fCost, gCost, hCost;

    public AStarNode(Position position, VesselFace face, AStarNode parent, double gCost, double hCost) {
        this.position = position;
        this.face = face;
        this.parent = parent;
        this.gCost = gCost;
        this.hCost = hCost;
        this.fCost = this.gCost + this.hCost;
    }

}
```
</code></pre>

# Answer
Your approach here:

```
for(AStarNode neighborNode : neighbors) {
    int at = context.getMap().getTile(neighborNode.position.getX(), neighborNode.position.getY());
    if(at > 2) { // special action tiles
        neighborNode.position = context.getMap().getNextActionTilePositionForTile(neighborNode.position, at);
    }

    // ...

```

...looks to me like the correct way to start, if action tiles only ever change the position of the ship, never its facing direction, and never care about the facing direction going in.

You could expand this to a function that takes a whole node and returns a whole node, returning the input unchanged for non-action tiles. That would let you also create actions that change the facing direction of the ship, or that have different outcomes depending on the direction you enter the tile.

The next item to check is your **cost function**. Should the bonus movement provided by the action tile be something you pay as part of the cost of the path? That's what your current code does:

```
double gCost = current.gCost + current.position.distance(neighborNode.position);

```

Here, if the action tile helps us out by rocketing us forward 10 extra spaces, it counts the same as if we had to take 10 steps to get there - because we're doing this after updating the neighbour position. So the pathfinder won't try to use this as a shortcut - it doesn't see it as saving anything.

If you want these action tiles to count as "free" movement or at least discounted, you can do something like this...

```
for(AStarNode neighborNode : neighbors) {
    // Compute the cost to get *to* the action tile.
    double costToReach = current.position.distance(neighborNode.position);

    int at = context.getMap().getTile(neighborNode.position.getX(), neighborNode.position.getY());

    // Get our early-out as early as we can.
    if(at == 1 || at == 2) continue; // ignore rocks
    if(at > 2){ // special action tiles
        neighborNode.position = context.getMap().getNextActionTilePositionForTile(neighborNode.position, at);

        // If your actions have a cost / pathfinding disincentive, add it here.
        costToReach += context.getMap().getCostOfActionTile(neighbourNode.position, at);
    }

    // Add the cost to reach and action cost here.
    double gCost = current.gCost + costToReach;

    // ...

```

Finally, we need to update your **heuristic** `hCost` computation. To be an "admissible" heuristic for A\*, our function needs to never *overestimate* the cost to reach the goal from a particular node.

For instance, if you pay a cost of 1 for orthogonal moves and a cost of \\$\sqrt 2\\$ for diagonals, your heuristic function could look something like this:

```
const double ORTHOGONAL_COST = 1.0;
const double DIAGONAL_COST = ORTHOGONAL_COST * Mathf.Sqrt(2.0);

double HeuristicDistance(AStarNode current, AStarNode goal) {
    int xDifference = Math.Abs(goal.position.x - current.position.x);
    int yDifference = Math.Abs(goal.position.y - current.position.y);

    int diagonal = Math.Min(xDifference, yDifference);
    int orthogonal = xDifference + yDifference - 2 * diagonal;

    return orthogonal * ORTHOGONAL_COST + diagonal * DIAGONAL_COST;
}

```

(This is a slightly tighter estimate than Euclidean distance because it accounts that your ship can only travel at angles of 0°, 45°, 90°..., so it can't take a direct 30° path to a goal - it has to zig somewhere. It also avoids an expensive square root as a bonus )

But if some tiles move you an extra space for free, then this could be an over-estimate!

Let's say we have to cross a distance of 8 tiles North, but fortunately enough, every second tile is an action that moves us another space North for free. That means we can complete the journey in 4 steps, half of what the heuristic estimates. That makes the heuristic *inadmissible*: using this heuristic could lead us to find paths more expensive than the cheapest one available.

For a simple action like this (and assuming you can't chain action tiles if one bonus move drops you onto another tile with a bonus move, and that a move in an orthogonal direction never gives you a bonus move diagonally), there's an easy fix: divide the heuristic estimate by two. That estimates that *every* tile you hit will take you double the distance - so it never over-estimates the cost of a path, no matter how many of these bonus move tiles are between here and there.

It does *under-estimate* the cost of many paths through areas of plain tiles, but that's not so bad. You can under-estimate the cost and still find the correct least-cost path, it just might take a little more searching because the algorithm is more optimistic about exploring detours (they might lead us to speedy action tile shortcuts!). It also under-estimates all such paths equally, so this doesn't introduce harmful biases that might lead the search astray.

The more complicated your action tile effects become, the more complicated your heuristic might get. But you can always simplify it, accepting a looser estimate (more searching) in favour of simpler computation (faster to process each node you search).

You can bound by the most extreme cases: if you have one action tile that transports you 10 units, divide your heuristic by 10. If you have wormhole tiles that teleport you across the map, assume the closest wormhole goes straight to the wormhole closest to your goal. See that linked answer for more discussion about picking heuristics.

Since you haven't told us the full set of what action tiles are allowed to do (and their costs), that's about all we can tell you for now. If you need help designing a heuristic for a particular set of actions, try posting a new question detailing the full movement and action tile design.
> 3 votes

---
Tags: java, game-design, path-finding
---


# Question
Title: Contact friction for overlapping rectangles
I am currently developing a top-down "tabletop simulator" where you are able to drag, drop and rotate playing cards on a table. The cards are able to overlap but do not interact as of yet. What I now want to implement is that whenever a card is being dragged over another card, that the bottom starts moving as a result of the dynamic friction between the overlapping cards. Right now I am thinking of two ways to approach this:

* Determine the area of overlap and use the center of mass of this area as the point where the friction force is acting on
* Rasterize the cards and determine the overlapping raster and let the friction force act on these points.

Unfortunately I expect these methods to be computationally demanding and was wondering if there are more efficient methods out there. So far I have not found any material referencing this type of problem. I assume it relates to determining the area of contact for 3D objects and applying a friction force.

# Answer
> 0 votes
Assuming that you won't have thousands of cards dragging each other simultaneously, I'd go with calculating overlap area.

This seems to be good starting point: https://stackoverflow.com/questions/44797713/calculate-the-area-of-intersection-of-two-rotated-rectangles-in-python

especially this answer https://stackoverflow.com/a/45268241/14953457

---
Tags: 2d, physics, geometry
---


title: Why Sorting process not happening?

text:
# Question
Title: Why Sorting process not happening?
I created 10000 array and assigned value 1 and 0 to it, then used gizmos to generate 10000 cubes. I paint it black or white depending on the assigned value.

After that I use the bubble sort algorithm to sort the cubes, expecting all black cubes pieled on the bottom but when I run it, the sorting does not happen and I can't spot where my mistake is.

```
    using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{
    int x;
    int y;
    int z;

    int[,] array1 = new int[100, 100];
    int temp;
    // Start is called before the first frame update
    void Start()
    {

        for (x = 0; x < 100; x++)

        {
            for (y = 0; y < 100; y++)
            {
                array1[x, y] = Random.Range(0, 2);

                Debug.Log(string.Format("{0},{1},{2}", x, y, array1[x, y]));

            }
        }
        OnDrawGizmos();

    }
    void OnDrawGizmos()
    {

        for (x = 0; x < 100; x++)
        {
            for (y = 0; y < 100; y++)
            {
                Vector2 pos1 = new Vector2(0 + x, 0 + y);
                Gizmos.DrawCube(pos1, transform.position);
                Gizmos.color = (array1[x, y] == 1) ? Color.black : Color.white;
            }
        }
    }

    void update()
    {
        for (z = 0; z < 100; z++)
        {
            for (x = 0; x < 100; x++)
            {
                for (y = 0; y < 100 - z; y++)
                {
                    if (array1[x, y] > array1[x, y + 1])
                        temp = array1[x, y];
                    array1[x + 1, y] = array1[x, y];
                    array1[x, y] = temp;

                }
            }
        }
        OnDrawGizmos();
    }
}

```

# Answer
> 3 votes
You have multiple obvious errors in this code.

1. You are setting the colour to draw the cube *after* you have drawn it. That will apply its colour to the *next* cube you draw, not the one you just drew. Set the colour before you draw the cube.
2. Your bubble sort is comparing the cube with its neighbour above (x, y + 1), but then copying its value to the neighbour beside (x + 1, y).
3. You're copying the value and overwriting what was in the neighbouring spot, not swapping it as a bubble sort should.
4. You're using bubble sort. You're spending 100 * 100 * 100 = 1 000 000 loop iterations on a problem that you can solve a hundred times faster. You're also repeating this sort every frame, when (if you'd done the sort correctly), the results won't change after you've done it once.
5. Or rather, you *would* be repeating the sort every frame, if you'd spelled `Update` correctly with an uppercase U. With a lowercase u, this method won't get called by the engine.
6. You're calling `OnDrawGizmos` manually. This is called by the engine - you should not call it yourself.
7. You're using member variables for things that can easily be temporaries.

You can do this much more efficiently:

```
using UnityEngine;

public class CubeSorter : MonoBehaviour
{
    bool[,] cubeIsBlack = new bool[100, 100];

    // Start is called before the first frame update
    void Start()
    {
        for (int x = 0; x < 100; x++)
        {
            for (int y = 0; y < 100; y++)
            {
                cubeIsBlack[x, y] = (Random.Range(0, 2) > 0);

                Debug.Log($"{x}, {y}, {cubeIsBlack[x, y]}");
            }
        }

        // We'll sort just once, not every frame.
        Sort();
    }

    // This sorts all the black cubes to the bottom of the column.
    // You can swap x & y to sort along rows instead.
    void Sort() {
        for (int x = 0; x < 100; x++) {
            // Count how many black cubes are in the column, and remove them.
            int blackCount = 0;
            for (int y = 0; y < 100; y++) {
                blackCount += cubeIsBlack[x, y] ? 1 : 0;
                cubeIsBlack[x, y] = false;
            }

            // Replace the black cubes all together at the bottom of the column.
            for (int y = 0; y < blackCount; y++) {
                cubeIsBlack[x, y] = true;
            }
        }
    }

    void OnDrawGizmos()
    {

        for (int x = 0; x < 100; x++)
        {
            for (int y = 0; y < 100; y++)
            {
                Vector2 position = new Vector2(x, y);
                Gizmos.color = cubeIsBlack[x, y] ? Color.black : Color.white;
                Gizmos.DrawCube(position, Vector3.One);
            }
        }
    }
}

```

# Answer
> 1 votes
I think it should be `Update()` instead of `update()`. Btw your code in update can be quite slow, so I'd rather run it once instead of every frame.

---
Tags: unity
---


# Question
Title: I'm failed to understanding array coordinate
I'm totally lost in understanding the arrays' coordinates. Below is the code I use to generate an one dimensional `array(10)`. I attached the console result and the generated result.

Please explain why `array[0]` (the cube at the bottom) does not match the gizmos color? It looks like `array[0]` actually refers to the 2nd cube (counting from bottom) while `array[10]` has gone missing from the display. The lowest cube looks like an extra generated cube which is irrelevant to the gizmos color.

```
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour

{
    int y;
    int[] array1 = new int[10];
    int temp;
    void Start()
    {

        for (y = 0; y < 10; y++)
            {
                array1[ y] = Random.Range(0, 2);

                Debug.Log(string.Format("{0},{1}", y, array1[ y]));

            }
    }

    void OnDrawGizmos()
    {

            for (y = 0; y < 10; y++)
            {
                Vector2 pos1 = new Vector2(0,  y );
                Gizmos.DrawCube(pos1,new Vector3(0.5f,0.5f,0.5f) );
                Gizmos.color = (array1[ y] == 1) ? Color.black : Color.white;
            }

    }
}

```

# Answer
> 1 votes
`Gizmos.color` sets the colour of the **next** cube to be drawn so you need to call it before `Gizmos.DrawCube`.

```
for (y = 0; y < 10; y++)
{
      Vector2 pos1 = new Vector2(0,  y);
      Gizmos.color = (array1[y] == 1) ? Color.black : Color.white;
      Gizmos.DrawCube(pos1,new Vector3(0.5f,0.5f,0.5f));
}

```

---
Tags: unity
---


# Question
Title: What is the name for the technique to use different palettes for different tiles of a screen?
I've found the keywords "subpalette" and "PPU palette", but they seem to be NES-specific. Though the idea of using a small palettes table and use 2 bits per pixel in an image (+ few bits reference to a palette per tile) looks like a cool retro compression method with low decompression drawbacks, so I guess it was used more widely.

Does this technique (of using different palettes for different blocks of pixels) have a name? Does it have a usage apart from NES?

# Answer
I think there is no single name for such technique but quite close are color mapping and color look-up tables. In such approach color from single channel texture can be remapped to final RGB color via 1-dimentional remapping texture. If you want to farther compress data and use 2 bits per pixel, then you can treat 8 bits of source texture pixel as 2x2 block of destination pixels. Why would you want to do so in your project? Do you actually want to compress data that much or just render retro-like graphics?
> 0 votes

---
Tags: textures, terminology, palette
---


# Question
Title: Unity - plain material colour darker than expected
I want to add to scene object without textures, only plain material, here is my import flow:

I create object in Sketch and export to SVG:

Then I import SVG to blender (Material do not use nodes, has plain color #96DFE4) and export it to FBX.

Then I import FBX to unity, as you can see material colour is much darker than SVG created:

The only Lighting source I use is Ambient with colour white and Intensity 0.

How to render object with exactly same material colour as SVG? I don't want any shadows etc, just plain color.

# Answer
Default imported materials are not exactly what you'd want to have there. Create new material with `Unlit/Texture` shader, add your texture to it and apply material to model.
> 2 votes

---
Tags: unity, materials, color
---


# Question
Title: What rotation needs to be applied to align mesh with expected axis of target?
I'm using LWJGL and JOML to create a 3D view of hexagons whose positions lie on a torus.

I have a number (NxM) hexagons, whose centres and normals I have calculated to be placed on the torus to completely cover the torus surface, but in the "game" engine I'm using I need to convert each item being rendered to a position and 3 rotation angles. I'm struggling to go from the 3 normals of the item to the 3 angles.

EDIT: Subsequent to posting this I have got some way in creating a matrix with the angles and converting to Euler angles, everything is now turned according to those angles, but they aren't facing directions I expect.

**The background**

I'm trying to create a visualisation of a Conway Game of Life using hexagons but instead of a simple plane, mapping each hexagon onto a Torus.

I've done the maths to calculate the centres of every hexagon, and the 3 direction unit vectors that they need to point to, when in their places around the torus.

For illustrative purposes, here's a view of the torus and 2 hexagons that would lie on it (not real, this is just me mocking it up in Blender)

What I'm struggling to understand is how to rotate the single mesh for a hexagon to its calculated normals at the position I want to place it.

i.e. How do I rotate some "unit" hexagon mesh (loaded from an OBJ file exported from Blender) to point in the direction of the 3 normals I've calculated they should be for each hexagon around the torus.

I have read a similar question here, but I'm struggling to get from the idea of the 4d rotation matrix to how I convert that to a Vector3f for rotations. I have the 3 vector normals, could create the 4d matrix, but I need a Vector3f (the rotations about x/y/z) to the mesh is drawn correctly.

My code is here. I'm following this guide for using LWJGL to create GameItems (my hexagons) and position/rotate them from a loaded obj file mesh, but as I say, I'm struggling to calculate the rotation Vector3f needed to point in the same direction I've calculated.

Here's the code section relevant to the problem at hand:

```
    val mesh = loadMesh("/conwayhex/models/simple-hexagon.obj")

    hexGrid.hexAxes().forEach { (location, axis) ->
        // axis is a Matrix3f with my 3 normals at the centre of the hexagon, e.g
        // cX  cY  cZ
        //  0  -1   0
        //  0   0  -1
        //  1   0   0

        val gameItem = GameItem(mesh)
        gameItem.position = location
        gameItem.scale = 0.2f // TODO: calculate this according to the torus size

        // what rotation do I give this?
        // How do I calculate it from the given axis for the current item?
        gameItem.rotation = Vector3f(30f, 30f, 30f)

        gameItems += gameItem
    }

```

The output of the application given the above static 30 degree rotation is:

Can anyone help me unserstand how I apply the rotation to my items so they align to what I've calculated they should be?

# Answer
I converted to using a quarternion to hold the value of the rotation which I could readily create from the normals, so the "fix" was for me to understand how rotations work better.

For the libraries I was using, the fix was simply:

```
val q = Quaternionf().setFromNormalized(axes)
gameItem.setRotation(q)

```

Here's an image from inside the torus better showing what I was trying to achieve initially (i.e. the placement and rotation of the hexagons onto the torus). This is from my application.

Next step is to animate these according to game of life rules.
> 1 votes

# Answer
3 direction unit vectors contain all the needed information for rotation. So there are 2 solutions:

1. Having calculated the centres and the 3 direction unit vectors you can build a matrix that would transform local space mesh to world space. `GameItem` would have single `Matrix4f` field instead of position, scale and rotation fields. You then just pass actual matrix to renderer.

This pseudocode should handle it:

```
Matrix4f Create(Vector3f eye, Vector3f forward, Vector3f up, float scale)
{
    Vector3f f = normalize(forward);
    Vector3f u = normalize(up);
    Vector3f s = normalize(cross(f, u));
    u = cross(s, f);

    s *= scale;
    u *= scale;
    f *= scale;

    Matrix4f result = new Matrix4f(1.0f);
    result.m00 = s.x;
    result.m10 = s.y;
    result.m20 = s.z;
    result.m01 = u.x;
    result.m11 = u.y;
    result.m21 = u.z;
    result.m02 = f.x;
    result.m12 = f.y;
    result.m22 = f.z;

    return translate(result, new Vector3f(-eye.x,-eye.y,-eye.z));
}

```
2. As an alternative you can decompose mentioned matrix into euler angles. In that case do not apply scale to it (or just pass 1.0):

How to extract euler angles from transformation matrix?
> 1 votes

---
Tags: opengl, 3d, mathematics, lwjgl, kotlin
---


# Question
Title: Should a game object class contain the information for how to render it?
If I have a class called Enemy:

```
// Simplified version
class Enemy
{
    float xPosition_;
    float yPosition_;
    int hp_;
};

```

Should this class also contain the information needed to render an enemy? Like in these two examples:

```
class Enemy
{
    float xPosition_;
    float yPosition_;
    int hp_;
    Model renderModel_;
};

```

```
class Enemy
{
public:
    void drawSelf(Window& window);
private:
    float xPosition_;
    float yPosition_;
    int hp_;
};

```

Or should the rendering information be inside a special renderEnemy function?

```
void renderEnemy(const Enemy& enemy)

```

Which is the better alternative?

# Answer
"Should" is a tricky question in games. Really, all that game code "should" do is play your game correctly and be comfortable enough to work with that your team can release the game on time. If you break every rule in the book and still release a good game, then the code's doing its job.

(It's not hard to find stories of absolutely monstrous code that managed to ship great games, even if it did everything the books say code "should" not do)

That said, there are some principles that dev teams have found *tend* to help make code easier to maintain and improve development speed and flexibility.

One is the **Single Responsibility Principle** (SRP).

It says that each type in your program should have just one job, which it owns entirely. This helps make it easier to know which file to edit when you want to make a change to a particular behaviour, because it lives in exactly one, clearly-defined place. It also makes it easier to track down bugs, because they're more often confined inside one clearly-identifiable file, rather than diffused across a messy pattern of interaction between many files.

A related idea is the **DRY Principle**, "Don't Repeat Yourself".

It says that you should write each bit of code once. If you find yourself copying and pasting code into multiple files, you're repeating yourself, and that opens up the potential for bugs. In the future, you'll often need to change this code, and you might make the change in one place, but miss updating one of the copies to match. That creates an inconsistency that can flare up into a bug you'd swear up and down you fixed, leading to a frustrating search for the case you missed.

In this situation, I'd argue your enemy's single responsibility is to be an enemy. It shouldn't contain any behaviours that are also needed by things that are *not* enemies, because then we'd be repeating ourselves.

* A position is also needed by player/neutral/friendly characters and by inanimate objects like barrels. Not the enemy's job.
* Health is also needed by other characters or destructible objects. Not the enemy's job.
* Rendering is needed by other characters, objects, background tiles, UI sprites, etc. Not the enemy's job.

One way that games commonly break up these different (and often shared) responsibilities is to use a component-based architecture.

In this approach, instead of deriving a new subtype of game object for each different kind of thing in your game, your base game object or entity becomes a kind of container for a list of components.

Each component type has a very narrow responsibility:

* A position or transform component stores and manipulates the object's position in the world, handling placement and movement
* A health component stores and manages its HP, handling damage and firing events on death
* A collider component stores the hitbox / collision representation for objects that should be solid or react to contact
* A sprite renderer component stores the sprite used to draw the object

...etc. Components (or the systems that process them) can reference one another - so the collider or sprite renderer components/systems can reference the transform component to know where to offset the collider in the world / draw the sprite on screen. A sprite animation component can reference the sprite renderer component and swap its sprite to match the current frame of animation. And so on.

This frees up your enemy behaviour components to not have to re-invent the wheel by implementing their own positioning/rendering boilerplate, but also without locking them into a strict place in an inheritance hierarchy where that functionality is applied to all descendants (whether they need it or not).

In fact you could even break "enemy" itself into multiple components like...

* A faction component that establishes that this entity is hostile to the player
* A patrol behaviour component that handles its idle movement pattern
* A vision/awareness component that detects players in a vision cone or radius
* A pursuit behaviour component that chases a target once spotted (disabling the patrol behaviour component)

Now each individual component type is very simple and easy to understand in isolation. Bugs are less common because we're working with smaller, simpler files, and it's easier to track them down because they're usually restricted to a single component file. It's also easier to collaborate with a larger team, because you'll less often be fighting over the same files and sorting out merge conflicts when making unrelated changes.

You don't have to re-implement things like HP again and again for players and enemies and destructibles, they can all re-use the same health component - even if they sit in vastly different parts of your game's taxonomy of objects (which can be a challenge to accomplish with inheritance).

And better yet, you can often create new entity types in your game without writing new code, just kitbashing together different combinations of the components you've already built, and populating them with different parameters. This is an especially big advantage if you're working in a bigger team that might include non-programmers, like level designers and game designers. Giving them these reusable building blocks of behaviour they can snap-together in new combinations frees them to build unique gameplay scenarios independently, without needing to request new work from the programming team for each and every variant or experiment.

You might find those principles and the component-based approach help you, or you might find they don't, so I hesitate to call them a "should" obligation. But these are the reasons why I wouldn't recommend tying up rendering in an enemy class.
> 1 votes

# Answer
It really depends on what type of architecture you are trying to mimic.

In ECS, you would have a component for model information that you would associate with any entity that needs it and a system that handles rendering those models.

For a more manager style system, which is what I used in my game engine, I have a model manager class which loads, stores, and unloads model class objects using function calls. Anything that needs a model associated with it gets a pointer to the model class which can be acquired with a GetModel function in the model manager class object. I hadn't optimized my rendering setup yet, but my objects were grouped into 1kmx1km cells which contained all the instances of objects, and the cells had their own render function.
> 0 votes

---
Tags: c++, rendering, oop
---


# Question
Title: In unity, making a navmesh for a tiny planet?
I'm trying to build a scene in a small planet, and baking will always give me the result on the half top of the planet. But what I want is to create a navmesh all around the small planet.

I am wondering if there is a way to convert a mesh that I well built in blender, to be a navmesh in Unity. That means using the mesh totally without baking. Or, if there is some other ways to create navmesh for my poor planet.

# Answer
> 2 votes
Here is a thread on doing just what you're asking about: https://forum.unity.com/threads/new-navmesh-how-to-create-rotated-localnavmeshbuilder-solved.476489/

This might require you to break your planet into pieces based on angle thresholds and link them together. You could possibly get away with 3 - one for the north pole, one for south, and one for equatorial. You could also hide separate meshes and only display the single planet mesh and the NavMesh will still be valid.

Take a look at the Unity NavMesh Extensions here: https://github.com/Unity-Technologies/NavMeshComponents

I think those extensions are required for the classes they are talking about and to link nav meshes together. I've used them to generate meshes at runtime in the past.

Edit to enumerate what is in the Unity thread from the Unity employee adriant:

> Hi! You will need to change the code to set the rotation of the NavMeshData object before building the NavMesh. This means adding something like this

```
m_NavMesh.rotation = Quaternion.AngleAxis(41, Vector3.forward);

```

> any time before NavMeshBuilder.UpdateNavMeshDataAsync(...) or NavMeshBuilder.UpdateNavMeshData(...) are called.

> The NavMeshSurface takes the rotation from its game object when the NavMesh \>gets built with this call

```
    var data = NavMeshBuilder.BuildNavMeshData(GetBuildSettings(), sources, sourcesBounds, transform.position, transform.rotation);

```

> This effectively creates a NavMeshData object, sets its position and \>up-\>vector orientation and then calls UpdateNavMeshData(...).
>
> Please see also the documentation pages for NavMeshData and \>NavMeshBuilder.BuildNavMeshData .
>
> When the NavMeshData needs to be aligned with the originating geometry then it has to be added to the NavMesh system with the same position & rotation with which it was built. Try this in your code:

```
if (m_NavMesh.rotation != transform.rotation)
    {
        m_NavMesh.rotation = transform.rotation; // I've added this line
        m_Instance.Remove();
        m_Instance = NavMesh.AddNavMeshData(m_NavMesh, m_NavMesh.position, m_NavMesh.rotation);
    }

```

> You get freedom for where to place your NavMesh data in the world. Multiple instances of the same NavMeshData can be used by the NavMesh system in various locations and with whichever orientation you need. As a side note, changing the position or rotation of the NavMeshData will trigger a full build of that nav mesh, unlike just moving/changing the bounds which doesn't recompute the nav mesh in unchanged areas.
>
> Please keep in mind though that the bounds passed to UpdateNavMeshData() are local to m\_NavMesh. This means that for the LocalNavMeshBuilder class at least the bounds' center needs to be adjusted. Try adding this in QuantizedBounds():

```
if (m_NavMesh)
    {
        var nmMatrix = Matrix4x4.TRS(m_NavMesh.position, m_NavMesh.rotation, Vector3.one);
        center = nmMatrix.inverse.MultiplyPoint(center);   // from world to local space
    }

```

> And make sure to adjust the gizmos' transform accordingly in OnDrawGizmosSelected() with:

```
Gizmos.matrix = Matrix4x4.TRS(m_NavMesh.position, m_NavMesh.rotation, Vector3.one);

```

---
Tags: unity, navmesh
---


# Question
Title: Prevent UI Button focus loss when clicking somewhere else
I have a set of UI buttons in a canvas. The user is be able to navigate the buttons through both mouse clicks and arrow key movements. However, clicking anywhere not on the buttons results in focus being lost from the buttons, making arrow key navigation no longer work. Is there a way to solve this?

# Answer
> 1 votes
Focus is handled by the EventSystem component. While you can’t really do much with that, you *can* easily replace the existing EventSystem component with your own implementation based on their code. You can find it right here:

https://bitbucket.org/Unity-Technologies/ui/src/0651862509331da4e85f519de88c99d0529493a5/UnityEngine.UI/EventSystem/EventSystem.cs?at=2018.3%2Fstaging&fileviewer=file-view-default

So the first step is to take that file and put it in your project, changing the file name and class name to something like `MyEventSystem`. Also change the `AddComponentEntry` attribute argument to something like “Event/My Event System”

Then update the `SetSelectedGameObject` method to return early if the `selected` argument is `null`.

Finally, find the EventSystem GameObject in the scene and replace the EventSystem component on it with your own implementation.

**Edit:**

Turns out making your own EventSystem won’t work. Instead, you’ll have to create a InputModule implementation. Here’s one:

https://bitbucket.org/Unity-Technologies/ui/src/0651862509331da4e85f519de88c99d0529493a5/UnityEngine.UI/EventSystem/InputModules/PointerInputModule.cs?at=2018.3%2Fstaging&fileviewer=file-view-default

Look into changing `DeselectIfSelectionChanged`

# Answer
> 3 votes
What I did to solve this problem was store the last selected object in a gameobject variable and reset it back to that if `Eventsystem.current.currentSelectedGameObject` returned `null`:

```
GameObject lastSelected;

private void Update()
{
    if(EventSystem.current.currentSelectedGameObject == null)
    {
        if (lastSelected && lastSelected.gameObject.activeSelf && lastSelected.GetComponent<Button>() != null && lastSelected.GetComponent<Button>().interactable)
        {
            EventSystem.current.SetSelectedGameObject(lastSelected);
        }
    }
    else
    {
        lastSelected = EventSystem.current.currentSelectedGameObject;
    }
}

```

---
Tags: unity
---


# Question
Title: Unsure where to right click to delete Unreal C++ class
Trying to delete a c++ class (this should **not** be this difficult!) and I have deleted the .h, .cpp, and binaries. Next everybody says "now, right click on your .uproject file and select Generate Visual Studio files." *Where* do i right click it? I can't find the file in Visual Studio, and it doesn't give the option to generate the files in my file browser. Sorry about the noob question, but I 've google searched to no avail. thnx.

# Answer
> 1 votes
It shouldn't be this difficult but unfortunately, it is.

You right click the .UProject file in your File Explorer.

It's also recommended that you delete the Intermediate folder as well.

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


# Question
Title: Why does Ads (Rewarded Video or Intersititals) in games skips when you press home and tap on games icon in Android?
I have stumbled upon an issue wherein Android when I play **rewarded video** or any interstitial and do following steps:

1. In the middle of a video Ad I press the home button
2. Resume back from background tray the ad plays where I left off.

BUT if,

1. In the middle of a video Ad I press the home button
2. Tap on the game **icon** to resume back then it skips the ad and game continues without getting any reward.

I thought this might be anything specific to my code but then I tried playing many other games including **Mr. Bullet**, **Hospital Inc**, **Idle LumberJack**, **Super Salon** and the list goes on and all had the same issue.

Is this some android thing? As for iOS, this doesn't happen. I would like to have some information on why this happens and can we prevent it from happening. I am using Unity 3D for my game development and AppLovin MAX for ads.

# Answer
> 0 votes
I can only begin to guess as to the cause, but I think what you’re really looking for is a solution. I would recommend going through AppLovin’s support guide, which recommends enabling verbose logging to see if there’s anything amiss:

https://monetization-support.applovin.com/hc/en-us/articles/236114328-How-do-I-enable-verbose-logging-in-AppLovin-s-SDK-

> Unity (MAX Plugin)
>
> If you are on the AppLovin MAX Unity Plugin, verbose logging can be toggled directly on the MaxSdk class.

```
MaxSdk.SetVerboseLogging(true);

```

Then check your logcat to find out what’s going on.

They also have a contact form:

https://monetization-support.applovin.com/hc/en-us/requests/new

As for the cause, my first guess is maybe the icon is bound specifically to launch the Unity activity, not whatever activity was in the foreground.

---
Tags: android, unity-ads
---


# Question
Title: Godot / GDscript label text not updating every frame like intended
I am very new to Godot and coding in general, so I apologize in advance for any simple mistakes. I am trying to have my text display the variable `ammodisplay` on my object `Marine`. When I launch the game, the text sets to 7 (the correct value) but as I play the game and the variable changes, the text does not update with it. Any insight as to how I can fix this? Thanks in advance!

```
extends Label

var NODE = load("Marine.tscn")
var ammo = NODE.instance()
var ammod = ammo.ammodisplay

func _process(delta):
    text = (str(ammod))

```

# Answer
> 1 votes
## Don't copy the value

In the code you are taking a copy of the value `ammo` and store it in the variable `ammod`:

```
extends Label

var NODE = load("Marine.tscn")
var ammo = NODE.instance()
var ammod = ammo.ammodisplay

```

Then you display the copy, which does not get updated.

```
func _process(delta):
    text = (str(ammod))

```

Read the value again instead:

```
func _process(delta):
    text = (str(ammo.ammodisplay))

```

---

## Getting the correct node

Besides, it is unclear from the example if you actually want to instantiate a new instance with this script, or you want to access one you have in the scene tree. For example, your declarations could look like this:

```
extends Label

onready var ammo = $Marine;

```

Which assumes you have a node `Marine` as child of the `Label` in the scene tree. The type of `ammo` will be that of the node `Marine`. The code above is roughly equivalent to (except the version below has worst IDE integration, and worse typing information):

```
extends Label

onready var ammo = get_node("Marine");

```

The type of `ammo` will be `Node`.

In case you are not familiar with `onready`, let me tell you that the code above is roughly equivalent to (except the version below has typing information lost):

```
extends Label

var ammo = null;

func _ready():
    ammo = get_node("Marine");

```

The type of `ammo` will be `Variant`.

It is important to get the node in ready or afterwards because initialization of the node happens before it is added to the scene tree (and thus can't get nodes from it).

---

Chances are that `Marine` should not be a child of the `Label`. For that situation I suggest to export a node path.

By exporting a node path you can specify in the editor when the node you want to access. For example:

```
extends Label

export(NodePath) var ammo_path;
onready var ammo = get_node(ammo_path);

```

Then in the inspector panel you will see a new property "Ammo Path" (Godot auto capitalizes the name) where you can specify where in the scene tree the node you want to access is.

# Answer
> 0 votes
I'm new to GDscript myself, but I suspect that it should be `self.text = ...`, otherwise you just create a local variable that is not used.

# Answer
> 0 votes
It seems that you retrieve an new instance of marine, rather than accessing the one you would like to change the value on.

Godot uses scene trees and the `Marine.tscn` should be a child of a another scene.

For example let's say you have a world scene with a textlabel called `Speed` and you want to update the text.

Then you would access the speed textlabel in your world scene via `getNode()`

```
get_node("Speed").text = "Speed: %s" % getSpeed()

```

---
Tags: godot, gdscript
---