# Question
Title: How to make obstacles spawn randomly but still leave a way for player to pass?
I'm trying to make a game like Crossy Road:

In this game, you control the character(the frog in this case) to go across the streets, and you have to prevent your character from being hit by a car.

There are also "footpaths". On the footpaths there are trees act as stationary obstacles and you can't go through them.

I tried to make a similar game but I have a problem:

The obstacles prevent the player from getting further. What can I do to make sure that the player always has at least one way to pass through?

# Answer
For the footpaths, you want to ensure there's always at least one gap / clearing all the way through to the far side. Some ways you can do this:

1. **Guess-and-Check**

Generate the trees/rocks randomly, then try to flood-fill the passable space from the near side. If your flood fill reaches the far side, then there's at least one passable route. If not...

* Try again from scratch! This approach is easy, but relies on your randomization routine already having a good probability of making a passable result by luck. If passable results are rare, you might spend a lot of time re-generating only to fail.
    * Fix it: carve out one or more solution paths somewhere, either picking a random column to bulldoze to passable space, or selectively deleting an obstacle (eg at the thinnest point)
2. **Solution First**

Start by picking one or more solution paths - say taking a few biased random walks from the passable tiles from the previous footpath, until they reach all the way to the far side of this footpath. Mark each tile these random paths touch as "reserved".

Now, randomly fill some/all of the non-reserved tiles with obstacles. You're guaranteed that your reserved solutions still work, possibly in addition to some other solutions if you've left gaps in the non-reserved tiles.
3. **Remix**

Pre-author a bunch of "chunks" of footpath in various thicknesses with a solvable route through it.

When generating a new footpath, randomly select from these chunks and snap them end-to-end like LEGO bricks.

This approach gives you a lot of stylistic control, curating arrangements of obstacles/powerups that look good to you, but the repetition can be perceptible to players.

For the lanes of traffic/logs, it may suffice to ensure that there is *eventually* a way through:

* Set the traffic generation in each lane to produce at least some gaps (say, add a randomized cooldown between obstacle spawning in a single lane, or deal obstacles from a "deck" with several "gap" cards in it)
* Set adjacent lanes to travel in opposite directions or at different speeds, so that even if sometimes an obstacle in one lane blocks a gap in another, it won't always do so.

This way you'll get gaps stochastically, and you can tune the spawning frequencies/speeds to control how often they arise.

But the other approaches above work too, if you add time as a variable. For instance, a "remix" strategy could use pre-authored blocks of cars in adjacent lanes that move at the same speed. Or a "solution first" approach could periodically plan a path for the player between adjacent footpaths, recording the time window they'll be in each tile, then veto random spawning of any obstacle that's projected to overlap that tile in that time window, based on the lane's speed. Try the simple/stochastic route first though, and see if you still have unsolvable situations cropping up too often.
> 4 votes

# Answer
You could generate a random path or a few paths, and reserve this space. When you are placing objects, make sure they avoid the path area.
> 3 votes

# Answer
Additionally to what DMGregory said already you can check for potential paths after each obstacle generation.

You generate potential random position for obstacle and test if it's possible to find any way through.

If `Yes` \- you spawn obstacle at this position.

If `No` \- ignore this position and generate a new one.
> 1 votes

---
Tags: algorithm, game-mechanics, procedural-generation
---


title: How to implement this XP formula?

text:
# Question
Title: How to implement this XP formula?
I found this response but the thread is closed:

https://gamedev.stackexchange.com/a/13639

level = constant * sqrt(XP)

I seem unable to properly get current level, this is how I tried to do it, and everything seems to work except the actual current level for some reason:

```
xpConstant = 0.05;
currentXp = 80;
-- with those two values, level 1 should require 20 xp:
-- xp = 1^2 / xpConstant;
-- with 80 xp, the player should be level 2, 2^2 / 0.05 = 80

-- this is 0.47 but it should be 2?
currentLevel = xpConstant * math.sqrt( currentXp );

-- and to retrieve xp until next level, this does seem to work:
nextLevel = currentLevel + 1;
XPUntilNextLevel = nextLevel ^2 / xpConstant;
XPUntilNextLevel = XPUntilNextLevel - currentXp;

```

so for some reason the currentLevel variable doesn't give 2 as expected,

# Answer
You need to multiply by the xpConstant, then get the square root. You can see this by rearranging your equation:

$$xp = level^2 / xpConstant$$ $$xp \cdot xpConstant = level^2$$ $$\sqrt{xp \cdot xpConstant} = level$$
> 1 votes

# Answer
As Bálint says, your two formulae do not agree with one another:

$$level = constant \cdot \sqrt {xp} \\ xp = \frac {level^2} {constant}$$

If you choose to keep the xp formula as-is, then you need to change the level formula as shown in Bálint's answer.

Or, if you want to keep the level formula as it was in the original Q&A you're referencing, then you need to correctly solve for xp, by inverting each operation in sequence from the outside in:

$$\begin{align} level &= constant \cdot \sqrt {xp}\\ \frac {level} {constant} &= \sqrt {xp}\\ \frac {level^2} {constant^2} &= xp\\ \end{align}$$

So with constant = 0.05 your XP progression per level looks like:

```
 1:    400
 2:  1 600
 3:  3 600
 4:  6 400
 5: 10 000

```
> 1 votes

---
Tags: mathematics, lua
---


# Question
Title: Why would I receive a NullReferenceException when the object is clearly set, and still works?
I am getting the exception "NullReferenceException: Object reference not set to an instance of an object" while changing text of a user interface text field, even though the text changes successfully, as you can see in the image. It still gives me a null reference exception; if it was not set, then how can it change the text?

I don't know what is happening, here. I have re-imported the project, but the problem stays.

```
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class Menu : MonoBehaviour
{

    public Text headingaccuracy;
    public Text magneticheading;
    public Text rawvector;
    public Text trueheading;

    private void Start()
    {
        headingaccuracy.text = "Heading Accuracy  ";
    }
}

```

# Answer
I have ran into this problem more often than I care to remember. First and foremost, there is *no* `NullReferenceException` in the script associated with *"emptyTest"*. We know that for two reasons:

1. We can clearly see that the reference has been assigned via the Inspector
2. We only have one line of code, and as you confirm, it *is* successfully running. A `NullReferenceException` infers that the line *did not* successfully run, and if there was a null reference, we certainly would not be able to edit a value with in that referenced class.

The solution is simple. You have *another* instance of `Menu` running, somewhere. I would speculate that it is attached to an object in your canvas, as the working model you show us appears to be a *test game object*. This happens to me all the time.

The easiest solution is to try `Debug.Log(gameObject.name);` before the first line of your `Start()` method. Before the instance hits a `NullReferenceException`, it will output the name of the game object. This will tell you exactly what game object has the non-setup version of `Menu`, instead of having to procedurally check each one.

---

You could also change your logic to anticipate such problems, in the future. The common approach is to simply check if a reference is valid, before using it. An alternate is to simply use a try..catch statement in anticipation of the specific error.

```
// The simple "check if null, first" approach
if(headingaccuracy != null)
{
    headingaccuracy.text = "Heading Accuracy  ";
}
else
{
    Debug.Log("WARNING: headingaccuracy not set up on " + gameObject.name);
}

/* -------------------------------------------------------------------- */

// The more complicated "try/catch" approach (make sure your using the System namespace)
try
{
    headingaccuracy.text = "Heading Accuracy  ";
}
catch(NullReferenceException exception) // using an error type, like this, requires System.
{
    // we have hit a NullReferenceException, so apply this logic, instead.
    Debug.Log("WARNING: headingaccuracy not set up on " + gameObject.name);
}

```
> 5 votes

# Answer
The absolute most common cause of this is that there is some other GameObject running this script that shouldn't be running it. Check each of your GameObjects and make sure the script that's giving you problems isn't attached if it's not supposed to be.
> 0 votes

---
Tags: unity, gui, text
---


# Question
Title: An algorithm to make one object follow another on a 2D grid
I am using Greenfoot, but this can apply to pretty much any 2D engine.

So my question is a basic one that I somehow couldn't find an answer to already. Basically, if I have an enemy and the player, how can I make the enemy follow them? The player can move in all 4 directions, and the enemy can move in any direction, whichever one is faster. It would be done using a method that accepts an integer for speed, and an in-game object to move towards (an Actor in Greenfoot). It shouldn't simply teleport there but move closer by however much the value for speed is. And this would have to be done without rotating the image of the enemy.

This is in Java but if the answer you provide is in pseudo-code or a similar language (such as c++ or c#) I can still use it.

# Answer
> 1 votes
Here is a pretty simple and general method that I think satisfies the conditions.

Let's call the player position `(x_p, y_p)` and the enemy position `(x_e, y_e)`.

Next, we'll calculate the direction that would move the enemy onto the player. This is `(x_e - x_p, y_e - y_p)`. We can call this `(x_d, y_d)` where the `d` is for distance.

The next thing we want to do is to normalise the distance. This will make the length of the distance vector exactly equal to 1. This will also give **non-integer values** which may or may not be suitable for your grid.

You want to use the Pythagoras theorem to find the length of the vector, and divide by the length. So let's call the normal vector `(x_n, y_n)` which is `(x_d / D, y_d / D)` where `D = sqrt(x_d * x_d + y_d * y_d)`.

Now what we have is a direction from the enemy to the player, and the length of this direction is exactly 1 unit whichever way it is pointing. We can easily adjust a speed factor here by updating the enemy with `(x_n * speed, y_n * speed)`. This will move the enemy in exactly `speed` units toward the player.

---
Tags: 2d, mathematics, path-finding, greenfoot-engine
---


# Question
Title: How to use OOP to handle different requirements
I've been trying to make games for a while now, but even when making a very simple one, I've always run into a problem - Because different subclasses have different functionality, therefore needing different requirements, I can't properly use OOP concepts in my code.

For example, I have a Projectile class in my code, which serves as a superclass for a Bullet class and Missile class. All of my projectiles are stored in a List, and I would like to be able to loop through the List and update all projectiles. However, I would like the Missiles class to follow the player, which means I need to supply the player's position to update it.

I could also store a pointer to the player in the Missile class, but this quickly becomes messy, and since the game is very simple, I wouldn't want to use ECS's. What solutions are available for this?

# Answer
> 3 votes
Fundamentally, if you have implementations of any interface (`Projectile` in this case) that need data that isn't available via that interface to operate then your solutions are:

1. Modify the interface such that it can supply the data.
2. Give the data directly to the subclass implementation.
3. Accept that perhaps some of the implementations are can longer correctly be considered implementors of that interface, and treat them separately.

The first option tends to scale poorly and lead to very poor OO designs, because over time the interface or base class becomes bloated with various pieces of data that are only actually relevant to a subset of implementations or subclasses.

The second option is generally preferable (you could argue that the third is as well, but that often involves a more significant set of changes). Alexandre's answer provides possible implementations of both, but you yourself provided (what I think is) a better one:

> I could also store a pointer to the player in the Missile class,

I'd argue this is better from an OO design perspective (because it doesn't push subtype-specific behavior up into a base type), and also better from a more abstract design perspective (because it doesn't require reliance on global state).

You could generalize this to storing a reference to some kind of `HasPosition` type of interface, so your missiles can track anything.

You note that

> this quickly becomes messy

but I'd challenge that argument, on the basis of the above points. Also on the basis that where I *can* see some eventual complexity here, since you describe your game as "simple" I'm not convinced it would come up.

I will concede that you've traded a *type design problem* for a *lifetime design problem* in going this route, however: now you have to either ensure that the target *always* outlives the missile (not practical in most game contexts) or you have a dangling reference.

However you can address that by providing the reference via something *other than* a vanilla, language-level pointer or reference. Using a handle or similar "weak" reference that allows you to determine if the referred-to thing is still alive and valid allows you to deal with the lifetime problem by first checking for validity in the missile's `Update` function. If the target reference is still valid, track it. Otherwise let the missile continue along whatever its previous trajectory was, or maybe try to acquire a new target.

# Answer
> 2 votes
You don't necessarily need to *supply* the position of the player to the `Missile`.

You can make the position of the player available to everyone, and let your game objects access it.

For instance (pseudo-code):

```
GameManagerSingleton
  static getInstance()

  getPlayer()

Missile : Projectile
  update():
    player = GameManagerSingleton.getInstance().getPlayer()

    position = bla bla bla player.getPosition()

```

Yes, a singleton. It will work, but this, too, can get messy and grow out of control.

You could pass the player object to the Update function, without keeping a reference to it (pseudo-code):

```
Projectile
  update( PlayerRef )

Missile : Projectile
  update( PlayerRef ):
    position = bla bla bla PlayerRef.getPosition()

```

Of course, your `Bullet` does not care, but that's ok. Note that this is a slippery slope, though, as new subclasses need new objects, you'll have more and more stuff to pass through the Update function parameters.

You could also go hybrid, and pass your game manager instance to your update function, so that it goes get whatever it needs :)

In my experience, though, I kind of have concluded that inheritance can be a pain to work with - nothing is really generic and reusable. And I would suggest you find a way to plug in a component based architecture into it *because* it is a small project. That could be a great practice run for your *next* project.

---
Tags: oop
---


# Question
Title: Particle Effects move awkwardly as the camera approaches them
Particle effects seem to move rather awkwardly when partly out of camera bounds. When scaling up particle effects to the point where they fill most of the screen they don't appear static anymore.

Video of the effect

I'm using particles to simulate clouds. Is there a way to fix this without scaling down the individual clouds?

# Answer
> 4 votes
This is due to the Max Particle Size property inside the Particle System Renderer component.

This setting ensures no billboarded particle ever takes up more than a configurable fraction of the viewport.

The reason for this is that large overlapping particles can be very taxing on the fill rate of your GPU. When they're only drawing a few hundred or thousand pixels each, this is pretty manageable. But as you get your camera close to a particle system and it fills your screen, each particle might be drawing to millions of pixels every frame, massively increasing the cost to draw them all.

So, for particle systems that are normally seen at a distance or take up just part of the screen (most cases), Unity defaults to scaling each particle to take up no more than half the viewport.

As you approach such a particle system, there comes a point where the particles stop growing in apparent size and instead appear to just slide sideways out of the frame - which can also help mask the "popping" you might otherwise see as the camera near plane clips through the particles.

You can turn off this behaviour when it's not desired by cranking up the Max Particle Size property, or changing the particles to draw in Mesh mode (using a quad mesh) instead of one of the billboarded modes.

---
Tags: unity, particles
---


# Question
Title: ContactFilter2D does not detect a trigger even with "use triggers" enabled
I'm Using Unity 2018.3.11f1 and I'm going crazy trying to understand why the "use triggers" variable of the ContactFilter2D is not having any effect and I'm always detecting only the non-trigger colliders.

The problem is just as simple as that: If I use the OverlapCollider trying to detect a collider that is not a trigger it works perfect. However, if that collider is set as trigger the "OverlapCollider" does not detect it even if I set the variable "useTriggers" of the used filter is set to true (and obviously in false the same behavious appears)

Does anyone have any clue about why it happens?

This is the code:

```
    ContactFilter2D filter = new ContactFilter2D();
    filter.SetLayerMask(GameManager.Instance.interactableLayers);
    filter.useTriggers = true;
    Collider2D[] results = new Collider2D[10];
    int collidersDetected = col.OverlapCollider(filter, results);

```

Thank you for your help in advance.

# Answer
> 1 votes
I found out that I had disabled "Queries hit triggers" on the Physics 2D configuration section.

Enabling it solved my problem.

---
Tags: unity, c#, physics, collider, layers
---


# Question
Title: If my camera does not change position but rotates, Does adding lerp do anything?
If my camera does not change position but rotates, Does lerp do anything?

```
        cameraposition = Vector3.Lerp(Camera.main.transform.position, Camera.main.transform.position, Time.deltaTime * cameraLerp);
        Camera.main.transform.position = cameraposition;
        Camera.main.transform.LookAt(gameobject.transform.position);

```

# Answer
These two lines together do nothing:

```
cameraposition = Vector3.Lerp(Camera.main.transform.position, Camera.main.transform.position, Time.deltaTime * cameraLerp);
Camera.main.transform.position = cameraposition;

```

Lerp is just a math function, that returns a value along the line between the first and second argument. If those two arguments are the same then it's just returning that argument, no matter what number you put in the third place (excluding NaNs and infinities as "not numbers")

So this is the same as:

```
a = lerp(b, b, t)
  = (1-t) * b + t * b
  = b

b = a

```

It does not leave any kind of residue behind that affects later operations like rotation.

If you want to smooth the rotation, you should use a Lerp or RotateTowards to compute the Quaternion orientation, not the position. eg:

```
Vector3 lookDirection = target.position - camera.position;
Quaternion targetOrientation = Quaternion.LookRotation(lookDirection);

camera.rotation = Quaternion.RotateTowards(
                    camera.rotation,
                    targetOrientation,
                    Time.deltaTime * degreesPerSecond
                );

```
> 2 votes

---
Tags: unity, camera, lerp
---


# Question
Title: How to calculate the distance from the camera to make a GameObject fill the screen?
How do you calculate the distance from the camera so that a GameObject fills the screen? I.e. Without reaching out of the view and regardless of screen orientation.

# Answer
You can return the difference of `transform.position` of Main Camera and `transform.position` of GameObject, **if you only want the distance between them**.
If you want something else, I think this video might help you
https://www.youtube.com/watch?v=MFQhpwc6cKE
> 1 votes

---
Tags: unity
---


# Question
Title: How to fix Corner Collision with SAT algorithm?
I am making a platformer game, my way of handling collision works most of the times, but when I jump on a platform's corner I get pushed away, it probably happens because my function returns right or left respectively and not bottom collision. Is there anyway to modify this function to work, or is there another algorithm that works better?

public static string RectangleCollision(Rectangle r1, Rectangle r2) {
    string result;

    float w = 0.5f * (r1.Width + r2.Width);
    float h = 0.5f * (r1.Height + r2.Height);
    float dx = r1.Center.X - r2.Center.X;
    float dy = r1.Center.Y - r2.Center.Y;

    if (Math.Abs(dx) <= w && Math.Abs(dy) <= h) {

        // Collision
        float wy = w * dy;
        float hx = h * dx;

        if (wy > hx) {
            if (wy > -hx) {
                // Collision on top
                result = "top";
            } else {
                // On left
                result = "left";
            }
        } else {
            if (wy > -hx) {
                // on right
                result = "right";
            } else {
                // on bottom
                result = "bottom";
            }
        }

     } else {
         result = "false";
     }

     return result;
}
```
</code></pre>

# Answer
Can you provide some screenshots of the problem?

Just try this method below, I hope it can solve your problem:

```
        public HitState checkHit(Rectangle r1, Rectangle r2)
        {
           HitState retv;
            retv.hit = false;
            retv.hitTop = false;
            retv.hitBottom = false;
            retv.hitLeft = false;
            retv.hitRight = false;
            retv.hitInside = false;
            retv.hitExact = false;

            Rectangle temp1 = Rectangle.Intersect(r1, r2);
            if (temp1.Width == 0 && temp1.Height == 0)
            {
                return retv;
            }

            retv.hit = true;
            if (temp1.Y == r1.Y) retv.hitTop = true;
            if (temp1.Y+temp1.Height == r1.Y+r1.Height) retv.hitBottom = true;
            if (temp1.X == r1.X) retv.hitLeft = true;
            if (temp1.X+temp1.Width == r1.X+r1.Width) retv.hitRight = true;

            return retv;
        }
    }

    public struct HitState
    {
        public bool hit; // true if hit
        public bool hitTop; // true if hit top
        public bool hitBottom; // true if hit bottom
        public bool hitLeft; // true if hit left
        public bool hitRight; // true if hit right
        public bool hitInside; // true if one inside other
        public bool hitExact; // only true if both bounding boxes exact size
    }

```
> 0 votes

---
Tags: c#, collision-detection, monogame
---


# Question
Title: How do I determine the rotation of a Tile using Tilemap in Unity 2d?
I want to know the rotation of the tile in C# in order to do some logic on another object that is sitting on the tile. The rotation matters for the logic. I don't see anything except GetTileData in the doc, but that doesn't actually seem to "Get" the tile data. I could cast to Tile but not all tiles are Tile. Alternatively, I think I can get the rotation if I can get the GameObject for the tile but I have no idea how to do that either from a BaseTile.

Anyone have any suggestions? Maybe I'm trying to do this wrong and I should make different tiles for each orientation or extend BaseTile or some other solution instead of trying to determine rotation. Any help or ideas would be greatly appreciated!

Additional info: When I inspect around in the Unity editor I see that the rotation is stored in Z in something called "Grid Selection" but I can't find a programmatic way of accessing that.

# Answer
Thanks to @Arkeus in the Unity Developer Community Discord for helping me out with this!

You need to get the transformation matrix of a specific tile in a tilemap. That includes the rotation information of the specific tile.

```
myTilemap.GetTransformMatrix(Vector3Int).rotation

```
> 0 votes

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


# Question
Title: Unity: How to receive input events on a RectTransform that does not contain any image/text/...?
In Unity 2018.3: Imagine a `GameObject` with only a `RectTransform` component and a custom script attached to it - otherwise completely empty. Is there a way to receive input events (like `IPointerClickHandler.OnPointerClick`) without adding any graphical GUI components like text/image/rawimage/etc. ?

In other words: Is there a component or superclass available to receive input events without adding an unused graphical component?

Any clarifications are welcome, Thank you.

# Answer
As @DMGregory pointed out, an elegant solution is to inherit a script from Graphics class, which works just perfect.
> 0 votes

---
Tags: unity, gui
---


# Question
Title: I want a variable/field to only be declared when a specific condition is true. I used Compiler Directives. Is the code I wrote valid?
I want a field I declared (`float attackRange`) to be only declared when inheriting class set "`bool haveLongRangeAttack`" is set to `true`. I wanted to use ***Compiler Directives*** for this purpose. Here is the code I wrote;

```

using UnityEngine;

public abstract class Enemy<T> : MonoBehaviour where T : Enemy<T>
{
    [SerializeField] protected bool haveCloseRangeAttack = false,
                                    haveLongRangeAttack = false;
#if haveLongRangeAttack == true
    [SerializeField] protected float attackRange = 1f;
#endif

    [SerializeField] protected GameObject mainCharacter = null;
    protected GameObject enemy = null;

    protected virtual void ChasePlayer()
    {
        if(haveCloseRangeAttack)
        {
            //...
        }
        else if(haveLongRangeAttack)
        {
            //...
        }
    }
}

```

---

I don't know if it is right way to/of *do what I want* or *using **Compiler Directives*** so please review my code and tell me if there is a problem, or if there is a better way.

It was before 6 months when I started *writing* code, and C was my first language. I am trying to learn new things/*concepts* and writing at my own style. So *there will be another way* (**maybe more efficient**); if there is one, please teach me. I'm working on my own Game Project right now, I'm open to learn new things that will benefit me...

***TY for taking time ^.^!***

***PS:****There is no **compiler-directives** tag in Tags section. Maybe it will be useful to add this tag.*

# Answer
> 1 votes
The `#if` preprocessor directive can be used to check if specific preprocessor symbols are defined or not. Those symbols include certain predetermined ones (such as `DEBUG`) as long as whatever you define with `#define` or the `-define` switch to the compiler itself.

You cannot use the preprocessor to check for the existence of a *field* or any other sort of member within a generic parameter.

One way you could solve this problem is through the use of interfaces: create an interface `IHasLongRangeAttack` which mandates the behavior of an entity with a long-range attack, and implement that interface on enemies that need it.

An alternative is to use composition instead of inheritance to define your objects, creating a `LongRangeAttackBehavior` object or similar; enemies with long-range attacks have an instance of this type assigned to that field, enemies without leave it null.

The latter is probably what I'd suggest.

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


# Question
Title: Is triangle count so much cheaper on hard surface models that on animated meshes?
I have a human character that consists of 40k triangles. When I animated him, I noticed a huge impact on the frame rate.

Then I created a 10k tris version of the same model and animated him, and the frame rate was significantly higher.

I would like to ask if there is any formula or any other way to compare this situation with a high-poly model of a hard surface model against a low poly version of a hard surface model.

For example, I see some 3D model vendors that offer weapons for FPS games, and they call their weapons with 25k tris "lo poly".

Am I missing something here?

Is it really so cheap (for some reason that I haven't found out) to throw 25k of hard surface geometry to CPU or GPU, and it wouldn't make a noticable difference in comparision to a 3k tris hard surface model?

I'm working with Unity and HDRP, if that is important for an estimation.

Thank you.

# Answer
Yes. Much less is done with static mesh triangles at runtime, they basically get loaded and then pushed into the rendering pipeline repeatedly.

Triangles for animated meshes have all that done, but *also* the work of animating them (either on the CPU or the GPU or a combination of both). Either way, it takes more work.

As to your specifically question about *how* much more work...

> I would like to ask if there is any formula or any other way to compare this situation with a high-poly model of a hard surface model against a low poly version of a hard surface model.

No, there's no way to do this in general. There are countless ways to load, process and draw triangles for just static meshes, and countless more ways to do all that plus *animate* the triangles for animated meshes. It's impossible to generalize that possibility space to a formula.

In theory, for a specific implementation you could come up with some kind of relative cost factor (e.g., if you knew the Unreal implementations of static and skeletal meshes deeply enough, plus how they were used in your specific game). But practically speaking it's probably better just to profile the cases you are concerned about and make targeted optimizations.
> 2 votes

---
Tags: unity
---


# Question
Title: How to change the alpha of an uneditable LineEdit to 1?
I noticed that Godot changes the alpha of the LineEdit text when editable = false. I want the alpha to stay 1. What I'm trying to do here is let the user input a name and then when they press enter it saves it in some dict etc (not important) and still shows as normal text (they can't edit it again)

# Answer
Unfortunately, the LineEdit text's alpha appears to be hardcoded to 0.5 when it's disabled. I guess it could be replaced with a custom color property instead – this should be an easy addition, but it will require modifying the engine's source code.
> 1 votes

---
Tags: text, godot, alpha
---


# Question
Title: Unity UI Dropdown list rendering on top of other canvases
I have 2 screenspace canvases in my scene..

Canvas 2 has just the mouse pointer image on it, the canvas has a sort order of 10.

Canvas 1 has everything else on it, it has a sort order of 0.

The mouse pointer renders in front of everything on canvas 1, except for the dropdown list. which is pretty much the standard dropdown from the Create\UI\DropDown menu.

I didnt think it was possible for some things on one canvas to render on top of another, and some things to not. It obviously is! But how? What is going on? What do I need to change on the dropdown to make it render with the rest of the stuff on its canvas?

# Answer
OK duh It appears the default dropdown list has its *own* canvas with a sorting order of 30000

Its very late, brain not work.

It seems the DropDown component generates this canvas at runtime, so you cant just set it to not override sorting.. Unless you want to write a script to find the canvas everytime someone clicks the dropdown..

I just set my mouse canvases sorting order to 30,001 .. That worked
> 1 votes

---
Tags: unity, gui
---


# Question
Title: How can I start multiple StartCoroutine one by one inside loop?
```
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;

public class ConversationTrigger : MonoBehaviour
{
    public List<Conversation> conversations = new List<Conversation>();
    public GameObject canvas;
    public bool conversationEnd = false;

    private bool isRunning = false;

    [HideInInspector]
    public static int conversationIndex;

    private DialogueManager dialoguemanager;

    private void Start()
    {
        conversationIndex = 0;
        dialoguemanager = FindObjectOfType<DialogueManager>();
    }

    List<int> conversationsToPlay = new List<int>();
    public List<int> StartConversations()
    {
        for (int i = 0; i < conversationsToPlay.Count; i++)
        {
            if (!isRunning)
            {
                StartCoroutine(PlayConversation(conversationsToPlay[i]));
            }
        }

        return conversationsToPlay;
    }

    public IEnumerator PlayConversation(int index)
    {
        isRunning = true;

        if (conversations.Count > 0 &&
            conversations[index].Dialogues.Count > 0)
        {
            for (int i = 0; i < conversations[index].Dialogues.Count; i++)
            {
                if (dialoguemanager != null)
                {
                    dialoguemanager.StartDialogue(conversations[index].Dialogues[i]);
                }

                while (DialogueManager.dialogueEnded == false)
                {
                    yield return null;
                }
            }

            conversationIndex = index;
            conversationEnd = true;
            canvas.SetActive(false);
            Debug.Log("Conversation Ended");
        }

        isRunning = false;
    }

    public void SaveConversations()
    {
        string jsonTransform = JsonHelper.ToJson(conversations.ToArray(), true);
        File.WriteAllText(@"d:\json.txt", jsonTransform);
    }

    public void LoadConversations()
    {
        string jsonTransform = File.ReadAllText(@"d:\json.txt");
        conversations.Clear();
        conversations.AddRange(JsonHelper.FromJson<Conversation>(jsonTransform));
    }
}

```

This is the loop part :

```
List<int> conversationsToPlay = new List<int>();
        public List<int> StartConversations()
        {
            for (int i = 0; i < conversationsToPlay.Count; i++)
            {
                if (!isRunning)
                {
                    StartCoroutine(PlayConversation(conversationsToPlay[i]));
                }
            }

            return conversationsToPlay;
        }

```

And this is he script where I'm adding the indexs :

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

public class NaviDialogue : MonoBehaviour
{
    public ObjectsManipulation op;
    public bool scaling = true;
    public Scaling scale;
    public ConversationTrigger conversationTrigger;

    private bool ended = false;
    private bool startConversation = false;

    private void Start()
    {
        scaling = true;
        op.canScale = false;
    }

    private void Update()
    {
        if (scaling == true && DOFControl.hasFinished == true)
        {
            DOFControl.hasFinished = false;
            scaling = false;
            op.Scaling();
            PlayerController.disablePlayerController = true;
            conversationTrigger.StartConversations().Add(0);
            conversationTrigger.StartConversations().Add(1);
            conversationTrigger.StartConversations().Add(2);
        }

```

The first problem is that it's adding one item then start the conversations. But I want it first to add all the items 0,1,2 and then only to StartConversations.

The second problem is that once it's playing the first conversation it does playing the conversation 0 when it finish the conversation nothing happened and I want it to start playing conversation 1.

The idea is to play conversation 0 after conversation 0 ended start conversation 1 when 1 ended start 2 until it played all the conversations in the list.

So this example :

```
conversationTrigger.StartConversations().Add(0);
conversationTrigger.StartConversations().Add(1);
conversationTrigger.StartConversations().Add(2);

```

Should work like : playing the first item when ended play the second item when ended play the last item.

# Answer
It should be a coroutine too:

```
public IEnumerator PlayConversations () {
    for (int i = 0; i < 5; i++) {
        yield return StartCoroutine (PlayConversation (_conversations[i]));
    }
}

```

Call it:

```
StartCoroutine (PlayConversations ());

```

And it will call 5 `PlayConversation` coroutines one after another.

---

Updated: It turns out that `yield return StartCoroutine (SomeCoroutine ());` can be simplified to `yield return SomeCoroutine ();` in coroutines.
> 0 votes

# Answer
This sounds a like a situation where it might be useful to use an eventsystem/callbacks/delegates. Do some research on those keywords and see, if something like that fits your project better. It might be a little more work at the beginning, because you might need to learn something new, but I think it's the better way to go than to fix a problem, which you really don't need to solve right now.
> 0 votes

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


# Question
Title: Lowering Unity launcher graphic quality settings reduces mouse x turn speed, does quality affect time?
Lowering Unity App quality settings reduces mouse x turn speed, how to fix this?

I am not sure why this happens my only thought was time.timedelta is affected by the graphics quality setting in unity launcher.

when rotating a cube with input mouse x, the cube rotates at normal speed on high quality graphic settings, but lowering the graphic settings it begins to slow down. Inevitably at lowest it barely rotates.

```
using UnityEngine;

public class This : MonoBehaviour
{
    private float mouseTurn;
    private float turnSpeed = 64f;

    void Update()
    {
        mouseTurn = Input.GetAxis("Mouse X");
        transform.Rotate(0, mouseTurn * turnSpeed * Time.deltaTime, 0);
    }
}

```

# Answer
`Input.GetAxis("MouseX")` returns a value proportional to the distance the mouse has moved horizontally *since the previous frame*.

When your framerate is high, your mouse movement gets chopped into more, smaller pieces over the same time interval. When your framerat is low, a single long frame captures a wider span of mouse movement.

This would not be a problem ordinarily: if on each short frame you do a short camera movement, the total movement over the whole interval should match the total movement of the mouse.

The problem is this line:

```
transform.Rotate(0, mouseTurn * turnSpeed * Time.deltaTime, 0);

```

Here you're taking a `mouseTurn` variable, which as we saw before has a smaller value on short frames, and multiplying it by `Time.deltaTime` which *also* gets smaller on shorter frames.

The result is that you double-dip on time adjustment, multiplying your mouse speed by the *square* of the time interval. So short frames get an *even shorter* movement than they should, and long frames get an *even longer* movement than they should.

The solution: remove `* Time.deltaTime` when using a value like `MouseX` that has the time interval baked-in already, just like the mouse example shown in the Unity docs.
> 0 votes

---
Tags: unity, mouse, rotate
---


# Question
Title: Shadow flickering with first-person near clipping plane
After adding a first-personal controller asset, world shadows flicker like crazy. I don't understand the cause, and everything I've tried based on googling has failed to help.

https://i.imgur.com/Mx5MCKB.gifv

I've tried:

* Increasing the near clipping plane of the camera. The first-person asset I have defaults to `0.01`. Changing it to `0.1` or higher seems to solve the issue, except that breaks the first-person view.
* Toying with bias value on the directional light
* Changing `Render Mode` from `Auto` to `Important` on the directional light
* Changing the Shadow Projection quality to Stable Fit

The authors of the asset have not been able to help, though it doesn't seem to be specifically related to their product, just the clipping planes required.

I'm using Unity 2019.1.2f1 Personal.

# Answer
The first person asset uses two Camera objects, a `Camera` and a `First Person Camera`. Both had the `Near Clipping Plane` set to 0.01. Changing that value on the root `Camera` object solved the flicker, and did not interfere with the `First Person Camera`'s view of the character arms.

The "Camera" object:

The "First Person Camera" child object:
> 1 votes

---
Tags: unity
---


# Question
Title: How to connect multiple Godot 3.1 clients to a websockets server?
I'm trying to connect multiple players ( godot clients) to 1 nodejs server and it's the second client would not connect. The first client connects, not the second.

All the relevant tutorials and projects that I found are written for Godot 3.0, therefore they are useless in 3.1 since 3.0 did not have support for websockets.

Any minimal multiplayer web sockets tutorial / code snippet or project, written for godot 3.1? Could you share minimal code?

Something like this won't work

```
extends Node

var ws = null

func _ready():
    ws = WebSocketClient.new()
    ws.connect("connection_established", self, "_connection_established")
    ws.connect("connection_closed", self, "_connection_closed")
    ws.connect("connection_error", self, "_connection_error")

    var url = "ws://localhost:8080"
    print("Connecting to " + url)
    ws.connect_to_url(url)

func _connection_established(protocol):
    print("Connection established with protocol: ", protocol)

func _connection_closed():
    print("Connection closed")

func _connection_error():
    print("Connection error")

func _process(delta):
    if ws.get_connection_status() == ws.CONNECTION_CONNECTING || ws.get_connection_status() == ws.CONNECTION_CONNECTED:
        ws.poll()
    if ws.get_peer(1).is_connected_to_host():
        ws.get_peer(1).put_var("HI")
        if ws.get_peer(1).get_available_packet_count() > 0 :
            var test = ws.get_peer(1).get_var()
            print('recieve %s' % test)

```

# Answer
> 1 votes
The problem was simple to solve

When running multiple Godot editors it is also important to change the debugger port for one of the editors.

Both editors were trying to listen to port 6007 to find out any errors from the running game instance and this gives an error in one of the editors, like this: Error listening on port 6007

Change you debugger port by going to: Editor Settings -\> Network -\> Debug and change the remote port there to 6008 (or anything else than 6007)

# Answer
> 2 votes
Sometime ago I found this github repo who explain to connect multiple godot 3.1 client to a nodejs server with websocket.

The github project

some useful example

It's pretty much self explanatory. I hope this will help you in your search

---
Tags: godot
---


# Question
Title: SFML - How to animate two Sprites with the same Clock?
I'm making a basic Street Fighter style game in SFML, and I use `Clock` and `Time()` from SFML to time the animations. Here's the code I started with for my `Idle()` animation:

```
//frameTimer being Clock frameTimer;
void SpriteAnimator::Idle(Sprite & targetSprite, IntRect & targetRect)
{
    // changes x of target rect to proper point in sprite sheet to start animation
    if (targetRect.left < 0 || targetRect.left > 150)
        targetRect.left = 0;
    // every 0.2 seconds, change targetRect
    if (frameTimer.getElapsedTime().asSeconds() > 0.2)
    {
        if (targetRect.left == 150)
            targetRect.left = 0;
        else
            targetRect.left += 50;
        targetSprite.setTextureRect(targetRect);
        frameTimer.restart(); // set Clock back to 0
    }
}

```

This works for one sprite, but I have the 2nd sprite use the same methods as the first sprite. They both are objects made from PLayer.H, and they both call an instance of `SpriteAnimator` to animate their respective sprite sheet.

The problem is, they're both running off the same clock, so when one sprite calls `frameTimer.restart();` it messes both of them up, and only one can `Idle()` at a time.

How can I make it so they both can loop through their spritesheet at the same time, without the clocks overlapping?

(Btw my class structure is like this: main.cpp --\>has player.cpp --\>has spriteAnimator.cpp)

# Answer
> 1 votes
You could iterate over all your sprites in your main loop and set the textures using one clock, then reset the clock **after** the textures have been set.

# Answer
> 0 votes
Disclaimer: I have no experience with sfml.

I see two solutions to this problem:

* use different Clocks
* use deltatime instead of resetting the clock.

I think the deltatime aproach is the way to go. Just store the starting timestamp of your animation. With this approach: `ElapsedTime = Now - StartTime`. Everything with an animation has to have its own StartTime. Reset StartTime to Now at the end of the animation.
Somehow this is like an own clock, but if you pause the main clock, everything is paused.

---
Tags: c++, sprites, sfml
---


# Question
Title: Fast Serialization for Multiplayer Gaming
I wish to make a Java based multiplayer game. I am learning all about sockets and so forth. I have built a very basic UDP system that serializes an object with all the information about the game state and then sends that to the client. The client sends input which changes the game state.

My question is, is serializing an entire object an acceptable way to send game info over the internet.

It's super simple but my placeholder images are lagging quite a bit across the screen on a localhost. This could be for several reasons but I was wondering if serializing and then sending and then de-serializing was just too slow a method? This game will be fast paced and reflex oriented.

# Answer
> is serializing an entire object an acceptable way to send game info over the internet.

Yes and No, if the objects data is reasonably small and serialization is fast there's no problem. You generally want to send the least amount of data possible so java's default serialization is not your candidate for game networking, it's slow and generates large byte blobs.

Kryo on the other hand is a very good example for an easy to use and performance oriented serialization library, it allows you to register an object beforehand so that only the objects field-values and a class id (usually single byte) are sent. The default Java serialization generates a lot more data compared to Kryo since it saves additional info which you don't need for game networking but is handy for storage and when classes change.

There even is the Kryonet networking library which is built on top of Kryo. It's reasonably fast and also allows you to send over whole objects with fast, automatic serialization.

> It's super simple but my placeholder images are lagging quite a bit across the screen on a localhost.

Serialization is likely not your problem, you could have timing and/or interpolation problems, especially since you said that you only send a few values. Once you're running your game online you will need interpolation to handle network jitter.
> 1 votes

---
Tags: java, multiplayer, serialization, socket
---


# Question
Title: How to compile custom module for iOS in Godot3.1
I'm trying to add Share module in my game for iOS platform. i have this repo for sharing module Godot-Share.

I'm using godot 3.1 and i download latest godot source code from Link.

To implement share module i follow this step to compile custom module.

1. Copy share folder to godot/modules folder.
2. Then i compile for iOS using this Link. I used following command to compile.

```
scons p=iphone tools=no target=debug arch=arm

scons p=iphone tools=no target=debug arch=arm64

```

In **godot/bin** i get as result two files :

> libgodot.iphone.debug.arm.a
>
> libgodot.iphone.debug.arm64.a

3. After i used following command to generate **\*.debug.fat.a** file.

```
lipo -create bin/libgodot.iphone.debug.arm64.a bin/libgodot.iphone.debug.arm.a -output bin/libgodot.iphone.debug.fat.a

```

as result i get **libgodot.iphone.debug.fat.a** file in **godot/bin** folder.

4. i replaced **libgodot.iphone.debug.fat.a** file into **godot/misc/dist/ios\_xcode** folder
5. i copied **ios\_xcode** folder in documents, rename **ios\_xcode** to iphone, then zip it. i get result file **iphone.zip** in Document folder.
6. Then i add **iphone.zip** file to `Project>Export>Options>Custom Package>Debug`

7. Then Export project.

**Error I'm Facing :**

```
Undefined symbols for architecture armv7:
"_z_verbose", referenced from:
_inflateInit2_ in FBLogin.a(ftgzip.iphone.debug.arm.o)
_inflate in FBLogin.a(ftgzip.iphone.debug.arm.o)
_inflateEnd in FBLogin.a(ftgzip.iphone.debug.arm.o)
_inflateReset in FBLogin.a(ftgzip.iphone.debug.arm.o)
_inflate_blocks_reset in FBLogin.a(ftgzip.iphone.debug.arm.o)
_inflate_codes_free in FBLogin.a(ftgzip.iphone.debug.arm.o)
_inflate_blocks_new in FBLogin.a(ftgzip.iphone.debug.arm.o)
...
"_z_error", referenced from:
_inflate_codes in FBLogin.a(ftgzip.iphone.debug.arm.o)
ld: symbol(s) not found for architecture armv7
clang: error: linker command failed with exit code 1 (use -v to see invocation)

```

So my question is : Am i compiling and linking custom module for iOS is right?

How do i solve above issue?

# Answer
> 0 votes
i'm facing this error because because i'm trying to build custom binary from different version source code and provide to different version of godot engine.

I found solution from godot github repo.

**Answer :** To generate custom binary for custom module you need same version of `godot engine` and same version `source code` of engine. In my case i solve using `Godot 3.1` stable version for engine and source.

Here is link that provide step-by-step explanation of compile process.

Full Tutorial for Facebook Module Compile is here : Link

---
Tags: ios, godot
---


# Question
Title: How to pass more than one parameter for an object?
I am typing a code using C# in unity for game called Sea Gauntlet. In this game, there is a hero ship which I am suppose to control to do certain tasks. Along with that there is whirlpools, drones designed to destroy the ship and there are shield and hull power ups to survive in this game. It is surrounded by lake.

In this task, I am trying to avoid the whirlpool while collecting one shield and one hull power up. Here the AvoidWhirlpool passes a parameter Position2 Whirlpool.

This is just one whirlpool so even though I try to loop through all the whirlpools I am actually only looking at the same whirlpool many times. Any suggestion as to how to fix the problem? I have done the coding this far.

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

 public class AI : MonoBehaviour
 {
    public float vectornorth, vectoreast, ForwardThrust, RotationSpeed;
public float endDistance = 40f;
public float pressureScale = 0.1f;
public float rateScale = 4.2f;

public PID.PID_Params forwardThrustPIDParms;

public Position2[] waypoints = new Position2[5];
public int waypointIndex = 0;

public Position2[] MoveAwayWhirlpool = new Position2[5];
public int MoveAwayWhirlpoolIndex = 0;

// Used to initialise at the start of a Game Level or Task
public void StartTaskOrLevel()  // This is called at the start of each Task or game level
{
    forwardThrust = 0f;       // Initialise motion to zero
    rotationSpeed = 0f;

    forwardThrustPIDParms = pid.PIDParametersSet(1, 0, 0, -heroStatus.maxForwardThrust, heroStatus.maxForwardThrust, 0, 0);

    resetDataRunTime = true;
    logDataString = "X,Y";
    logData = true;

    waypoints[0].east = 100;
    waypoints[0].north = 100;
    waypoints[1].east = 200;
    waypoints[1].north = -100;
    waypoints[2].east = 300;
    waypoints[2].north = -200;
    waypoints[3].east = 100;
    waypoints[3].north = -100;
    waypoints[4].east = 250;
    waypoints[4].north = -100;
}

// Used to update Hero during a task or Game Level.
public void TaskOrLevelUpdate() // This is called 50 times per second during a Task or game level but not when a menu is displayed.
{

    if (heroStatus.task)
    {                               // Do task
        switch (heroStatus.level)
        {
            case 1:
                Task1();
                break;
            case 2:
                Task2();
                break;
                //case 3:
                //    Task3();
                //    break;
                //case 10:
                //    Task10();
                //    break;
        }
    }
    else
    {                              // Do Game

    }
}

// Used to close anything at the end of a Game Level or Task
public void EndTaskOrLevel()  // This is called at the end of each Task or game level
{
    logData = false;
}

public void Task1()
{
    float vectornorth, vectoreast, distToWhirlpool, stopDisPoint;
    float requiredVel;

    vectornorth = whirlpools[0].north - heroStatus.position.north;
    vectoreast = whirlpools[0].east - heroStatus.position.east;
    distToWhirlpool = Mathf.Sqrt(Mathf.Pow(vectornorth, 2) + Mathf.Pow(vectoreast, 2)); //calculate the distance from whirlpool
    stopDisPoint = distToWhirlpool - heroStatus.stopDistToWhirlpool;                    // defines about when to stop the ship

    target = whirlpools[0];
    useTarget = true;

    requiredVel = stopDisPoint * rateScale;
    if (stopDisPoint < endDistance)
    {
        requiredVel = stopDisPoint * rateScale;
    }
    else
    {
        requiredVel = heroStatus.maxForwardSpeed / 2f;
    }
    forwardThrustPIDParms = pid.PIDParametersSet(forwardThrustPIDParms, 1, 0, 0, -heroStatus.maxForwardThrust, heroStatus.maxForwardThrust, requiredVel, heroStatus.velocity.forward);
    forwardThrustPIDParms = pid.PIDController(forwardThrustPIDParms);
    forwardThrust = forwardThrustPIDParms.output;

    rotationSpeed = heroStatus.maxRotationSpeed;

} // The code is taken from class code video AI Week 2
public void Task2()
{

    if (shieldPowerups.Length == 0 && hullPowerups.Length == 0)
        return;
    forwardThrust = heroStatus.maxForwardThrust;
    rotationSpeed = heroStatus.maxRotationSpeed;
    if (shieldPowerups.Length != 0 && hullPowerups.Length != 0)
    { // There is both shield and hull power up
        float distShield, distHull;

        distShield = DistBetweenPoints(heroStatus.position, shieldPowerups[0]); // Distance from the shieldpowerup
        distHull = DistBetweenPoints(heroStatus.position, shieldPowerups[0]);   // Distance from hullpowerup
        useTarget = true;
        if (distHull < distShield)
            target = hullPowerups[0];
        else
            target = shieldPowerups[0];
    }
    else
    { // There is one shield or hull power up
        if (hullPowerups.Length != 0)
            target = hullPowerups[0];
        else
            target = shieldPowerups[0];
    } // The code is refered from class code and videos AI Week 3

    target = AvoidWhirlpool(heroStatus.position, whirlpools[0], target);

}

// Name: AvoidWhirlpool
// Input: Position2 - origin, whirlpool, target
// Output: Position2 - target
// Description:
//      Look at area between origin and target. If the whirlpool is
//      within that area, calculate a new target to avoid whirlpool.

public Position2 AvoidWhirlpool(Position2 origin, Position2 whirlpool, Position2 target)
{
    if (whirlpools.Length == 0)
        return target;

    float FinalDistance = 350f;

    // Rotate object
    Position2 rotTarget;
    Position2 rWhirlpool;

    //Find an angle to rotate through
    float angle = Mathf.Atan2(target.east - origin.east, target.north - origin.north) * 180f / Mathf.PI;

    // Rotate target above.
    rotTarget.east = 0;
    rotTarget.north = DistBetweenPoints(origin, target);

    for (int i = 0; i < whirlpools.Length; i++)
    {
        float distToWhirlpool = DistBetweenPoints(origin, whirlpools[i]);

        // Define original position
        rWhirlpool = whirlpool;
        rWhirlpool.east -= origin.east;
        rWhirlpool.north -= origin.north;

        // Rotate whirlpool in north
        rWhirlpool = RotateAboutUp(rWhirlpool.east, rWhirlpool.north, -angle);

        //Check for obstacle
        if (rWhirlpool.north > 5f && rWhirlpool.north < 300f && rWhirlpool.east > -40f && rWhirlpool.east < 40f)

        {
            //Whirlpool is an obstacle
            if (distToWhirlpool < FinalDistance)
            {
                if (rWhirlpool.east > 0f)
                {
                    // Move target towards left
                    rotTarget.east = -50f;
                    rotTarget.north = distToWhirlpool;
                }
            }
            else
            {
                // Move target towards right
                rotTarget.east = 50f;
                rotTarget.north = distToWhirlpool;
            }
            FinalDistance = distToWhirlpool;  // Save present distance
        }
        else
        {
            // Whirlpool not an obstacle
        }
        target = RotateAboutUp(rotTarget.east, rotTarget.north, angle);
        target.north += origin.north;
        target.east += origin.east;

        return target;
    }
    return target;
}

```

# Answer
> 1 votes
Here.

> `rWhirlpool = whirlpool;`

`whirlpool` is *not* your current whirlpool, `whirlpools[i]` is. That's why you look at one and the same whirlpool which comes as a parameter. You don't need that parameter at all.

Also, look at this:

> ```
>     return target;
> } // the brace from for loop
>
> ```

You *always* return after the first iteration. So you will never process more that one first whirlpool. If you want to iterate through all whirlpools, get rid of this `return`.

If this function should avoid only one whirlpool, remove the loop from it, and instead call it from inside a loop.

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


# Question
Title: How can I only call write function when value from series of IF statements change?
I'm calculating the distance of the player from a point at any given time point in the game (using a series of IF statements), then returning the label associated with the nearest point. So that I can output that point to a text file.

Is there a way I can only get (or at least only output) the value if the value has changed?

I'm a fairly novice coder so please provide as much information as possible. Thanks in advance.

```
if (distPlayer5 < distPlayer2 &&
    distPlayer5 < distPlayer1 &&
    distPlayer5 < distPlayer4 &&
    distPlayer5 < distPlayer3 &&
    distPlayer5 < distPlayer6 &&
    distPlayer5 < distPlayer7)
{
    pathPoint = ("E");
    Debug.Log("pathpoint =" + pathPoint);
    WriteData();
}
if (distPlayer6 < distPlayer2 &&
    distPlayer6 < distPlayer1 &&
    distPlayer6 < distPlayer4 &&
    distPlayer6 < distPlayer3 &&
    distPlayer6 < distPlayer5 &&
    distPlayer6 < distPlayer7)
{
    pathPoint = ("F");
    Debug.Log("pathpoint =" + pathPoint);
    WriteData();
}
// ... etc.

```

# Answer
Store the value every frame but before that check if it changed:

```
if (distPlayer5 < distPlayer2 && distPlayer5 < distPlayer1 && distPlayer5 < distPlayer4 && distPlayer5 < distPlayer3 && distPlayer5 < distPlayer6 && distPlayer5 < distPlayer7)
{
    //...
}
//...

if(lastPathPoint != pathPoint){
    Debug.Log("pathpoint changed to: " + pathPoint);
}
lastPathPoint = pathPoint; //Store for the next frame

```

`lastPathPoint` should be declared where it will survive until next frame.

---

However you can create an array of `distPlayer` and then look for the index with the minimal value:

```
float minDistance = distPlayer[0];
int pathPoint = 0;
for (int a = 1; a < distPlayer.Length; a++)
{
    if (minDistance > distPlayer[a])
    {
        pathPoint = a;
        minDistance = distPlayer[a];
    }
}
if(lastPathPoint != pathPoint){
    Debug.Log("pathpoint changed to: " + pathPoint);
}
lastPathPoint = pathPoint; //Store for the next frame

```

Then you can use that index to get the related information regarding that player.
> 1 votes

---
Tags: c#
---


# Question
Title: Violation of Usage of Android Advertising ID policy
I made a game in Unity with admob integration, and I published it on the Google Play store.

After 2 days I got a mail from the Play store mentioning a policy violation (reproduced below). I l researched the issue and updated a privacy policy document on my app, then resubmitted the game.

It came went live, but then I got the same mail from the Play store again and they removed it.

From the beginning onwards my ads are also not showing in game, but the test ad is working fine.

Can you tell me what mistake I made and how I can fix it?

Message from Google:

> Notification from Google Play about Green Puzzle Truck
>
> Google Play Support
>
> Hi developers at \**** \**** Studio,
>
> After review, "my game name" , package name, has been removed from Google Play due to a policy violation. This app won’t be available to users until you submit a compliant update.
>
> Issue: Violation of Usage of Android Advertising ID policy and section 4.8 of the Developer Distribution Agreement
>
> Google Play requires developers to provide a valid privacy policy when the app requests or handles sensitive user or device information. We’ve identified that your app collects and transmits the Android advertising identifier, which is subject to a privacy policy requirement. If your app collects the Android advertising ID, you must provide a valid privacy policy in both the designated field in the Play Console, and from within the app.
>
> Next steps: Submit your app for another review
>
> Read through the Usage of Android Advertising ID and User Data policies, as well as the Developer Distribution Agreement, and make appropriate changes to your app. If you decide to collect sensitive user information, be sure to abide by the above policies, and include a link to a valid privacy policy on your app's store listing page and within your app.
>
> Make sure that your app is compliant with all other Developer Program Policies. Additional enforcement could occur if there are further policy violations.
>
> Sign in to your Play Console and submit the update to your app.
>
> Alternatively, you may opt-out of this requirement by removing any requests for sensitive permissions or user data.
>
> If approved, your app will again be available with all installs, ratings, and reviews intact.
>
> If you’ve reviewed the policy and feel this removal may have been in error, please reach out to our policy support team. One of my colleagues will get back to you within 2 business days.
>
> Thanks for helping us provide a clear and transparent experience for Google Play users.
>
> Regards,
>
> The Google Play Team

# Answer
You must implement something for GDPR if you're shipping in the EU. Your customers need to be able to opt out of the use of tracking IDs and have an option to **delete** any existing tracking info you have.

I had to do this for Cognizer, for both iOS and Android. I was using Unity, so they made it easy with a plugin.

Cognizer is free (no ads either), so you can download it and take a look at how that is interfaced as an example of what is acceptable. Go to the Credits screen, and click the Privacy icon in the lower left.
> 1 votes

---
Tags: unity, google-play-services, google-play, admob
---


# Question
Title: Why isn't my vertical scrolling functioning properly?
I'm trying to make a simple 2D platformer in XNA, but I'm having trouble with the vertical scrolling.

What I'm trying to accomplish is that whenever the player is above half the height of the screen, the player should jump and fall. However, if the player is below half the height of the screen, then the player should remain in the middle of the screen and the background image and platforms should move around him instead, creating a scrolling effect.

I'm not sure why, but whenever the player is at half the height of the screen, the background and platforms don't move as much as they should, so the player can't make jumps that he would otherwise be able to.

I'm at a loss as to how to fix this issue, can anyone help? Any assistance would be much appreciated.

```
        if (keyState.IsKeyDown(Keys.D))
        {
            if (player.position.X < bgView.Width / 2 || bgView.X >= backgroundImage.Width - bgView.Width) //If the player position is less than 400px or if the bgView is greater than 1200 then the player moves, the BG is stationary
            {
                player.position.X += speed;
            }
            else //If the player is greater than 400px and and the bgView is less than 1200 then the BG elements move instead, the player remains centred
            {
                bgView.X += 4; //moves the BG
                for (int i = 0; i < rows; i++)
                {
                    for (int j = 0; j < cols; j++)
                    {
                        if (block[i, j].position.X < bgView.Width / 2 || bgView.X >= backgroundImage.Width - bgView.Width)
                        {
                            block[i, j].position.X -= speed; //moves the platforms
                        }
                        else
                        {
                            block[i, j].position.X -= speed;
                        }
                    }
                }
            }
        }

        if (keyState.IsKeyDown(Keys.A))
        {
            if (player.position.X > bgView.Width / 2 || bgView.X <= 0)
            {
                player.position.X -= speed;
            }
            else
            {
                bgView.X -= 4;
                for (int i = 0; i < rows; i++)
                {
                    for (int j = 0; j < cols; j++)
                    {
                        block[i, j].position.X += speed;
                    }
                }
            }

        }

        if (player.position.X < 0) //Stops the player from moving backwards from the beginning of the stage
        {
            player.position.X = 0;
        }
        if (player.position.Y + player.image.Height > screenHeight) //Stops the player from falling through the floor
        {
            player.position.Y = screenHeight - (player.rectangle.Height);
        }
        if (player.position.X + player.image.Width > screenWidth) //Stops the player from leaving the end of the stage
        {
            player.position.X = screenWidth - player.image.Width;
        }

        for (int i = 0; i < rows; i++) //Checks the player position to see if it's intersecting a block's rectangle.
        {
            for (int j = 0; j < cols; j++)
            {
                if (player.position.Y + player.image.Height >= block[i, j].rectangle.Top - 1 && //checks if the player is intersecting the top of a block
                    player.position.Y + player.image.Height <= block[i, j].rectangle.Top + (block[i, j].rectangle.Height / 2) &&
                    player.position.X + player.image.Width >= block[i, j].rectangle.Left + (block[i, j].rectangle.Width / 5) &&
                    player.position.X <= block[i, j].rectangle.Right - block[i, j].rectangle.Width / 5)
                {
                    gravity = 0;
                    jumping = false;
                    player.position = new Vector2(player.position.X, (block[i, j].position.Y + 1) - player.image.Height);
                    touchingTop = true;
                }
                if (player.position.Y <= block[i, j].rectangle.Bottom + (block[i, j].rectangle.Height / 5) && //checks if the player is intersecting the bottom of a block
                    player.position.Y >= block[i, j].rectangle.Bottom - 1 &&
                    player.position.X + player.image.Width >= block[i, j].rectangle.Left + (block[i, j].rectangle.Width / 5) &&
                    player.position.X <= block[i, j].rectangle.Right - (block[i, j].rectangle.Width / 2))
                {
                    player.position = new Vector2(player.position.X, block[i, j].rectangle.Bottom + 5);
                    force = 0;
                }
                if (player.position.X + player.image.Width <= block[i, j].rectangle.Right && //checks if the player is intersecting the left of a block
                    player.position.X + player.image.Width >= block[i, j].rectangle.Left - 5 &&
                    player.position.Y <= block[i, j].rectangle.Bottom - (block[i, j].rectangle.Width / 4) &&
                    player.position.Y + player.image.Height >= block[i, j].rectangle.Top + (block[i, j].rectangle.Width / 4))
                {
                    player.position = new Vector2(player.position.X - 4, player.position.Y);
                }

                if (player.position.X >= block[i, j].rectangle.Left && //checks if the player is intersecting the right of a block
                    player.position.X <= block[i, j].rectangle.Right + 5 &&
                    player.position.Y <= block[i, j].rectangle.Bottom - (block[i, j].rectangle.Width / 4) &&
                    player.position.Y + player.image.Height >= block[i, j].rectangle.Top + (block[i, j].rectangle.Width / 4))
                {
                    player.position = new Vector2(player.position.X + 4, player.position.Y);
                }
            }
        }
        for (int i = 0; i < rows; i++) //sets the block's rectangle position
        {
            for (int j = 0; j < cols; j++)
            {

                block[i, j].rectangle.X = (int)block[i, j].position.X;
                block[i, j].rectangle.Y = (int)block[i, j].position.Y;
            }
        }
        //Checks whether or not the player is falling
        if (force <= 7)
        {
            falling = true;
        }
        if (force > 7)
        {
            falling = false;
        }

        if (keyState.IsKeyDown(Keys.W)) //After the player jumps, the force of the jump decreases over time, increasing the speed of falling
        {
            jumping = true;
        }
        if (jumping && player.position.Y + (player.image.Height / 2) > screenHeight / 2)
        {
            touchingTop = false;
            player.position.Y -= force;
            force -= 0.3f;
            if (force < 0)
            {
                force = 0;

            }
        }
        if (player.position.Y + (player.image.Height / 2) <= screenHeight / 2)
        {
            player.position.Y = screenHeight / 2 - (player.image.Height / 2);
            bgView.Y -= (int)force;
            bgView.Y += (int)gravity;
            for (int i = 0; i < rows; i++)
            {
                for (int j = 0; j < cols; j++)
                {
                    block[i, j].position.Y += (int)force;
                }
            }
        }
        else
        {
            bgView.Y += (int)force;
        }

        for (int i = 0; i < rows; i++) //Stops the blocks from ascending higher than the position they start at
        {
            for (int j = 0; j < cols; j++)
            {
                block[i, j].position.Y -= gravity;
                if (block[i, j].position.Y <= block[i,j].startingPos.Y)
                {
                    block[i, j].position.Y = block[i,j].startingPos.Y;
                }
            }
        }
        if (!jumping)
        {
            force = 14f;
        }
        if (bgView.X < 0) //Prevents the background from scrolling backwards from the beginning of the stage
        {
            bgView.X = 0;
        }
        if (bgView.Y > 600)
        {
            bgView.Y = 600;
        }
        if (bgView.Y < 0)
        {
            bgView.Y = 0;
        }
        player.position.Y += gravity; //Gravity is constantly being added to the player's Y position
        base.Update(gameTime);
    }

```

# Answer
> 1 votes
In your code you have tied the game logic of the player directly to the motion of the camera; this creates a situation where the player and the camera play catch-up. Thus the player's "screen" position dictates the behavior, while actually this should be the "world" position.

The best way to solve this, is to untie the camera to the game logic. Basically, the player should move in the game world even when the camera is not watching. So the player falls down if it is not standing on a platform. The camera should then follow the falling player if the player is in the bottom half of the screen. Have a look at this classic article about camera implementations. In your case you want a "camera window" that covers the top half of the screen.

To implement this, a lot of games implement a separate camera class, that follows the player around.

Have a look at my answer to this question for example code (or check the accepted answer to that question- though I'd argue that that answer is less modular, but uses the same principle).

The basic idea is to code the game logic to work on game world coordinates; and worry about what part of the game world you show in a camera implementation.

---
Tags: c#, xna, scrolling
---


# Question
Title: Running into issues with Unity Vertical Layout Group
I feel sure that I'm missing something obvious, but I've been stuck with this over the past few days.

I want to make a relatively simple UI component for a character creation screen that looks something like this:

The structure is something like:

Canvas
-Panel
--Dropdown 1 Container
---Header
----Collapsible Body (Set as inactive)
-----Buttons for options
-----Buttons for options
-----Buttons for options
--Dropdown 2 Container
---Header
----Collapsible Body (Set as active)
-----Buttons for options
-----Buttons for options
-----Buttons for options
--Dropdown 3 Container
---Header
----Collapsible Body (Set as inactive)
-----Buttons for options
-----Buttons for options
-----Buttons for options
--Dropdown 4 Container
---Header
----Collapsible Body (Set as inactive)
-----Buttons for options
-----Buttons for options
-----Buttons for options
...

Unfortunately, some basic parts of this seem to be beyond my ability.

The panel that contains everything has a Vertical Layout group, but the "Spacing" can only be set to one value at a time, which doesn't work for this because the drop down boxes alternate between two sizes depending on whether they're active or not. Grid Layouts don't seem to work either, because the cell sizes can't be changed dynamically.

Is there a simple option for this, or would I need to code something myself?

Thanks for any info you can provide.

# Answer
Alright my dude. Welcome to the hell that is layout groups. Here's a few things you'll need to know first:

1. If nothing is sizing the object, the layout group will not work as you expect (in fact it appears the opposite). Things that size the object include LayoutElement and ContentSizeFitter. For whatever reason the default rect transform sizings make the layout groups work opposite how you expect.
2. Layout groups CAN dynamically size, but sometimes when working with them via script, they don't update their layout fast enough. You may need to make calls to LayoutRebuilder.ForceRebuildLayoutImmediately()
3. ContentSizeFitter will take it's children's prefered or min size (I usually use min) and make sure they fit those values. You'll want to make sure all your children of a ContentSizeFitter either have their own sizefitter OR LayoutElement. Set your LayoutElement min width/height to the width and height you want the element to be.
4. All these layout classes like to "drive" different parts of the rect transform. Sometimes, when you change the settings or delete the layout, it will still say it's driving the values and you can't edit them. This is a bug. Duplicate the game object, and delete the old one and it will reset. This can also apply for when you change settings on LayoutGroups. If something doesn't seem right, it probably needs you to duplicate the entire layoutgroup gameobject, and delete the old one.

With that, let me explain how i'd handle this. Note, all content size fitters should be set to minimum in the vertical dimension. I Assume your Panel is the viewport for a unity scroll area so let's add a gameobject as a child of Panel called Content since Unity's scroll area reaquires a Viewport and Content. Content will have your vertical layout group and contain all the DropdownContainers. Each DropdownContainer should have a ContentSizeFitter that will resize it's rect transform to it's contents. Sometimes unity will yell at you for this, but just ignore it. It's BS. Inside, your Header needs a content size fitter as well. This let's it scale to the size of the collapsableBody. Now when this collapsable body resizes, you also need to know it's size. If you're just expanding the height of the viewport, then update a LayoutElement on the CollapsableBody to match the height of the viewport at all times. Just make sure you somehow declare to the ContentSizeFitter on Header that it's getting bigger. For the elements in the header visuals, they all need to have LayoutElement on them with their min width and height defined as well. Just remember, anything that doesn't have LayoutElement or ContentSizeFitter or something of the sort will be invisible to the ContentSizeFitter. Now that we have all the internal elements resizing correctly, add a ContentSizeFitter to the Content alongside the VerticalLayoutGroup. It will give you a warning. Ignore this. It's a false positive. Now the Content of your scroll area will be sizing ALL that child content. Holy crap. Now. Finally. Let's set the properties on your layout group. Set padding/spacing to what you want. Child alignment is Upper Center, Child Controls Size should be checked for height. Uncheck everything else. If you want you can force child expand on width. This will mean when you make your Content box wider, the elements inside will scale. But to do this correctly you'll need to make sure all the children are open to being scaled, and their rect transforms are anchored to scale width wise.

That's it. Quite a mouthful. Overall, I found not only were layout groups incredibly buggy and awful to work with, but also they are very nonperformant. And relying on them may require you to force rebuild the layout which is very heavy. Unity's UI works amazingly when you scale from an outside-in approach. Using rect transforms and anchors can get you a long way. Scaling from the inside-out, is only necessary with dynamically added elements. Like an inventory, or your dropdown UI. My advice is to design your UI to be as outside-in scalable as possible. What I mean by that, is have it so you can change the parent rect transform, and all the inner objects will grow/shrink to match instead of scaling the children and making the parents fit their contents. Consider tabs, pages, static lists over resizing elements. try to limit layoutgroups to inside scroll areas.
> 13 votes

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


# Question
Title: What is wrong with this particular code?
I have to correct this code without changing the structure. Cannot seem to figure out what's wrong.

`missiles` is an array of `missiles`.

`DeleteAtIndex()` takes the last object in the array and replaces the object at the index with it. And decrease the count of the array with one.

`pos` and `pos` of the `missiles` are vectors. All operators are defined for them. Length works on a Vector and returns the magnitude of the vector.

```
public void Defense::Update()
{
 float dist;
 for(int i = 0; i < missiles.Count(); i++)
 {
      dist = (pos – missiles[i].pos).Length();
      if( dist = detectionRadius )
      {
           CreateDeathEffect(missiles[i].pos);
           missiles.DeleteAtIndex(i);
      }
 }
}

```

# Answer
> 2 votes
You're cutting off the branch on which you're standing.

You're changing the size of the container over which you're iterating. Even if you replace the item at index with the last one, you'll be skipping that item because you increase i at the end of each loop.

To fix that, you could iterate over your missiles starting with the end of the collection:

```
for(int i = missiles.Count() -1; i>= 0; i--)

```

# Answer
> 2 votes
I cannot guess what language do you use so I answer about generic c-like language. Also since you didn't write explicitly what's wrong I can't be sure what's wrong so I will guess.

Comparison is `==`, not `=`. `=` is *assignment* and it will *rewrite* your variable and because it's inside `if` it will be implicitly cast to boolean.

Also you should not compare two floats with `==` or `!=`. Floating point operations are not perfectly accurate because of limited precision of the floating point number type. You remember old calculators: when you divide 1 by 3 and then multiply 0.333... by 3 the result will be 0.999..., not 1. They are not equal. The same rule applies there.

That's how you should compare them in most cases: `if (abs(a-b) < 0.001) {...}`

But your case is about radius where missiles explode, you probably should handle case when they are not *on circle border*, but *inside*, so simply change `=` to `<`.

---
Tags: debugging
---


# Question
Title: Is it possible to use unnormalized texture coordinates from a GLES2 GLSL fragment shader?
I want to look up a texel from my `GLES2` `GLSL` **fragment shader** using un-normalized texture coordinates (0-w, 0-h instead of 0-1, 0-1). The reason is that this texture is used as a look up table and I get **precision** **problems** with normalized coordinates.

I see that `GL_TEXTURE_RECTANGLE` is not supported wihtout extensions and neither is `texelFetch()`, so I have ruled out those options.

Thanks!

# Answer
I'm not sure what you mean by un-normalized texture coordinates. All texture lookups are going to be in the range of 0-1. You can have them be anywhere in that range however. If you're having precision problems in the range of 0-1 I suspect something else going on.

A couple of hints to help fix this:

For example, make sure you don't have `GL_LINEAR` set for your texture. For a lookup to be accurate you're probably going to want `GL_NEAREST`. Otherwise it could average the data around the textel and give you a interpolated result. Same goes for the GL\_WRAP settings. You probably want something like this:

```
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

```

I once had a large texture atlas (2048x2048) with a bunch of sprites on it. And in one small area of the texture I had a look up table. So in that case the lookup S started at 1024/2048 and ended at 1536/2048. So I passed to the shader uniforms for `SStart` and `SWidth`. And `TStart` and `TWidth`. `SStart` was `0.5` and `SWidth` was `0.25`. In my S direction I had 512 steps on the lookup, or `0.25` of `2048`. In the T direction it was also a small segment, but there I also needed to make sure it didn't bleed over in to the one next to it. So I made each lookup in the texture about 8 pixels wide, and in code I aimed to hit the middle.

The math for the S direction was an input of 0-1, so the formula was `s = SStart + input * SWidth`.

There is plenty of precision in a lowp variable to handle a lookup in the range of 0-1 for any texture size that your hardware supports. Even `1/4096`. This is what the gxf card is designed to do.
> 1 votes

# Answer
What you want is a texture rectangle. Take a look at this question.

Usually you can get around this by converting to normalized values so that they map to the pixel coordinates centers of the stored image which is specified in the OpenGL standard as:

> A fragment is located by its lower left corner, which lies on integer grid coordinates. Rasterization operations also refer to a fragment’s center, which is offset by (1/2,1/2) from its lower left corner (and so lies on half-integer coordinates).

So if you want to retrieve the pixel at *(i,j)* where *i=0,1,2,..,W-1* and *j=0,1,..,H-1* then use the normalized coordinate *(u,v) = ((i+0.5)/W, (j+0.5)/W)* and make sure filtering is set to `GL_NEAREST`.
> 0 votes

---
Tags: textures, glsl, opengl-es2, precision
---


# Question
Title: Is it reasonable to use a 2D texture as a lookup table in GLSL
I need a lookup table in a shader. The input values would be color values and the output other color values. Something like:

```
uniform float lut[256];

color = vec3(lut[int(color.r*255.)], lut[int(color.g*255.)], lut[int(color.b*255)]);

```

does what I need but certain implementations of OpenGL ES do not allow arrays with variable indexing so finally I've arrived to the conclusion that the most portable way is to have a 2D texture as the LUT. A texture of 256x256 could store many different lookup tables, each one (256 entries) in a single row.

In order to load a row in the texture (c++) I would use:

```
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 256, 1, GL_LUMINANCE, GL_UNSIGNED_BYTE, data);

```

to store a table in the first row (I assume that internally in the texture I'd have the value repeated in R, G and B)

To fetch the LUT in the fragment shader I'd use `texture2D(lut,vec2(index, constRow))` (index in the range 0-1 and constRow = 0 being the row in the texture where it is stored the lut).

Is that a reasonable way to implement that?

**Update:** In order to fetch values in the texture-LUT you need normalized indexes (0.0-1.0), so to access row 7 I have to index it as `texture2D(lut, vec2(index, 7./255.));` From what I see the result is (or may be) an interpolation with the two other consecutive rows.

# Answer
Your normalization is not exactly correct. You need to note that the OpenGL standard says

> A fragment is located by its lower left corner, which lies on integer grid coordinates. Rasterization operations also refer to a fragment’s center, which is offset by (1/2,1/2) from its lower left corner (and so lies on half-integer coordinates).

Therefore, the integer pixel coordinate `(i,j)` is located at the normalized coordinate `((i+0.5)/W, (j+0.5)/W)`.
> 2 votes

---
Tags: opengl, textures, glsl
---


# Question
Title: Passive skill for balanced race / faction
I'm currently working on an RPG game project. I’m out of ideas on how to properly set race skills in the RPG. In the game, three different races exist:

* **Human** – Balanced starting stats, active skills are focused on crowd control, debuffs, and average damage
* **Dwarf** – starting stats has huge amount of HP but at the cost of damage and speed. Active skills are focused on defense.
* **Elf** – starting stats has boost to damage and speed, but at the cost of low HP/MP. Active skills are focused on Damage

Currently I’m in the phase when I want to implement race skills. Race skills should be a passive skill which your character automatically earns after creation. This skill is another way of diversification, so if you compare a dwarf warrior with an elf warrior, there will be a difference in active skills, in starting stats, and also with a race skill.

I'm thinking about race skill for Dwarfs and Elves, but I'm out of ideas for a race skill for humans, which are characterized as a balanced race.

* **Dwarfs** – 10% damage reduction on each hit by the enemy
* **Elfs** – +5% critical hit chance
* **Humans** – ???

Any suggestions are welcome.

# Answer
> 4 votes
Sort of two part answer...

First, I'd make humans "normal" myself - nothing special. We are a kind of bland race. But that's totally a subjective thing.

Second, I would create a combat simulator that is driven off your rules and character classes. The simulator is not a visual, game-type environment. It's purely a program that spits out statistics of simulated combat. This is a classic Monte Carlo simulation setup.

With a system like this, you can let it fight thousands and thousands of random matchups and see what the results are overall. Ideally with 3 races, you want a nice 1/3 1/3 1/3 split showing that all in all the 3 races are statistically even when it comes to victory.

Once you have that simulator working, start tweaking and adjusting your race specs, and re-run the simulation. This will let you get a better idea of how well balanced (or not) your design is. It lets you for example answer the question, "What is the impact of changing the Elf critical chance from 5% to 4%?"

This also gives you full freedom to experiment with different skills for humans to see what the impact is. What happens if humans heal faster? Do a double attack every 10th round? You can test and find out with the simulator.

# Answer
> 2 votes
You can't properly balance races unless you have the combat system in place. How useful is 10% damage reduction? If combat is mostly focused on avoiding hits, this skill becomes less and less useful. Also for the 5% critical, what if combat is based on 1-2 hits to kill an enemy? That would require a different critical percentage than if an average enemy needs 50+ hits to kill.

Here's how I've done it in the past, it's not the best way, but it can help you go to the right path.

* Create a formula like: "A level 1 hero needs 5 hits to kill a level 1 enemy, a level 1 enemy needs 10 hits to kill a hero" (example numbers)
* Based on that formula, whenever you give a skill to a specific race, try to keep them inside that formula.
* If the dwarf takes 10% less damage, that means the enemy needs to deal more hits to kill him, to keep the balance, the dwarf would also need to deal less damage.
* If the elf has 5% chance to score a critical hit, that means it is more likely to kill an enemy with less hits (based on critical damage as well) so to keep the balance they'd need to be weaker to being damaged.

Experiment with different formulas depending on your game. How often a hero attacks is useful in some games but in others its not. When increasing levels, use the same formula but increase some numbers.

---
Tags: rpg
---


# Question
Title: Testing a Client's Camera in a Multiplayer FPS
I'm attempting to do a logic test regarding a client's camera in a multiplayer FPS in Unity and I'm a little uncertain of which way to implement the functionality.

**The scenario:**
\- I have a host and a client playing together.
\- I want to be able to tell if specific objects are visible from each player's camera, even on the edges of their screens.

For a local player this is simple, I just take the local camera reference, convert the target object's position to that camera's viewport space to see if it's within the bounds of the camera, and then raycast to test for blocking objects.

In a Host-Client setup, I've been attempting to ensure I do everything on the Host's machine, but the Client's camera does not exist in that context, only a third-person remote-player.

Possible solutions:

* I could pass the object's position to the client, convert it to the client's viewport space on their machine, then send that converted position back to the Host every frame, but this seems like a lot of network traffic for this. Furthermore it would use a stale client's camera position on the Host's up-to-date object position.
* Or I could do the full logic test on the client machine and only tell the host the result (e.g., success/fail). But from my understanding this is an ill-advised practice given how authority should be handled in a Host-Client setup...
* Or I could keep a camera object on the remote-player and synchronise that with the client's camera position and then do the test solely on the Host's machine involving that synced camera and objects.

I'm not sure which approach to pursue and would appreciate any input!

# Answer
> 1 votes
You can pass the direction vector and position of the camera to the server, since it only takes up 24 bytes. Then just take the position of the object, subtract the position of the camera you just received, normalize the resulting vector and take the dot product of it and the direction vector from the client.

This gives you the cosine of the angle between the cameras viewing direction and the vector from the camera to the angle. If this is less than the cosine of the FOV, then you know the object is visible.

But, since this solution requires you to know the position and direction of the camera, unless you set it on the server side and the client has no control over it, you might as well just do the visibility check on the client side and send the results to the server. The client could just fake the vectors, so there's no point in doing a less-precise test to make it just a bit more secure.

---
Tags: unity, camera, multiplayer, first-person-shooter
---


title: how to call function

text:
# Question
Title: how to call function
how do I get a function from another script and insert it into a button, I did this is giving this error

"Object reference not set to an instance of an object"

```
public Button Mybutton;

    void Indice(){
        if (index <= 0)
    {
        index = 0;
    }

    if (index >= 2)
    {
        index = 2;
    }

        if (index == 0)
    {
        Mybutton.GetComponent<Button>().GetComponent<MyScript>().MyFunction();
    }
    else if (index == 1)
    {
        Mybutton.GetComponent<Button>().GetComponent<MyScript>().MyFunction2();
    }
    else if (index == 2)
    {
        Mybutton.GetComponent<Button>().GetComponent<MyScript>().MyFunction3();
    }

```

# Answer
There are some errors:

```
Mybutton.GetComponent<Button>().GetComponent<MyScript>().MyFunction();

```
1. MyButton is correctly referenced ?
2. If Yes, just use: MyButton.GetComponent().MyFunction();

To get MyButton reference use:

```
GameObject MyButton = GameObject.Find("MyButton");

```
> 0 votes

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


# Question
Title: Player experience using a server in single player adventure to prevent cheating
I'm making a game where the user can sell items he finds during the the "single player" adventure on an online, I was looking at ways to prevent any malicious user to create rare and expensive items from scratch to sell them on the net.

I tried obfuscation but soon or later someone will successfully break into my code and I can't afford that, for obvious reasons.

Items are stored in files, so I thought about making client add a digital signature to generated files but I have to keep the key on the client machine, so same problem: if someone finds his key he can apply digital signature algorithm to generate the valid key for any file he creates.

So I ended up think the only secure option was to make the single player adventure interact with the server (everyone around here tends to say this is the way to go, like this subject, in my opinion the accepted answer explains it well).

But what about the user-friendly aspect?

My game is divided in two parts. Firstly the "real" single player adventure, where you can cheat all you want because everything is stored on your pc and server won't ever use it (~24h), then you beat the final boss and you're notified you're able to go online to battle against other players with the stuff you acquired on the single player map. At this point of the adventure, my idea was to record everything the player is doing in singleplayer mode onto the server, so whenever he plays a tournament, his stuff is verified.

I can't verify stuff just before a tournament begins because overpowered items can be obtained but are very rare, I want to systematically know if it was hardly-obtained or cheated.

Do you think it would be acceptable for a player to play "single player mode using internet" if he was told this will allow him later to rank up online and be

The single player map will be kind of mixed with the multi player area, but maybe I can think about a feature to play totally offline but then you won't be able to use your "online items" during this time.

EDIT: My app might outputs txt file (representing an item) with its corresponding digital signature, so I just need a way to be sure that it's my app (and not a modified copy) that has created a given file. That's why I'm reading about Trusted computing and Memory curtaining right now, but maybe I should head to security.stackexchange?

# Answer
> 0 votes
Any client-sided anti cheat solution is not going ot work. If it is executed on the client hardware, it's under the control of the player. There is no way around that. If you really want to prevent cheating, then the critical computations must run on hardware you control.

Several big name studios have created games which forced the player to be online at all times for no other reason than to prevent piracy. Consumers grumbled a bit about this, but accepted it eventually. You actually have a legitimate reason for always-online play, so you shouldn't have to worry much about backlash.

However, think carefully if this is really worth it from a cost/benefit point of view. Running one server is affordable, but running a server network across the world to ensure everyone has low latency can quickly become a considerable investment in both hosting cost and administrative work.

Adding a replay feature might be an interesting approach, though. It has benefit for the player because it could easily be enhanced to allow players to retroactively take videos of their greatest accomlishments. But you might want to make sure that recording **all** player activity is allowed according to applicable data protection laws. Please consult a lawyer for details about this. Anonymous wisecrackers on the internet like me are not a reliable source for legal questions like this.

Anyway, I am looking forward to playing your game.

---
Tags: game-design, user-experience, anti-cheat, single-player
---