# Question
Title: change one object into another, and then back again in Unity
For example, I would like to change a cube into a sphere, then change that sphere into a capsule, by pressing the up arrow. I would also like to be able to change in the other direction. Change the capsule into a sphere, then change the sphere into a cube, by pressing the down arrow. It would be great if i could add extra objects in, say a pyramid etc.

Ultimately i would want to do this with something like a seed, sapling, and tree. Each with there own properties.

# Answer
> 1 votes
You can do it using Prefabs and array of GameObjects.

For instance:

1. Declare an array of GameObjects

\[SerializeField\] GameObject\[\] MyObjects;
2. "Draw" and put each objects into that array (drag and drop using UnityEditor)
3. Attach a script to an empty gameobject (say: Player) and use Update function to change object

void Update() { if (Input.GetButtonDown("Fire1")) { Instantiate(MyObjects\[index\], Player.transform.position, new Quaternion(0,0,0,0); index = index +1; if(index \> MyObjects.Lenght) index = 0; } }

Look at :

1. https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
2. https://unity3d.com/fr/learn/tutorials/topics/scripting/arrays

# Answer
> 0 votes
If you have several behaviours you want to stay on the object and retain their data after the "metamorphosis", then it might be a good idea to have one game object without a renderer which carries all the shared behaviours and add child objects which represent the different appearances of the object. Deactivate all except the one you want to show at the moment.

But keep in mind that this solution is not very memory efficient. So if you have a very large number of such objects in the game at once (thousands) it might be suboptimal. Destroying and instacing might be better in that case. But if that happens a lot, memory fragmentation might become an issue. Object pools would be a solution, but that would again cost memory. You see, this rabbit hole goes deeper and deeper.

A compromise between both methods could be to retain the object and only exchange the Mesh of its MeshFilter / Sprite of its SpriteRenderer

---
Tags: unity
---


# Question
Title: Most Efficient Way to Check Player Distance from a Line?
I need to get the player's distance from a line (or the outside edges of an Gameobject, if that's easier) throughout their time in the game. I need the code to be fairly simple because I'm a novice (though if it's thoroughly explained, I can implement more complex solutions).

Is there an optimal way to do this that doesn't involve resorting to using the full formula for a point to a line? Because I think I might have some trouble implementing that in unity's system (translating to/from coordinate systems, maybe).

Thanks!

# Answer
> -1 votes
First of all, because I don't have a compiler right now:

```
List<GameObject[]> gList=new List<>();//this may have some problem, try initiating in your way

GameObject[] line1=new GameObject{g1,g2,g3}; //g-n is just some gameobject
GameObject[] line2=new GameObject{g4,g5,g6,g7};

gList.add(line1);
gList.add(line2);

GameObject[] targeted=null;

foreach(GameObject[] x in gList)
{
Vector3 f=x[0].transform.position;
Vector3 l=x[x.Length-1].transform.position;

//calculate distance as you know the math
//if(condition) //depending upon min or max or what-ever
    //targeted=x;

}

```

Maybe this will help

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


# Question
Title: Frequently change TextMeshPro text without garbage allocation?
Is there a way to frequently change a timer display created with TMP, without it generating garbage?

I'm currently using TMP.SetText(), which is supposed to not generate garbage, but it does.

# Answer
> 2 votes
What you could be seeing is, when running in the Unity Editor, TextMeshPro will allocate a string to display the formatted character array in the Inspector. This only happens when running in the editor. You can stop this by commenting out that line in the TMP\_Text.cs file located in the project's Packages/TextMesh Pro/Scripts/Editor. Like this:

```
        #if UNITY_EDITOR
        // Create new string to be displayed in the Input Text Box of the Editor Panel.
        //m_text = new string(m_input_CharArray, 0, index);
        #endif

```

I am on Unity 2019.1.1f1, TextMeshPro 2.1.6.

---
Tags: unity
---


# Question
Title: Going from a solo game project to a team project, how should I organize the new team and potential revenues?
I have been working on a game partial time for 2 years now, I've done the code and assets myself, but eventually I understood that I would not be able to have nice looking assets without spending a lot of time into it. And that greeting a new team member with graphic designer skills on this project would be a good idea.

My project is purely casual ATM. While I would love to earn a bit of money from it, my main goal is to have something fun to play with my friends (it's a couch console game) and I'm not sure what I want for the release of the game.

Now that I'm about to greet a graphic designer in the game project I'm excited but I want to do things right.

What should I define prior welcoming a second member in the team to make things work regarding the organization of the new team and the potential earnings?

What if things goes wrong and we split, when I have worked 900h on the game and him 20?

Any other tips from your experience regarding this aspect of welcoming a new teammate?

# Answer
> 3 votes
According to John Romero (minute 3:50 https://youtu.be/na4KHCO9lO8) you should prefer paying the artist directly for the job you need, and should not found with him/her a company unless you know him/her very well. Otherwise, it could "turn into legal garbage later" he says, according to his experience.

He suggests also you find someone with much more expertise than you in game development, cause they might give you heads up on what to do at each step of the development until release.

Just watch the video, Romero is really cool!

# Answer
> 2 votes
Even if it's casual, you have to protect yourself and your game. Having strong agreements and understanding of you and your teammates' relationship to the project will only make it less stressful for you to work with other people and vice versa.

So do these things:

* Incorporate (e.g., form an official company, pay the $50 or whatever to register the company name)
* Trademark your company / game name
* Get a formal agreement for your teammates (e.g., independent contractor agreements for contractors, etc -- so that you can define exactly what happens if he works 20 hours and then bails, who owns his work, etc).

/u/VideoGameAttorney in the reddit gamedev community gives lots of advice like this and more.

---
Tags: project-management, revenue
---


# Question
Title: Unreal 4 why does reducing scalability take so long to compile?
I have almost nothing in my scene--in fact, I reduced my scalability settings from "High" to "Medium" before even loading my level layout--and doing this has crashed the program multiple times. It didn't crash this time, but it is telling me it is compiling over 5000 shaders (!) and my objects' materials are not showing up in the viewport.

1) that is a ton of shaders, what shaders are these? I only made like 8 shaders.

2) What is making this take so long? it is taking forever, over 10 minutes already.

3) Is this normal?

# Answer
I'm afraid I've kept him waiting in vain.

I wish I could have just made one comment, but I found it useful to bring some pictures.

I have tested and modified all **scalability reference items** (https://docs.unrealengine.com/en-us/Engine/Performance/Scalability/ScalabilityReference) separately and together, but I did not get the result I had and what you are getting now.

**First person shooter project, blueprint of character** (*this was the project I had this same "problem" that you, when I was following this tutorial =\> https://www.youtube.com/watch?v=2sMwmEE3MuM&*)**:**

If I am not mistaken, it was when I activated this command for the first time (modifying all the options) that there was the delay, just like yours.

**Opening the project again, the moment I was modifying each option individually, the option below gave me a delay of 5 seconds, where the message "compiling shadows" appeared the moment I released the Q key:**

But only the first time, I tested again and it was immediate conversion, so...

I recommend not to take my answer as definitive, because when modifying only the effects option (in the individual tests), I had a delay of about 5 seconds in which the message "compiling shadows" appeared. And even after modifying everything, there was no further delay. That is, Unreal together with the computer must previously save data of these graphic changes, because there are changes, there is always this delay, but only the first time. **For example, cache, temporary files.**

My answer will only make sense, if and only if, you make those changes again and it does not take that long, but if you create a new project and do the conversion again, you have the delay. For then there will be a pattern in behavior.
> 2 votes

---
Tags: shaders, unreal-4, unreal, settings
---


# Question
Title: How do one NPC follow a succession of target points?
I have a project that contains 1 NPC (AI) and 2 target points. In the project I can make the NPC follow any of the 2 target points, but I can not get it to follow target point 1 and then target point 2, and that is what I would like to do, so that I can make a path.

**What I would like to know:**

*tp1 = target point 1* and *tp2 = target point 2*

**What I can do:**

In creating the variable that sets the target, I checked the box: **instance editable**. As you can see in the image, I can set the target in the level editor.

**Blueprint of the NPC:**

When I went to do the programming for him to follow the other target point (tp2) after reaching the first one (tp1), I did not get it in any way. No results appear with my search, which for me does not make any sense, because in the level editor I can easily.

**Looking at the level editor / Looking at the blueprint:**

I also tried using the **Get All Actor of Class**, but without success.

Link from where I also looked for help:

https://docs.unrealengine.com/en-us/Gameplay/HowTo/FindingActors/Blueprints

---

**EDIT 1 (Attempt based on ColdSteel's answer)**

**I created a variable of type array of actor called `varHelp`:**

As you can see, I added 2 elements to this array, but I can not edit any of the 2.

I researched a way to change this, until I got to this link:

https://answers.unrealengine.com/questions/813065/editing-this-value-in-a-class-default-object-not-a.html?sort=oldest

Unfortunately it caused an error in the code, causing me to give up for now and look for another way to solve my main problem.

**Although I created 2 elements in the array, none of the elements appears in the level editor:**

**But I can create new elements and define them as the desired target points:**

**However at the time of defining them in the construction script I again error in some detail:**

---

**EDIT 2 (Another attempt, based on Stephen's answer)**

**With the help of Stephen I discovered how to promote a variable (right click button):**

**New blueprint:**

But I still have not got the expected result, see below an explanation of what happens:

Red code (Simple Move) =\> *The NPC moves toward target point 2, without first passing target point 1.*

Blue code (AI MoveTo) =\> *Nothing happens.*

---

**EDIT 3 (Attempt made thanks to the progress I made with the answers of ColdSteel and Stephen)**

This time I managed to get the NPC to do the correct path, but it is not dynamic since the NPC does not go directly from target point 1 to target point 2.

**New blueprint:**

I know the loop executes all at once, so the value registered in the function to move the NPC was always the last.

With the creation of two Boolean variables, I was able to "circumvent the operation of the loop".

With the delay I assure you that it will allow NPC time to arrive at target point 1, only to go to target point 2.

*I know that what I did is far from ideal, to have an idea I would have much more problems if there were more target points.*

---

**EDIT 4**

Now I can get the NPC to go to target point 2 immediately after reaching target point 1.

**I added a collision box to target point 1:**

**Changes in the blueprint:**

Important to inform, that such a loop was not accused as infinite, since I added a collision box only to target point 1.

*Now I have to know how to make a code for any amount of target points.*

---

**EDIT 5 (Finally I did it!)**

For this I used the "Do N" and added an integer variable that will serve as counter.

**Blueprint:**

Basically, every time the NPC collides with a target point that has collision box, the loop with the "Do N" will be reset, but with the help of the integer variable that serves as a counter, the subsequent target point will be set correctly.

*I do not know if this form I found is the most effective and functional. Please feel free to comment and correct me.*

# Answer
> 0 votes
First, after the **Event BeginPlay**, you will use the function **Get All Actors Of Class**. This function will output an array, just right click on the output variable of the function to **Promote to Variable**:

After that, you will use a **ForEachLoop** more a function **DO N**, and before that you should create an **integer variable** (default value is 1) to command the function **DO N**:

The loop will execute until the number of target points is finished, without the function **DO N** the NPC would always be taken towards the last target point. So if you have 5 target points, and do not have the function **DO N**, the NPC would go straight to target point 5 without first going through any of the other target points.

Since the value of the integer variable is 1, at the first execution of the loop, what is inside the **DO N** will only be executed once, which is what matters:

Once time, then the target point to follow is 1.

The way I have made the next target point to be defined is that when it hits a target point, the integer variable is raised by 1 and the loop restarts.

For this to happen correctly, you must add a **box collision** to all target points except the last one:

This way you can use the **Event ActorBeginOverlap**.

In **EventActorBeginOverlap**, you use the **CastTo TargetPoint**, and with the help of a **sequence** you reset the function and increase the value of the **integer variable**, in order to start the **ForEachLoop** again:

Reset **DO N**:

**ForEachLoop** start again:

***You do not need to use print.***

That way, as soon as the NPC collides with target point 1, the **DO N** will be reset, the **integer variable** will increase its value by 1, and the **ForEachLoop** will start again.

Now, the **DO N** will execute 2 times, setting target point 2 as goal. And so on...

# Answer
> 1 votes
So your problem is... that you dont see TargetPoint2 in cast list ? - if so then it behaves as Intended because both TP and TP2 are instances of class TargetPoint. To distinguish between you TP placed in world - you could use tags or anything else just not the Cast.

Cast would work only if you made a Class for each TP like TP1 that inherits TargetPoint, TP2 that inherits TargetPoint and so on.

# Answer
> 1 votes
If you are trying to get an AI to move to two simple locations then use the AIMoveTo Function.

As you can see, it has an on success execution pin so when you successfully get to the first location, you can execute the movement to the second.

-- EDIT FOR WHAT SOME OF WHAT YOU'VE TRIED --

When you do a Get All Actors of Class, you are doing just that. UE4 is finding everything that matches the Target Point Actor but after this, you're only getting the first entry (0) in the array.

To get all Target Points you'd need to loop through that array and match the result with what is in the array in your AI pawn and if it's a match, move it. Get Display Name is probably the best option here.

---
Tags: movement, ai, unreal-4
---


# Question
Title: Easy way to generate colour-per-vertex models for input to Blender
I procedurally generate 3D planet models that I would like to import into Blender.

I use colour per vertex rendering in my shaders (In practice, I use the same colour for all vertices of a face, but my vertex attributes include RGBA.)

I like generating wavefront **.obj** files, because the syntax is so easy. But wavefront obj does not let me specify colour per vertex, or colour per face. Instead, the entire object is coloured with a material from the material-library that accompanies the obj geometry file.

I've looked into collada **.dae** as well, but frankly, that seems like a very complex format, and it still seems to work with material libraries, like the .obj format does.

Is there an easy to generate 3d model format that lets me specify a colour per vert (or face) without material libraries, and can be imported into Blender?

# Answer
> 0 votes
So, Stanford's .PLY Polygon File Format is the winner here.

Although, after the import into Blender, some actions are required to actually see the colours.

PLY supports colour-per-vertex and colour-per-face, but I've found that Blender can only handle the colour-per-vertex files.

---
Tags: color, file-format, vertex-attribute, face
---


title: How to use alpha channel with emission?

text:
# Question
Title: How to use alpha channel with emission?
I am trying to assemble scene assets and one asset needs an emission material where only the white part emits light:

I set up a texture with a simple (air-quotes) "mask" for the window...

...and tried to make only the white part emit light. This attempt blew up the entire material though (verified by checking model, adjusting intensity). I also tried plugging in the base texture directly but when I turned up the intensity, it looked like the black frame became a deeper black as well, which is not what I want.

Changing the intensity with just the white input and scalar multiplier does not reveal the black metal portion of the diamond pattern. **How can I update this graph so that only the white part glows?**

I want to use the texture to light the scene but may settle for filler lights, since it could be overkill. Here is the original scene I put together in Blender. The camera will be fixed like this. Note also that there are 9 other windows that emit light in this scene but are made invisible:

Thank you to everyone who takes an interest in helping me solve this problem, your time is appreciated.

# Answer
If you have an Alpha channel on that texture, or some other channel to use as a mask - you can fake Alpha for emission by just multiplying the BaseColor (RGB) with your Alpha or Mask. multiplication and then just plug it into the emissive color on the material
> 0 votes

---
Tags: lighting, unreal-4, unreal, materials, glow
---


# Question
Title: Efficient collision detection of sphere with wall
I'm building a first-person game where up till now the player has been represented as a dimensionless point; this makes collision detection really easy, as I can just cast a ray along their velocity vector, find the distance to the nearest obstacle, and clamp the magnitude of the displacement vector to that maximum distance on every frame.

Unfortunately, though, this runs into occasional glitches where a player can jump through a corner between two walls, especially if there isn't anything on the other side to collide with--if the player is facing exactly into the intersection, then the projected ray passes right through the corner without registering a hit on either adjacent wall.

To fix this, I want to instead model the player as a finite-sized sphere, which cannot fit through floating-point-error-sized gaps. (This will also have the nice side effect of forcing a minimum standoff distance for the camera from the walls, so you can't stick your eyeball right up against the surface and fill the screen with a single texel.)

Now, checking whether or not that sphere currently intersects a wall is easy. However, I find myself stuck on how to check whether the sphere *will* intersect a wall if translated in a certain direction--and if so, *where*.

All of my walls are axis-aligned, which I expect should simplify things.

Any tips?

# Answer
> 4 votes
I am assuming you have a sphere of radius r between two timeframes, at position $$x(t), \\,\\,t \in \left\[0, 1\right\]dt$$ and want to know whether there exists a time t such that the sphere is touching the wall. A wall is a plane, in general. So it can be defined using a position vector and the normal versor $$ x\_p,\\,\\,\widehat{n} $$ See figure. We assume that the sphere is moving at a constant velocity during the two frames x(0) and x(1), that is $$ x(t) = x(0) + t \\,dx, \\,\\,\\,\text{with}\\,\\,dx = \left( x(1) - x(0) \right) $$

The conditions for collision are

* The two objects are overlapping geometrically at some time t $$ \left(x(t) - x\_p\right) \cdot \widehat{n} \< r $$
* The sphere is approaching the wall (velocity is towards the wall). $$ dx \cdot \widehat{n} \< 0 $$

The last equation is easy to check. The former one has to be solved for t, using the linear motion assumed above. The solution is $$ t = \frac{ r \\,\\,–\\,\\, x(0) \cdot \widehat{n} + x\_p \cdot \widehat{n} }{dx \cdot \widehat{n} } \\;\\;\\; \\& \\;\\;\\; t \in \[0, 1\]dt $$ **remember to check whether your t occurs within the timeframe,** \\$ t \in \[0, 1\]dt \\$. From t calculated here you can get the exact position x(t) where the sphere starts touching the wall.

I hope there are no mistakes in the computation. Let me know if it works.

# Answer
> 1 votes
There are 2 ways of handling this

The first and the most primitive way is to substep the collision checks: for example if your player is about to move N meters for the current tick: and your sphere radius is M... you could subsequently move your player by amount of (for example) M/2 up until it reaches the N or hits a wall - this is easy to implement - and works fast enough, I am using it for the Collision Detection Avoidance in my game it handles hundreds of collisions like that without any CPU performance hit.

The second solution is to implement a sweep function - where you will sweep the sphere from start to end point - or up until the collision. This requires a bit more sophisticated mathematics.

This article may help you to get started: https://www.gamedev.net/forums/topic/526931-how-do-you-do-swept-sphere-vs-line-segment-intersection-tests/

In case you wonder here is the implementation of the first way with 200 moving agents - please note the Game Time (which is the actual CPU time) the overall FPS is low because my GPU cant handle that much animated skeletal meshes https://drive.google.com/file/d/17vYRyQxUtEN3QkUyx1nx9sx4oWsx\_B0s/view?usp=drivesdk

---
Tags: collision-detection, movement, raycasting, bounding-spheres
---


# Question
Title: Unity: Animation With Motion Now running in place
I am new to unity. I am trying to assemble a character that walks forward, stops, and walks forward again when I maneuver the joystick (ps4 controller) accordingly.

I have the whole thing pretty much set up...

However, my animations broke at some point. Initially, when I added the animations to my character, the character moved with the animation according to the motion encoded in the animations (all of which were auto-rigged at Mixamo...so I am almost certain the bug is downstream in something I did or enabled somehow).

Now, every animation has the character running, turning, jumping etc. in place. Meanwhile, the animation subscreen (when I inspect the clip) shows the character running forward. I tried implementing some fixes I found online; I changed the root motion node to Root Transform, for instance...and that is when the most confusing thing happened: a few of the animations started working...but all of the animations showed the character running in place in the subscreen...so now I have no idea what is happening.

Additionally, the animation clips which do not move the character actually transform the character back to the starting position (actually, that isn't correct--I moved the character into the air to test this; the clips without motion transform the character back to the starting position on the ground).

I have disabled all scripts...so have I somehow broken the animations...??? Re-Importing the animations does not fix them either.

---

Here are the images of my character settings, then the controller, and then an animation clip which shows the character moving forward in the sub-clip and where motion information is clearly present...

# Answer
> 0 votes
The problem is caused by: Apply Root Motion unchecked in the animator and "Loop pose" checked on the animation inspector. Which is a setting best suited when you move your character programatically, but it is then harder to get the natural foot cycle.

If you want to keep just part of the root motion, you can "bake into pose". For example Bake into pose XZ will not apply the root motion over axis X and Z.

See : https://docs.unity3d.com/Manual/RootMotion.html

# Answer
> 1 votes
The problem here is that the animation has it's position set to somewhere around (0,0,0). So, whenever you run the animation, the position is set to 0 (about). I have had this problem in the past, but the way I solved it was by making it a parent of a GameObject. The animation runs on the child, and the movement is run on the parent.
Note: You could switch the child and parent around.

---
Tags: animation, unity
---


title: User Leveling System

text:
# Question
Title: User Leveling System
I've already asked this before, but I just wanna encode this again with a new leveling format. What I want to do is that, the user will gain exp and once they leveled up, their previous experience will be added to their current exp.

So, to put it in a Scenario it goes like this: User1 is on a Level 1 with an exp\_needed of 1000 to reach level 2. He gained an exp of 1000, so he is now on level 2 with a current\_exp of 1000 and an exp needed of 1,400. Or if User1 gained an exp of 1,100 he is on level 2 with a current\_exp of 1,100 and 1,400 exp needed. And so on, depending on the algorithm. But I get a result of -900/1,400 if the user gains 1,100 exp.

Here is the code below:

```
while($user->curr_exp >= $user->exp_needed){
       $user->curr_exp -= ($user->exp_needed) + $user->prev_exp;
       $user->prev_exp = $user->exp_needed;
       if($user->level <= 19){
       $user->exp_needed = $user->prev_exp * 1.4;
       }
       elseif($user->level >= 20 && $user->level <= 39){
       $user->exp_needed = $user->prev_exp * 1.1;
       }
       elseif($user->level >= 40 && $user->level <= 59){
       $user->exp_needed = $user->prev_exp * 1.05;
       }
       elseif($user->level >= 60 && $user->level <= 79){
       $user->exp_needed = $user->prev_exp * 1.04;
       }
       elseif($user->level >= 80 && $user->level <= 99){
       $user->exp_needed = $user->prev_exp * 1.03;
       }
       elseif($user->level == 100){
       $user->exp_needed = $user->exp_needed * 0;
       }
       $user->level += 1;
       $user->save();
      }

```

Any ideas how to deal with this? Thanks.

# Answer
I think your levelling system in unnecessarily complicated because it makes the levelling's thresholds dependent on the player's current exp.

First, I propose to set fixed levelling thresholds, that you decide beforehand. For example, the first 20 levels need `1000` exp, `1400` exp, `1960` exp ... and so on. You can save them on an array for example.

Now suppose the player is at level 1, with 100 exp, and needs `900` exp to get to level 2. He gains `1000` exp, and now he is at `1100` exp, so it's promoted to level 2. The threshold for achieving level 3 is set to `1400`, for example.

You can proceed in two ways:

1. Keep his current exp to 1100, so now he will need only an additional `1300` to get to `1000+1400=2400` exp.
2. Reset his exp to `0`, and now he needs to reach `1400` exp to get to level 3.

The second solution has the disadvantage that you lose track of the actual total exp the player made because you are throwing away any additional exp he gained when levelling up. For that, you can use a second variable `curr_total_exp` which is never reset.
> 1 votes

# Answer
100 level is max so we add a check to prevent infinite loop.

```
while ($user->curr_exp >= $user->exp_needed && $user->level < 100) {

```

Subtract only XP needed to level-up:

```
    $user->curr_exp -= $user->exp_needed;

```

Add XP from this level to previous XP:

```
    $user->prev_exp += $user->exp_needed;

    if ($user->level < 20) {
        $user->exp_needed = $user->prev_exp * 1.4;
    }

```

if level less then 20 we don't need to check if it's greater or equal because we have `else`

```
    elseif ($user->level < 40) {
        $user->exp_needed *= 1.1;
    }
    elseif ($user->level < 60) {
        $user->exp_needed *= 1.05;
    }
    elseif ($user->level < 80) {
        $user->exp_needed *= 1.04;
    }
    elseif ($user->level < 100) {
        $user->exp_needed *= 1.03;
    }
    else {
        $user->exp_needed = 0;
    }
    $user->level += 1;
    $user->save();
}

```

We do not modify `exp_needed` based on `prev_exp` because we want a predictable exponential sequence:
1000, 1400, 1960, 2744...
instead of this:
1000, 1400, 3360...

If you want to calculate it based on *all already earned* XP, leave the code as is.
> 0 votes

---
Tags: algorithm
---


# Question
Title: How to preserve EGL context when pausing Android ndk app
I am trying to improve openframeworks so that the GL context is preserved when pausing and resuming my game. So that I don't have to reload all textures after each pause. I don't expect you to know openframeworks code, I'll explain my problem independent of it.

I have java activity which loads a main\_layout.xml file with a RelativeLayout inside another RelativeLayout. Then I instantiate a GLSurfaceView and add it to the inner RelativeLayout using `glContainer.addView(glView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));`. In onPause function, I call `glView.onPause();` on GLSurfaceView and in onResume, I call `glView.onResume();` on GLSurfaceView.

This code works but it destroys the gl surface in `onPause` (`GLSurfaceView.surfaceDestroyed` gets called on my `GLSurfaceView`, which is extended to `OFGLSurfaceView`, so that I can intercept this call).

To fix this, I added call to `GLSurfaceView.setPreserveEGLContextOnPause` with param 'true' to initialization of my `GLSurfaceView`. Now I see only black screen after pausing and resuming the game. I found out, that I can fix this by removing the `GLSurfaceView` from parent `RelativeLayout` and adding it back right away in `onResume` function: `glContainer.removeView( glView ); glContainer.addView( glView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT) );`. This however destroys the gl surface again and forces me to reload textures.

There are no reinstantiations of either one of the `RelativeLayout`s or the `GLSurfaceView` (I checked it by looking at the code and then checking identities of those instances with `System.identityHashCode`).

main\_layout.xml:

```
xml
<?xml version="1.0" encoding="utf-8"?>
   <RelativeLayout android:id="@+id/relativeLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android">
        <RelativeLayout android:id="@+id/of_gl_surface_container" android:layout_width="fill_parent" android:layout_height="fill_parent"/>
        <!-- add here other views' layouts -->
    </RelativeLayout>

```

Code in OFAndroidLifeCycle.java which handles events received from Activity:

```
java
public static void glCreateSurface()
{
    if(mGLView == null)
    {
        mGLView = new OFGLSurfaceView(m_activity);

        OFGLSurfaceView glView = getGLView();

        glView.setPreserveEGLContextOnPause( true );

        ViewGroup parent = (ViewGroup)glView.getParent();
        if( parent == null )
        {
            ViewGroup glContainer = getActivity().getSurfaceContainer();
            glContainer.addView(glView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        }
    }
}

public static void glPause()
{
    OFGLSurfaceView glView = getGLView();
    if( glView != null )
        glView.onPause();
}

public static void glResume(ViewGroup glContainer)
{
    OFGLSurfaceView glView = getGLView();

    if( glView != null )
    {
        glView.onResume();

        glContainer.removeView( glView );
        glContainer.addView( glView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT) );
    }
}

```

After working on it a bit, I improved it so that the `GLSurfaceView` is being paused and resumed from `Activity.onStop` and `Activity.onStart` respectively.

Problem remains and I was able to better locate the source of the problem. The surface is destroyed between `onPause` and `onStop` events, or better to say right before `onStop` event. Here is the stack trace of the call that reports that the surface was destroyed.

```
java.lang.Exception
    at cc.openframeworks.OFGLSurfaceView.surfaceDestroyed(OFAndroidWindow.java:251)
    at android.view.SurfaceView.updateSurface(SurfaceView.java:639)
    at android.view.SurfaceView.windowStopped(SurfaceView.java:222)
    at android.view.ViewRootImpl.setWindowStopped(ViewRootImpl.java:1348)
    at android.view.WindowManagerGlobal.setStoppedState(WindowManagerGlobal.java:623)
    at android.app.Activity.performStop(Activity.java:7151)
    at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:4158)
    at android.app.ActivityThread.handleStopActivity(ActivityThread.java:4210)
    at android.app.ActivityThread.-wrap24(Unknown Source:0)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1646)
    at android.os.Handler.dispatchMessage(Handler.java:105)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6710)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:770)

```

This corresponds to android-26 sdk sources.

I am still not sure where the problem is. I consider three alternatives:

1. problem with android platform version (I could use some advises here)
2. the way `openframeworks` interfaces with the `GLSurfaceView` might be somehow invalid (overriding some functionality)
3. other problem in propagation of that `preserveEGLContextOnPause` flag, I will need to read through the android code to better understand how that works

I found it! Summary:

* The point is that GL objects do not get destroyed when `GLSurfaceView.surfaceDestroyed` is called. I kept the `setPreserveEGLContextOnPause` on true and disconnected any signals to native code from `GLSurfaceView.surfaceDestroyed` and now the textures are good after minimizing and restoring the window.

So I guess that the surface and probably also EGL context can be destroyed and textures will still remain in GL context or something.

So now I just need to do some cleanup work and find the real indicator that GL objects were destroyed. And maybe try to verify that this approach really is the correct one, but I am confident I am on the right track. I might post more info once I do some more work on it.

# Answer
> 4 votes
Introduction to terminology and description state transitions are in the Android Understand the Activity Lifecycle guide. There are basicaly three states:

First state is CREATED, which is reported through the onCreate and onDestroy callbacks in Activity class. This state is entered at the beginning of the lifetime and exited at the end of the lifetime. Android app should be able to save its state during onDestroy and restore its state (if available) in onCreate so that Android can quickly and cleanly reload the app when for example screen configuration changes. These quick restarts do not really apply to games, the expected behavior from games is that they restart as rarely as possible.

If the Activity is in the CREATED state, it can enter second state - STARTED, that is reported through onStart and onStop callbacks of Activity class. The app can enter STARTED state multiple times during its lifetime. STARTED means that some part of Activity window is visible to user. Activity is not STARTED when we minimize the Activity or switch to another Activity. This is when EGL context is lost in default configuration and when Activity should be running on low resources without animation and rendering updates.

Third state is RESUMED, which can be entered from CREATED state and is reported through onResume and onPause callbacks of Activity class. This is not that useful, it basicaly means that the Activity has input focus. So for example in multiwindow mode, where two Activities are visible, both of them are CREATED but only the one that received input last is in RESUMED state. For games this basicaly means that when we exit RESUMED state (onPause is called), we should pause the gameplay. When the game enters the RESUMED state, we should do nothing but wait for user to manually unpause the game when he is ready to continue playing.

Now to the technicalities. When we are making game in Android, we can use either NativeActivity that I am not familiar with, or we can use standard java Activity class and request updates and renders from native code using NDK JNI calls. In that case, we will be usualy using GLSurfaceView. That is basically a UI element that calls our custom callback GLSurfaceView.Renderer.onDrawFrame in which an OpenGL context is available and we can make OpenGL calls and whatever we draw during this callback will be visible in the GLSurfaceView. We need to call GLSurfaceView.onPause when Activity exits STARTED state (Activity.onStop is called) and call to GLSurfaceView.onResume when Activity enters STARTED state (Activity.onStart is called).

Historically, there could be only one OpenGL surface existing at a moment, so when apps were switched, only the app in foreground had valid opengl context and apps in background had to restore the state of opengl context (reload textures, etc.) when they came to foreground. Since api level android\_11, more that one opengl context can exist (it needs to be requeste by the app), but we still need to be able to handle the case when system decides to kill either the opengl context or the whole app due to system resources constraints. I am not sure if devices with api android\_11 and higher may even kill only the opengl context or if they kill the whole app every time they run out of system resources. It might be useful for you to read more about this if you would like to avoid the necessity to reload resources on demand in your project.

Now we need a way to tell that opengl context was destroyed so we can reload all the textures and other resources. To do that, we can use callback GLSurfaceView.Renderer.onSurfaceCreated on renderer that is assigned to our GLSurface view. The renderer does not receive any callback when surface is destroyed, only when it is created. But that is not a problem. While the surface exists, the onDrawFrame callback is being repeatedly called. When the app goes to background, the onDrawFrame will not be called anymore. When the app enters foreground, either onSurfaceCreated will be called first, in which case we know that we need to reload everything before next draw or it will not be called and onDrawFrame is again repeatedly called in which case we are good to draw with old opengl resources.

Openframeworks was using GLSurfaceView.surfaceDestroyed callback to determine that opengl context was lost. But according to my testing, this is not how it should be used. That callback is called somewhere around onPause and onStop when app is going to background. And this happens even when the opengl context is not in fact destroyed. So don't use that. Second problem I had was that various callbacks in the code were a bit confused, so the rendering might sometimes get paused by custom bool variable, which caused the black screen in some test cases.

To tell Android to try to preserve the opengl context even when minimizing the app, we need to use method GLSurfaceView.setPreserveEGLContextOnPause - call it with parameter 'true' after the GLSurfaceView was instantiated. This will cause that GLSurfaceView.Renderer.onSurfaceCreated will not be usually called after minimizing and restoring the app.

I am glad I finaly solved this riddle, so back to gameplay programming for me :-).

# Answer
> 0 votes
That your context gets discarded when the user switches to a different app is a feature to free up memory for the different app.

However pause can also mean pausing the game and seeing the pause menu from witch you can edit options etc. This is the meaning that you want I believe.

If you want to do that then you don't need to call `onPause` but instead swap over to a different "game layer" which is a simple menu just like the main menu.

The most straightforward way to do so in any framework would be to add a `switch(layer)` in `update()` and `draw()` that dictates what gets done in each layer. So when the player hits the pause button you do `layer = PAUSE;` and the next frame will be the pause menu which you can add a nice animation to to make it swipe in.

A quick gander through the doc of openframeworks shows a way to switch the current main window. But I'm not sure that is fully what you want.

---
Tags: android, opengl-es, ndk, egl
---


title: Why WebGL Audio isn't working?

text:
# Question
Title: Why WebGL Audio isn't working?
I need to download audio (OGG, Mp3 or wav) from URL and play it.

In Editor is working fine, and also in stand alone build.

But not in WebGL build.

My Code:

```
    // Here audio is downloaded based on audioURL
...
      WWW data = new WWW(audioURL); yield return data;
            AudioClip downloadedClip = data.GetAudioClipCompressed(false, AudioType.OGGVORBIS) as AudioClip;
            if (downloadedClip != null)
            {
                _audio.clip = downloadedClip;
            }
...

public void PlayAudio() {
    // Here clip is play
            if (_audio.clip != null && _audio.isPlaying == false)
                _audio.Play();
            else
                Debug.Log("Background music not present!");
            _audio.loop = true;
}

```

To download clip i've used also (instead first code part):

```
 using (UnityWebRequest www2 = UnityWebRequestMultimedia.GetAudioClip(audioURL, AudioType.OGGVORBIS))
        {
            yield return www2.SendWebRequest();

            if (www2.isHttpError)
            {
                Debug.Log(www2.error);
                LogAdd(www.error, true);
            }
            else
            {
                AudioClip downloadedClip = DownloadHandlerAudioClip.GetContent(www2);
                _audio.clip = downloadedClip;
            }
        }

```

For some reason, audio in webgl isn't played.

EDIT 1: When uploading MP3 , error (also in editor) is:

> Streaming of 'mpeg' on this platform is not supported UnityEngine.Networking.DownloadHandlerAudioClip:GetContent(UnityWebRequest)

# Answer
> 0 votes
After upgrading to LTS 2018.4 using the same code above, it worked. Maybe there was a bug in 2018.3 ? At the moment works with Mp3 and not ogg.

```
using (UnityWebRequest www2 = UnityWebRequestMultimedia.GetAudioClip(audioURL, AudioType.OGGVORBIS))
        {
            yield return www2.SendWebRequest();

            if (www2.isHttpError)
            {
                Debug.Log(www2.error);
                LogAdd(www.error, true);
            }
            else
            {
                AudioClip downloadedClip = DownloadHandlerAudioClip.GetContent(www2);
                _audio.clip = downloadedClip;
            }
        }

```

---
Tags: unity, webgl
---


# Question
Title: how to detect touch on instantiated prefabs in unity
I have instantiated objects (that have `collider2D` attached) in a grid of `9x13`. Now I want to detect a touch on each object individually. I am confused about how to do it. Either write script separately on prefab or do it in my `gameController` script? Also what is the method to do it?

Here is my code for instantiating:

```
    public GameObject bubble;
    int row;
    int col;
    float x;
    float y;

    void Start ()
    {
        x = -2.4f;
        y = 2.95f;
        row = 13;
        col = 9;

        Vector2 position = new Vector2(x, y);

        for (int i = 0; i < row; i++)
        {
            for (int j = 0; j < col; j++)
            {
                Instantiate(bubble, position, Quaternion.identity);
                position.x += 0.6f;
            }
            position.x = x;
            position.y -= 0.6f;
        }
    }

```

# Answer
The simplest way is to give your prefab a suitable collider, and attach a script to the prefab that looks a bit like this:

```
public class TouchDetector : MonoBehaviour {

    // Called when a collider attached to this game object is pressed.
    void OnMouseDown() {
        // Put the actions you want to perform to respond to the touch here.
        Debug.LogFormat("Object {0} got touched!", gameObject.name);
    }
}

```

When you build, Unity looks for any MonoBehaviour scripts that have `OnMouseDown` or other mouse-related messages. If it finds them, then it automatically fires a ray into your scene every frame to see what collider it hits first, and then sends the corresponding up/down/enter/exit messages.

This also works for a single finger touch or stylus. I don't know if it handles multitouch in a useful way.

The downside is that this is a very generic solution, so it might be more heavyweight than you need (maybe you don't care about enter/exit/up messages at all, or only some of your objects need the pointer interaction, or you have gobs of objects and don't want to put a receiver script on every one of them...)

So, in many cases you can make this more efficient by firing the ray yourself, only when it's appropriate for your game rules.

Here we could have a single script that fires a ray for each touch and detects what it hits - without needing a receiving script on each prefab instance:

```
public class TouchManager : MonoBehaviour {

    public LayerMask touchableLayers;

    void Update() {
        var camera = Camera.main;

        int count = Input.touchCount;
        for(int i = 0; i < count; i++) {
            var touch = Input.GetTouch(i);

            var ray = camera.ScreenPointToRay(touch.position);

            RaycastHit hit;
            if (Physics.Raycast(ray, out hit, Mathf.infinity, touchableLayers)) {
                // Pur the actions you want to perform to respond to the touch here.
                Debug.LogFormat("Object {0} got touched!", hit.collider.gameObject.name);
            }
        }
    }
}

```
> 0 votes

# Answer
I've done this in my game controller script (but you don't have to). Whichever makes more sense to you, I think.

One method you can use is OnTriggerEnter.

Your could use code that goes something like the below. It will let you tag all the objects with one tag but you can do something with each individually -- if you want to do the same thing with each object but just have it happen only when that specific one is touched.

void OnTriggerEnter(Collider collider) {

```
    if (collider.gameObject.CompareTag("insert_tag_of_gameobject") {

```

do whatever you'd like to do with the object you've collided with }

If you only want to do something that is specific to a single object when you hit it then maybe try using something like this:

//this code says that when you collide with the object that the collider is attached to, find that object (then insert code that does whatever you want to do with the object) void OnTriggerEnter(Collider collider) {

```
    objectName = GameObject.Find("object_name");

```

do whatever you'd like to do with the object }
> 0 votes

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


# Question
Title: Shortest distance to chain of line segments
I'm trying to calculate the distance of the player to a few lines that intersect two points, and return the smallest distance (i.e. tell me which of the lines the player is closest to/how far the player is from it at any given point in time). The lines are finite, my game is in 3D.

I'm looking for a solution that doesn't involve just picking the midpoint of the line segments and detecting the shortest distance from the player. I can do that but ideally, I'd like something more precise.

I have tried to find a suitable formula but keep coming across ones that are for infinite lines rather than finite segments.

# Answer
> 1 votes
To find the distance of our point \\$\vec P\\$ to the line segment between points \\$\vec A\\$ and \\$\vec B\\$, we need the closest point on the line segment. We can represent such a point \\$\vec Q\\$ on the segment by:

$$\vec Q = \vec A + t (\vec B - \vec A)$$

for some scalar value \\$ 0 \le t \le 1 \\$, which ensures our point doesn't shoot off the ends of the segment.

To make our math simpler, let's define the "span" of the segment \\$\vec S = \vec B - \vec A\\$ and the "wander" of our point from the start of the segment, \\$\vec W = \vec P - \vec A\\$. This is effectively shifting the start of the segment to the origin, without changing any of the distances involved, so we eliminate one extra variable from the problem.

The squared distance of our point \\$P\\$ from the point \\$t\\$ of the way along the segment is then:

$$\begin{align} D^2 &= \left(\vec W - t\vec S \right)^2 \\ &= W^2 - 2t\left(\vec W \cdot \vec S\right) + t^2 S^2 \\ \frac {d D^2} {d t} &= -2 \left(\vec W \cdot \vec S\right) + 2 t S^2 \end{align}$$

We differentiate with respect to \\$t\\$, and set the result to zero to find the local minimum of this function at the closest point along the segment, \\$t = t^\*\\$

$$\begin{align} -2 \left(\vec W \cdot \vec S\right) + 2 t^\* S^2 &= 0 \\ 2 t^\* S^2 &= 2 \left(\vec W \cdot \vec S\right)\\ t^\* &= \frac{\vec W \cdot \vec S} {S^2} \end{align}$$

Now we can use this to find our closest point, like so:

```
Vector3 ClosestPointOnLineSegment(Vector3 segmentStart, Vector3 segmentEnd, Vector3 point) {
    // Shift the problem to the origin to simplify the math.
    var wander = point - segmentStart;
    var span = segmentEnd - segmentStart;

    // Compute how far along the line is the closest approach to our point.
    float t = Vector3.Dot(wander, span) / span.sqrMagnitude;

    // Restrict this point to within the line segment from start to end.
    t = Mathf.Clamp01(t);

    // Return this point.
    return segmentStart + t * span;
}

```

Now you can find the closest point to the player by...

```
int closestIndex = -1;
float closestSquaredRange = Mathf.infinity;

for (int i = 1; i < points.Length; i++) {
    var closestPoint = ClosestPointOnLineSegment(
                            points[i-1],
                            points[i],
                            player.position
                       );

    var squaredRange = (player.position - closestPoint).sqrMagnitude;

    if(squaredRange < closestSquaredRange) {
        closestSquaredRange = squaredRange;
        closestIndex = i - 1;
    }
}

// Closest segment is the span from points[closestIndex] to points[closestIndex+1]

```

---
Tags: unity, c#, geometry, linear-algebra
---


# Question
Title: Detecting collision between 2 rotated rectangles with limited parameters
Are there any function that can detect collisions between 2 rotated rectangles in javascript with this kind of information:

```
r1 = {x:0,y:0,w:2,h:2,transformX:5,transformY:Y,rot:30}
r2 = {x:1,y:1,w:2,h:2,transformX:5,transformY:Y,rot:30}
//rot is degrees
function rectColliding(rect1,rect2){
  //Code
}

console.log(rectColliding(r1,r2))

```

# Answer
Since you get no answers I will try to help. I am not super proficient in math etc, but your best approach would be to check if one or more of the vertices of one of the rectangles are inside the other rectangle BUT not all of them obviously.

So you will have to map your rects vertices taking the angle in to consideration... and then use a raycast/raytrace algorithm to determine if the vertices are inside other rect.

I hope this overview will get you started: https://en.m.wikipedia.org/wiki/Ray\_casting
> 0 votes

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


# Question
Title: Click on an isometric plane and obtain normal coordinates
I have photos distributed as cells. When I click, I get the corresponding row and column. console.log("Col:" + X + "Row:" + Y);

When applying an isometric view conversion like this:

ctx.translate(0, 300); ctx.scale(1, 0.5); ctx.rotate(-45 * Math.PI /180);

I do not know what mathematical formula applies to get the coordinates correctly.

---

Based on feedback so far, I've been able to get this far. The x coordinate seems to work fine, but the y coordinate not.

```
Isometrico();

function Isometrico(){
     ctx.translate(0, 300);
     ctx.scale(1, 0.5);
     var radianes= -45 * Math.PI /180;
     ctx.rotate(radianes);
}

/*
document.addEventListener("mousedown", function(e) {
             CorIsometrico( e.offsetX, e.offsetY);
});
*/

/*
function CorIsometrico(xI,yI){
     //RESPUESTA yI=yI-300;
     yI = yI * 2;
     xI = xI * Math.cos(45) - yI * Math.sin(45);
     I  = yI * Math.sin(45) + yI * Math.cos(45);
     console.log("Coor Isometricas:" + xI + "/"+ + yI);
}
*/

```

---

Edit:

Each cell is 50x50. Having 10 columns and 50 rows, the information of each cell would look like this:

1: 50/50 2: 100/50 3: 150/50 ... 49: 450/250 50: 500/250

Maximum Y value = 250.

xI=xI\*Math.cos(45 / 180 * Math.PI)-yI\*Math.sin(45 / 180 * Math.PI); yI=yI\*Math.sin(45 / 180 * Math.PI)+yI\*Math.cos(45 / 180 * Math.PI); yI=yI\*2; yI=yI-300;

Click in X:1 / Y:1 = -138.5929291125633/ 531.5575746753798 Click in X:1 / Y:5= 198.69700551341987/ 90.3229432149742

Y exceeds the maximum value.

---

Edit2:

var xI2=xIMath.cos(45 / 180 * Math.PI)-yIMath.sin(45 / 180 * Math.PI); var yI2=xIMath.sin(45 / 180 * Math.PI)+yIMath.cos(45 / 180 * Math.PI); yI2=yI\*2; yI2=yI-300; **xI2=xI2+150;**

/// console.log("Coor Isometricas:" + xI2 + "/"+ + yI2 );

x coor : 100 to 400 px if x+150; y coor: 0 to -155.

Been thinking that the problem is not necessary on isometry. What I'm looking for can be simplified to get the coordinates of a 2d plane by having it rotated X degrees

# Answer
> 2 votes
How you do this depends on the type of isometric surface you have

A diamond shaped surface is basically just a grid rotated by 45 degress and squashed along the y axis. To calculate the coordinate of the clicked tile, just multiply the y coordinate by 2 (or if your tiles don't have the standard 2:1 ratio, just divide the width by the height and multiply by that value), then subtract the position of top tile and apply a +45° rotation (45° clockwise). You can do the last step by using the formula

$$x'=x\cdot cos(45°)-y\cdot sin(45°)$$ $$y'=x\cdot sin(45°)+y\cdot cos(45°)$$

Where \\$(x';y')\\$ is the new coordinate. This will give you a position in a coordinate system where the top left tile is the `(0; 0)`. Floor the x and y coordinates if you need the tile coordinates.

A staggered isometric projection looks like this:

If you need to convert the coordinates from this to a cartesian coordinate system, follow this answer

---
Tags: javascript, geometry, html-canvas, isometric
---


# Question
Title: Getting closest distance between a square's edge and a point 2D
How would I get the closest distance between a square's edge and a point in 2D, if I only have the points coordinates, and the coordinates of the square and it's size?

# Answer
```
float DistanceFromRectangle(Vector2 point, Vector2 center, Vector2 size, float angle) {

    // First, transform the point into the rectangle's local coordinate space.
    Vector2 offset = Rotate(point - center, -1 * angle);

    // Take the absolute value of this offset, on x and y, and subtract the size.
    // This gives zero on the edge, increasing positively as we move away.
    // Clamp out any values less than zero.
    Vector2 outside = Max(Abs(offset) - size/2, Vector2.zero);

    // Return the length of this vector, which is our distance to the closest point
    // on the square's edges or corners, and zero inside the square.
    return Length(outside);
}

```
> 2 votes

# Answer
Thank you Felsir and DMGregory, I just googled 'distance point to square' and I found a already existing stackexchange question about this. How do I calculate distance between a point and an axis-aligned rectangle? Thanks!!
> 0 votes

---
Tags: 2d
---


title: How to make specific paths in UE4?

text:
# Question
Title: How to make specific paths in UE4?
I have a project where I have 1 character (playable) and 2 NPC's (AI).

The NPC's are programmed to meet 2 target points.

Below is an image to facilitate understanding:

As you can see, this green path is the full extent of the terrain that both **my character** and **NPC's** can walk through.

I know that in order for my character to traverse the full extent of the terrain, it is only necessary to add a **nav mesh bound** that covers the entire length of the terrain, but doing so the NPC's would cut their path:

**CODE NPC'S:**

I've made the target variable editable, so I can choose the target in the level editor.

I would like to know the simplest way to make the playable character go all over the terrain and the NPC's to follow the green route.

# Answer
> 0 votes
Creating two volumes of motion is impractical, in theory it is possible, but it is much more laborious, less practical and less fluid (**worst performance**).

Much better (for the situation) just define in more detail the path of the NPC. And for that, just **add more target points** (in the case of the question, just add 1 more).

The **nave mesh bound** would cover the entire extent of the map, so the controllable character can go anywhere.

**Look the image:**

Purple Square =\> controllable character

Red Circle = NPC

Blue X = target point 1

Black X = target point 2

Note that this way the NPC will make the desired path without affecting the controllable character.

In the answer to this question, you have a very easy way to do this:

How do one NPC follow a succession of target points?

There are numerous ways to do the same thing, it's up to you to decide which one to use. You could use the **AIMoveTo** instead of using the **Simple Move**. Even use **navigation filters** (refer to this in Stephen's answer)

# Answer
> 1 votes
Since you want to have a nav mesh over the whole level but make the AI only move to the location in the direction and angle you want them to, you need to switch from SimpleMoveTo and AIMoveTo.

You'll also need to add extra target points and set the AI on a path to one target point then, On Success, move it to the next.

The target points do not have to be an actual Unreal Target Point, they can be any actor you'd like them to be.

---
Tags: unreal-4, navmesh, path
---


title: Web based poker on Phaser 3

text:
# Question
Title: Web based poker on Phaser 3
Please can somebody help me as I'm a lil bit new to game dev and user interface designing. I am trying to create a simple Texas holdem poker using phaser3 for multiplayer application. I have a few doubts this is my app.js

```
   const config = {
  type : Phaser.AUTO,
  width : 800,
  height : 600,
  backgroundColor : #000000,
  physics : 'arcade',
  scene : {
    preload : preload,
    create : create,
    update : update

```

}, }

```
var game = Phaser.Game(config);

```

What is actually happening in this code and what should be my project folder structure for any simple multiplayer online game. Can I set the witdh and height dynamically depending on the device width and orientation??.

Please anybody who could just explain me a few things about gamedev...

Thanks in advance.

# Answer
First of all the code you have shared is able to display a sprite which is the name of an image you can play with in game developpement or an element of the game, like the code bellow, so if you want to ask some questions first about this snippet please you're welcome, then we can for example discuss about the basic tutorial to create a game with Phaser 3

```
var config = {
    type: Phaser.AUTO,
    parent: 'phaser-example',
    loader: {
      baseURL: 'https://cdn.jsdelivr.net/gh/samme/phaser-examples-assets@v2.0.0/assets/',
      crossOrigin: 'anonymous'
    },
    width: 800,
    height: 600,
    scene: {
      preload: preload,
      create: create
    }
};

var game = new Phaser.Game(config);

function preload ()
{
  this.load.image('dude', 'sprites/phaser-dude.png')
}

function create ()
{
  var sprite = this.add.sprite(50, 50, 'dude')
}
```

```
<script src="//cdn.jsdelivr.net/npm/phaser@3.17.0/dist/phaser.min.js"></script>
```
> 1 votes

---
Tags: game-design, game-mechanics, game-loop, browser-based-games, phaser
---


# Question
Title: Is this a reasonable method of detecting JS memory hacks?
I'm working on a single-player browser-based RPG in my free time. I do allow for saving the user's game on the server, but the game is largely going to run locally and I therefore acknowledge that it is impossible to outright prevent a user from cheating in a myriad of ways.

I'm just looking at the idea of a "dookie" achievement for editing the game data, and was wondering if this solution is in any way viable?

```
if (Reflect.set.toString() !== 'function set() { [native code] }') {
  throw new TypeError('Missing native Reflect.set');
}
if (Error.constructor.toString() !== 'function Function() { [native code] }') {
  throw new TypeError('Missing native Error constructor');
}
if (Proxy.constructor.toString() !== 'function Function() { [native code] }') {
  throw new TypeError('Missing native Proxy constructor');
}

function setTrap(target, _1, _2, receiver) {
  const res = Reflect.set(...arguments);
  const stack = new Error().stack.split('\n');
  if (stack.length >= 2 && stack[1].indexOf('<anonymous>') >= 0) {
    Reflect.set(target, 'cheated', true, receiver);
  }
  return res;
}

const myData = new Proxy({
  data1: valueA,
  data2: valueB,
  data3: valueC,
  // ...
}, {set: setTrap});

```

If the user edits `myData` in the browser console, their changes will remain, but `myData` will also get `cheated: true` after whatever change they make. Assuming `setTrap` is defined in a local scope, circumventing this would require editing the actual code loaded by the browser rather than simply editing a value in the console, and minified & packed JS would make that a more frustrating task than most would bother with, I think.

This would let someone who derives enjoyment from cheating do so without additional difficulties on their part, while letting me offer them a mild rebuke with a dookie achievement for cheating.

Of course, a determined cheater could prevent the game from sending the cheating marker to the server when saving the game. Even trying to alert the server from within the `setTrap` function could be easily defeated by simply cutting off the web connection while cheating, but this idea is more of a wagging finger than an attempt at preventing any cheating from occurring.

But my question is this: have I missed anything obvious with this idea? Is there a better way to write my conditional (I admit, I came up with it after just a few minutes messing around in Chrome, so it may not work the same in Firefox or something)?

# Answer
> 4 votes
Yes, your strategy for detecting manipulation of the runtime forgets that it is also possible to override the `toString` method of any function. After the cheater changed `Reflect.set` to their own implementation, they just need to enter the following in the javascript console of their web browsers to break your cheat detection system:

`Reflect.set.toString = function() { return "function set() { [native code] }" }`

Alternatively, they could set a break-point before `const myData` and replace `setTrap` with a different function. Which might ironically be really handy as an entry point for their own cheating functionality.

Sorry, but a browser-based anti cheat system is not going to work. The debugging tools of modern web browsers are just too powerful and the JavaScript language just allows too much runtime trickery.

---
Tags: javascript, savegame, anti-cheat
---


title: Packaging a multiplayer game in unreal

text:
# Question
Title: Packaging a multiplayer game in unreal
I have created a new project using the third person template. I set the number of players to two in the play settings as well as using a dedicated server.

How do I package the project so that I can run the server and connect to it with clients? So far when I package it all I get is an exe that starts the game like a normal single-player game.

# Answer
> 1 votes
You need to compile the Engine from Source in order to get the DevelopmentSever config as its not available on the LauncherVersion of the Engine. Pull the source from the github, run a few .bat files and you have the source. Compile it. Go to the game project directory on your drive and switch engine version for the project while opening .uproject. It will process this and generate the requisite files. Open solution file for the game and select DevelopmentSever config and build. You will get the DedicatedServer executable file in the binaries. Open the project and package file. You have the game executable and server executable.

# Answer
> 0 votes
There are two multiplayer hosting modes with Unreal: Client-Server and Peer-To-Peer. The second is easy to set up and is why you get a single executable file when packaging (any client can start a non-dedicated server). If you want a proper dedicated Server, you will need to write one yourself.

---
Tags: multiplayer, unreal-4
---


# Question
Title: How to change the Art of the Catch script in order to spawn random items?
I've downloaded the mod Art of the Catch and I was wondering how I could change the scripts in order to spawn three new category of items:

any ingredient (dragon bones) any non-enchanted craftable item (iron helmet) any enchanted craftable item (ring with magic enchantment that is vanilla or added by a mod)

Looking at the source code, I found this:

```
function SelectFish()
    Form fish_base = fish_detected.GetBaseObject()

    if fish_base == CritterPondFish01
        PlayerRef.AddItem(CritterPondFish01Ingredient, 1, true)
        _AC_CaughtFish01.Show()
    elseif fish_base == CritterPondFish02
        PlayerRef.AddItem(CritterPondFish02Ingredient, 1, true)
        _AC_CaughtFish02.Show()
    elseif fish_base == CritterPondFish03
        PlayerRef.AddItem(CritterPondFish03Ingredient, 1, true)
        _AC_CaughtFish03.Show()
    elseif fish_base == CritterPondFish04
        PlayerRef.AddItem(CritterPondFish04Ingredient, 1, true)
        _AC_CaughtFish04.Show()
    elseif fish_base == CritterPondFish05
        PlayerRef.AddItem(CritterPondFish05Ingredient, 1, true)
        _AC_CaughtFish05.Show()
    elseif fish_base == CritterSalmon01 || fish_base == CritterSalmon02 || _AC_FishWaterfallTypes.HasForm(fish_base)
        PlayerRef.AddItem(FoodSalmon, 1, true)
        _AC_CaughtFishSalmon.Show()
    endif
endFunction

```

It was inside \_ac\_beginfishing.psc with other functions. I am pretty sure I just need to modify the function, but I am not sure if we can use a general class of items as a variable, and I am even less sure about adding items with enchantments, because from what I know there's no variable that points to a list of items.

Anyway, how would you change the scripts so that it spawns random items? The way I would do is generate a random number and use it to select an item in a list, but I am not familiar with the scripting language, so I am not exactly sure how I could do that or even if it's possible.

# Answer
I'm not sure this is part of the modding script. This looks like it just tells the game to show the fish you've caught. I might be wrong. Mabye your looking at the wrong piece of code?

`PlayerRef.AddItem(CritterPondFish05Ingredient, 1, true)`

That part could lead you somewhere.

"akItemToAdd: The base form add to this reference's inventory. If this is a base object, it will add a newly-created item. If it is a reference, it will move/remove it from own place/container to this container. If a form list, then it will add aiCount of each item in the list."

Just replace CtitterPondFish05Ingredient with the desired object. DO realize that this will only trigger when the function selectFish is fired. If you don't want this, put it in some other function. Hope this helps.
> 0 votes

---
Tags: skyrim-modding
---


# Question
Title: My position is "changing" when handling animation
I'm trying to learn Monogames(Old XNA) and how to develop a 2d game.

I'm in the process of animating my sprites. It works but there are somethings that are weird to me.

For some reason when animating my sprites it "changes" the position when being animated WITHOUT changing the origin. Like so

When I have not changed my origin my character "shifts" his body upwards. Something he should not do.

Now if I change the origin to be the width and height of my frame this does not happend. Like so

Ass you can see the rectangle is still changing but my character does NOT shift in its position. I can't really understand why he shifts and DOES NOT shift.

The origin is at the top-left position of the rectangle.

Why does my character position shifts? I think it's something about offset with the different heights of the frames I am unsure. I don't understand how to work with offset.

EDIT.

```
//I have sheets with more animations (IDLE,WALK etc) This is how I get correct ones
List<CustomTexture2D.Frames> currentsheet = cts.frames.FindAll(x => x.filename.Contains(_currentstate.ToString()));
//Gets the information of the current frame (width, height, position on spritesheet)
var t = currentsheet.Where(x => x.filename.Contains(_currentframe.ToString())).FirstOrDefault();
//Without changing origin
_spriteBatch.Draw(cts.Texture, position, new Rectangle(new Point(t.frame.x, t.frame.y), new Point(t.frame.w, t.frame.h)), Color.White, rotate, new Vector2(0, 0), 1, SpriteEffects.None, 1);
//With changed origin
_spriteBatch.Draw(cts.Texture, position, new Rectangle(t.frame.x, t.frame.y, t.frame.w, t.frame.h), Color.White, rotate, new Vector2(t.frame.w, t.frame.h), 1, SpriteEffects.None, 1);

```

# Answer
If you look carefully at the first image the top left does not change position.

XNA does not know what is drawn in the sprite. So when you tell it to draw a sprite at (x,y) then it will draw that sprite at (x,y).

It's up to you to make sure the visuals actually match up. Either by making sure the character is always in the same spot relative to the top left, or by adding an offset to the (x,y) based on where the character is in the sprite.
> 1 votes

---
Tags: xna, animation, sprites, monogame
---


# Question
Title: Move and rotate one object to another C++ [3D]
I have two object, need attach 'TWO OBJECT' to 'ONE OBJECT'.

I have vectors 'angle' 'origin' of ONE and TWO objects.

I tried do "TWOOBJECT.origin += ONE.origin - ONE.oldorigin", this just attach coordinates, but not rotate with one object....

# Answer
> 1 votes
You need to associate a **matrix with each object**.

The matrix of the parent object is in world space, so the translation part contains the position of the parent in the world.

The matrix of the child object is in parent's space, so the translation part contains the relative position of the child to the parent.

Note that the same goes for the rotational part of the matrix: the parent's absolute rotation in the world is encoded. The child's relative rotation to the parent is encoded.

To know where the child ends up in the world, you need to **multiply these two matrices**.

The order of this multiplication depends on your conventions, whether you pre-multiply or post-multiply your vectors with a matrix.

So it could either be ***Mp X Mc*** or else ***Mc X mP***

The inventor of homogeneous coordinates used vertices as row vectors multiplied by a matrix.

So, the mesh vertices for child shape would end up being computed as:

```
      v        *       Mc        *        Mp

|v0 v1 v2 1 |  * | .. .. .. 0 |     | .. .. .. 0 |
                 | .. .. .. 0 |  *  | .. .. .. 0 |
                 | .. .. .. 0 |     | .. .. .. 0 |
                 | ox oy oz 1 |     | tx ty tz 1 |

```

With ***o*** as the child's offset to parent, and ***t*** the position of the parent in the world.

Note that every game engine associates a matrix with an object. If the game engine uses Scene Graphs, it is as easy as putting the child object as a child of the parent object in this graph, and you are done.

---
Tags: c++, 3d, geometry
---


# Question
Title: Fastest way to regroup every cell with the same value into a cellular noise
I'm working on a Map Generator, who are computed based on multiple height-map (I'm using FastNoise Asset on Unity Store to get all data) and they are split into Chunk.

Some noises are "cellular" and return the exact same value for group of cells next each others. Like:

I want now be able to get all "zones" defined on a chunk, with all Coords who are into the zone, the center of the zone, ... This is what I did so far, and it's working good, but it took in average **0.95sec to handle 240x240 cell !!** It's not something usable on runtime so I probably miss something.

```
float cellularHeight; // Current cell height
Dictionary<Coord, float> cellularHeights = new Dictionary<Coord, float>();  // Keep height for other cellular (to get if it's same than current)
Dictionary<Coord, int> cellularZoneIdx = new Dictionary<Coord, int>(); // Zone idx for every coord
Dictionary<int, List<Coord>> coordPerZoneIdx = new Dictionary<int, List<Coord>>(); // List of coord per zone idx
int nextZoneIdx = 0;
int countZone = 0;  // As zone can be merged, "next" is not a good way to get number of zone
int zoneIdxLeft = -1; // Someone at left ?
int zoneIdxBottom = -1; // Someone at bottom ?

int idx = 0;
Coord cellCoord;
int countPerLine = 240;

for (int _y = 0; _y < countPerLine; _y++)
{
    for (int _x = 0; _x < countPerLine; _x++)
    {
        cellCoord = new Coord( _x, _y );

        // Get cellular value (stored in 1D float array)
        cellularHeight = this.heightmap[idx++];
        cellularHeights.Add(cellCoord, cellularHeight);

        // Find if Left or Bottom cell are same ?
        zoneIdxLeft = zoneIdxBottom = -1;

        // Is the same than bottom ? (In all case (In left zone or not) we want this one to Bottom)
        if (_y > 0 && cellularHeights[cellCoord + new Coord(0, -1)] == cellularHeight)
        {
            zoneIdxBottom = cellularZoneIdx[cellCoord + new Coord(0, -1)];
            cellularZoneIdx.Add(cellCoord, zoneIdxBottom);
            coordPerZoneIdx[zoneIdxBottom].Add(cellCoord);
        }
        // Is the same than  left ?
        if (_x > 0 && cellularHeights[cellCoord + new Coord(-1, 0)] == cellularHeight)
        {
            zoneIdxLeft = cellularZoneIdx[cellCoord + new Coord(-1, 0)];

            // Current cell is on the same zone than left and bottom but both zone are not the same -> Regroup
            if (zoneIdxBottom != -1 && zoneIdxLeft != zoneIdxBottom)
            {
                foreach (Coord updateCellCoord in coordPerZoneIdx[zoneIdxLeft])
                {
                    cellularZoneIdx[updateCellCoord] = zoneIdxBottom;
                    coordPerZoneIdx[zoneIdxBottom].Add(updateCellCoord);
                }
                coordPerZoneIdx.Remove(zoneIdxLeft);
                countZone--;
            }
            else if (zoneIdxBottom == -1) // If not same Zone at bottom add to the left one (or it's already added to bottom)
            {
                // Add this to Left Zone
                cellularZoneIdx.Add(cellCoord, zoneIdxLeft);
                coordPerZoneIdx[zoneIdxLeft].Add(cellCoord);
            }
        }
        // No one
        if (zoneIdxLeft == -1 && zoneIdxBottom == -1) // New zone
        {
            cellularZoneIdx.Add(cellCoord, nextZoneIdx);
            coordPerZoneIdx[nextZoneIdx] = new List<Coord>();
            coordPerZoneIdx[nextZoneIdx].Add(cellCoord);

            nextZoneIdx++;
            countZone++;
        }
    }
}

```

Coord is a simple class:

```
[System.Serializable]
public class Coord {
    // Attributes
    public int x;
    public int y;

    public Coord(int x, int y) {
        this.x = x;
        this.y = y;
    }
    public override string ToString()
    {
        return "[" + this.x + ";" + this.y + "]";
    }
    public static bool operator ==(Coord a, Coord b)
    {
        return (a.x == b.x && a.y == b.y);
    }
    public static bool operator !=(Coord a, Coord b)
    {
        return (a.x != b.x || a.y != b.y);
    }
    // Dictionary.ContainKey
    public override int GetHashCode()
    {
        // Uniq string hashCode
        return (this.ToString()).GetHashCode();
    }
    // Dictionary.ContainKey
    public override bool Equals(object obj)
    {
        Coord c = Coord.GetCoord(obj);
        return (c.x == this.x && c.y == this.y);
    }
    public static Coord operator +(Coord a, Coord b)
    {
        return new Coord(a.x + b.x, a.y + b.y);
    }
    public static Coord operator -(Coord a, Coord b)
    {
        return new Coord(a.x - b.x, a.y - b.y);
    }
}

```

How to do the same thing but way faster ?

# Answer
> 1 votes
**UPDATE: (5/18/2019)**

If you are looking for how to get vertices (and other data like its range from 0 to 1, or its center point) of every cell generated in a Voronoi diagram, I would suggest using a Delaunay triangulation library. Coding this by hand is possible too, but may not be worth your time.

This one looks promising for Unity users: csDelaunay

Here is a description and some example usage of this library.

You can also use Lloyd's Relaxation in this library. Here is a demo showing this method: demo

This will require you some steps:

1. Get a list of polygon center points and each of their height values using the FastNoise heightmap.
2. Then you can go ahead and create your voronoi diagram using the above mentioned csDelaunay library.
3. If you want to detect each zone, simply loop through your polygon center points and check their corresponding height.
4. If you want to get the outline polygons of each zone (contiguous set of voronoi cells with same height ...like in Northgard), you will have to loop through the edges using a search function. To optimize this search, you could utilize recursion and/or sorting the data before searching.
5. If you want to be able to detect which zone a user has clicked on, you will have to loop through all the zones and check a point-to-polygon collision. To optimize this, you can use a quadtree and/or approximation methods for collision detection. In Unity, you might be able to register these zones as 2D collision hulls and just use the default collision check.

**ORIGINAL:**

The main line I noticed which may be causing slowdowns is:

`foreach (Coord updateCellCoord in coordPerZoneIdx[zoneIdxLeft])`

If you can avoid this, or optimize it, it will increase the speed by up to the average number of coords per zone. Maybe add a "checked" variable to each coordinate to avoid repetitions.

Another problem looks like the fact that you are looping through a 240x240 grid. Your focus could be on decreasing `countPerLine` and still get an acceptable result. You could convert your grid space into a smaller space (like in a Voronoi map) and then loop through those points instead of an entire grid.

This problem looks a little similar to Voronoi Diagrams. If you want to improve performance drastically, research the "Sweep Line" algorithm.

Also I would suggest putting conversion lines like:

`cellularHeight = this.heightmap[idx++];`

...into functions like:

`cellularHeight = this.getHeight(idx);`

...or something similar. This approach to your algorithms will help with avoiding small mistakes/repetitions with the index conversions in the long run.

---
Tags: unity, c#, perlin-noise, heightmap
---


# Question
Title: Unity is losing track of changes to Resources
I have a Unity project, where I recently changed the names of a few files in my Resources folder. This is relevant because I have code that looks like this:

```
        internal void LoadItems(string[] names)
        {
            var items = Resources.LoadAll<TileBase>("Tiles\\Items");
            var itemMap = items.ToDictionary(m => m.name.ToUpperInvariant());
            _items.Clear();
            _items.AddRange(names.Select(n => itemMap[n.ToUpperInvariant()]));
        }

```

The `AddRange` call is currently throwing an exception, because the incoming data is expecting the new names to be present, but `itemMap` for some reason still contains the old names. I've verified this in the debugger, and I've verified in Unity's file search that no file matching the old version of the name that's causing trouble here exists anywhere in the project anymore. And yet, when I run the project, (using the Attach To Unity And Run option from Visual Studio,) the old names still show up.

If I go into Build Settings and tell it to rebuild the project, this code works correctly... once. Subsequent runs cause it to fail, going back to the old names again, so it kind of feels like Unity is actively trolling me at this point.

The old data has to be cached somewhere, but I'm not sure where or how to fix it. Anyone know how I can resolve this?

# Answer
> 1 votes
Changing the file name does not *automatically* change the name property. That is, they are not inextricably linked. If you look inside the .asset or .prefab file for one of your assets (using Notepad, for example, assuming you are trying to load a prefab or ScriptableObject), you will see one or more “m\_Name” entries. If any name matches the old file name, it may be that when you renamed the files, the name property did not get updated for some reason. If you try just making any change to the asset and re-saving the project it may solve the problem.

However, as DMGregory mentioned, there may be a better way than to access everything by file name. Perhaps simply a ScriptableObject like this:

```
[CreateAssetMenu]
public class TileBaseCollection : ScriptableObject {
  //To assign a name unrelated to the filename, so changing the filename doesn't affect anything:
  [Serializable]
  public struct TileBaseID {
    public string id;
    public TileBase tile;
  }
  public TileBaseID[] tiles;

  //or, if you have just a few tiles:
  public TileBase DesertTile;
  public TileBase GrassTile;
  //etc.
}

```

Note that if you create an instance of this, neither it nor the tiles referenced need to be in resources folders. Just declare a direct reference to the object in whatever MonoBehaviour you need to access the tiles from and assign the newly created object directly in the inspector.

---
Tags: unity
---


# Question
Title: Unity: Unable to rearrange "Sorting Layer" for 2D game
Since yesterday I got a bit into game development with Unity (i've never done game development before), and I am currently making a small 2D game. I am attempting to rearrange the various layers in the "Sorting Layers" list. According to Unity's own official tutorial, you can simply drag & drop the layers around to rearrange them. However, when I click on one of the layers, I can not drag it anywhere.

Can someone help me out?

# Answer
> 0 votes
The elements that can be dragged to new positions will have a = sign next to it in the inspector. The other ones below cannot be dragged but can be set up however you like.

Here is a pic the highlighted Layer in sorting layers is draggable

Note: you must select edit layers button located in the Layers Dropdown Tab shown at the top middle in the pic to get the Tags & Layers Inspector Window.

---
Tags: unity, layers, sorting
---