# Question
Title: Calculating complex D&D style interactions
So I don't even know if this is the right community to ask (as I imagine it's probably quite maths heavy) in but I figure it falls under the realm of game mechanics.

I want to develop a game mechanic that utilises complex D&D style interactions but on another level from that, but I don't really know where to begin conceptually. What I mean by D&D style interactions is each character will have a set of attributes, strength, skill, intelligence etc and those attributes will dictate how interactions play out between characters.

So for basic example, two characters battling each other and each attribute ranges from 0-20.

Character A - Attack:13, Defence:14 Character B - Attack:15, Defence:10.

So when Character A strikes at Character B I need to calculate how successful that attack would be and what the outcome would be, which would then feed back into their attributes. So maybe their attack is semi-successful and produced a flesh wound, not enough to kill but that reduces Character B's Attack attribute to say 13.

Now that's a fairly trivial, example where I want to try and take it to the next level is to introduce combined attributes that all have an impact on the outcome of a move. So Skill, Experience, Fitness, Attack Speed, Anticipation and even Luck (which I figure would be randomised and offset by attributes like Experience).

Ideally I'd like to build an engine where I can define attributes and how they interact and can add more over time to build up the complexity of interactions. But I am at a loss where to begin. I'm not looking for a ready made solution but just to be pointed in the right direction.

To add some further explanation as to where I'm struggling. Are there known algorithms, techniques or maths solutions that are used to calculate attribute based interactions? In my head I'm imagining some system of values and weights with some pseudo-randomness thrown in but I'm at a loss as to how you actually calculate outcomes.

When I try and think it through all I get is a massive set of 'if' statements where values go in at the top, if's are applied and modify the outcomes. So...

```
If CharA_Attack == 15 and CharB_Defence = 10 Then Outcome = Kill

If CharA_Speed == 10 and CharB_Speed = 12 Then Outcome = Deflected Blow

If CharA_Luck == 14(random) and CharB_Luck 7(random) Then Outcome = Flesh Wound

```

Etc...

# Answer
> 4 votes
This is sort of an open-ended question, but I will try to offer you some guidance on where to begin.

> When I try and think it through all I get is a massive set of 'if' statements

Yes, not ideal. What I think you want here are weighted values between 0.0-1.0, weighted and combined through multiplication to a result in the 0.0-1.0 range. This is a way to represent falsiness (0.0) vs. truthiness (1.0) without being stuck with binary decisions as such. Google **weighted averages** for more.

For example, let's say two swashbucklers are fighting a duel. With light swords such as foils, speed and the ability to quickly perceive what your opponent is doing (wit, intellect) are crucial. Let's say A strikes at B:

```
float attackStrength = (A.speed * 0.8) + (A.wit * 0.2)
float defenseStrength = (B.speed * 0.6) + (B.wit * 0.4) //a little more wit, to see what your opponent is doing

```

You could also include each combatants footing, from the last attack / defend sequence:

```
float attackStrength = (A.speed * 0.5) + (A.wit * 0.4) + (A.footing * 0.1)
float defenseStrength = (B.speed * 0.5) + (B.wit * 0.2) + (B.footing * 0.3)

```

The *weights* are those constants you are multiplying by, e.g. `0.5`. These denote the *importance* of that term in resolving the equation in question.

And then

```
bool outcome = attackStrength > defenseStrength; //or you could make bool a float, too!

```

Formulae can be as simple or complex as you need them to be. Just ideally keep each term in this 0.0-1.0 range or you will get confused.

You'll notice that the weights on each line always sum to a maximum of `1.0`. This is required so that the maximum resultant value can be `1.0 * 1.0 = 1.0`. A similar requirement applies to your stat variables. Let's say your wit, speed and footing are all in the range 0-100 (max), you then just need to divide each one by the max, so a very high stat value of `100/100=1.0`. Obviously then, there will always need to be some form of maximum value...

...However this doesn't necessarily mean your characters reach a hard limit in terms of capability. One way to achieve that is to use a non-linear curve that drops off as skill goes higher and higher - it is tangent to some value but never quite reaches it (indeed, `Math.tan()`gent could work with some fiddling). This just ensures that you can keep pushing the stat in question, for infinite levels, but you will never reach a cap *in terms of the effectiveness it produces*.

The benefit to using 0.0-1.0 range for everything, both terms and result of each equation, and the final result, is that you always know what you are looking at: for example, a value of 0.8 is always going to be closer to true than the false, by a good margin.

# Answer
> 1 votes
There is a python-library called Lea that is made for doing calculations like that (or "working with discrete probability distributions in an intuitive way. It allows you to model a broad range of random phenomenons, like dice throwing, coin tossing, gambling, weather, finance, etc. More generally, Lea may be used for any finite set of discrete values having known probability: numbers, booleans, date/times, symbols, … Each probability distribution is modeled as a plain object, which can be named, displayed, queried or processed to produce new probability distributions"). One of the examples, called RPG Combat, shows how to calculate possible outcomes of D&D-style attacks (D20+attack vs defense, with a chance of critical hits): https://bitbucket.org/piedenis/lea/wiki/Lea3\_Examples#markdown-header-rpg-combat

It should be possible to expand on that to create a more complex combat system with more attributes and possible outcomes, then query the resulting models for various statistics and draw graphs etc.

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


# Question
Title: How to support importing .uasset files in game for content creators(UE4)?
I would like to support importing clothes(as SkeletalMeshes) and props(as StaticMeshes) as uasset files into game for content creators, which obviously have not been packaged with the game. Basically I am looking for a clean modding pipeline.

EDIT:
***TLDR:***
Is it possible to load .uasset files with `StaticLoadObject()` into game and use assets from it ***after the game has been packaged***?
Or does it only work with packaged files?

If not what function do you recommend for that purpose?

***not-TLDR***

Bringing in stuff does work well in the editor, using Rama's LoadObjectFromAssetPath, just by:

1. right clicking my asset in Content Browser
2. copy reference
3. and copy pasting the result to the path variable of the LoadObjectFromAssetPath blueprint node.

Well, I am not sure if it is going to work at runtime...

So I used my favourite search engine and put in some keywords and bumped into this.

Then I wrote some code(Blueprint Function Library):

```
void UFileDialogOpener::LoadFile(FString  from) {

    auto result = StaticLoadObject(UStaticMesh::StaticClass(), NULL, *from);

    GEngine->AddOnScreenDebugMessage(-1, 150.0f, FColor::Red, "from: " + from);

    if(result)GEngine->AddOnScreenDebugMessage(-1, 150.0f, FColor::Green, "name: " + result->GetName());
    else GEngine->AddOnScreenDebugMessage(-1, 150.0f, FColor::Green, "no result");

    auto * meSkelMesh = Cast<UStaticMesh>(result);

    if(meSkelMesh)GEngine->AddOnScreenDebugMessage(-1, 150.0f, FColor::Red, meSkelMesh->GetName());
    else GEngine->AddOnScreenDebugMessage(-1, 150.0f, FColor::Red, "no mesh");

}

```

As per the debug messages StaticLoadObject does not find anything. I tried feeding it the both of the results of righclicking my asset in Content Browser and choosing either: copy reference and copy path. Neither of them yielded any result.

Not sure where I am messing up.

Anyways, just wondering if anyone can recommend a better way of doing this(code, plugins etc)?

# Answer
After doing some research and stuff I figured out, my best bet is using Unreal's UGC solution. I think that would take care most of the heavy lifting for us, and for the content creators as well. Besides I would appreciate any help on the above code and questions, just to understand why it does not work...
> 1 votes

---
Tags: unreal-4, mesh, skeletal-animation, import
---


title: Tile base Farm Simulation in Unity

text:
# Question
Title: Tile base Farm Simulation in Unity
I am thinking of creating a sprite base 2d top down farm simulation game. The game uses tiles and I was wondering (conceptually) what is the best way to handle the farm tiles. Each tiles should have the following list of features.

* The player should be able to add seeds to each tile
* The player should be able to plant a variety of vegetables.
* Plants should have different stages of growth
* The player should be able to interact with each tile (dig, cover holes, water, add fertilizer, etc).
* The farm layout can have a variety of shapes (i.e. Not just a square (9 x 9) or rectangle (9 x 15) a shaped farm.)

Currently I have a script that generates a square or rectangle shaped like farm, each tile is a sprite object with a 2D collider. I have come up with a solution for planting and the different stages of growth. However, it isn't the most elegant solution. My current solution is to create prefab for each plant. Then once a seed is planted onto a tile, create a plant object in the location of the tile (using it's vector position), and make the plant a child object to that tile. Each plant will have an age counter that increase when a new day is triggered. To show the growth stage swap the texture depending on the plant's age.

My biggest problem with the implementation is that if the players farm is very large the game will have to create a hundreds object, which seem very taxing. Is that a different way achieve these features without the use of so many objects? If so, how would I implement it (conceptual of course). Thanks!

# Answer
> 1 votes
As your game appears to use rectangular tiles; for any arbitrarily shaped farm, there is an optimised subdivision of that farm into rectangles. Often, far fewer than you'd think. So, for now, let's ignore your last requirement.

Second, you want to be able to have different images on different tiles depending on plant type and growth stage. From a graphics perspective, there is not really a difference between these two.

* Subdivide your farm into rectangles.
* Generate a mesh, such that each tile has 4 owned corner vertices.
* Set for the texture of the mesh an extended tilemap (as an image, not an actual unity tilemap), and manipulate vertex UVs to vary what each individual tile shows.
* For Collision, use a simple rectangle collider and then apply some relative coordinate math to determine the exact tile that is affected.

There, all one object per subdivision. Each of these steps can have some tricky components, but this should be enough to get you started. For huge maps, be sure to keep mesh vertex limits in mind.

# Answer
> -5 votes
I'm going to give you a rather stupid answer but what the heck. First of all hundreds of objects in a game is no problem. Secondly there is this guy called quil 18 that has great tutorials.

Start with the Basics of 2d tile maps and then you can watch this gigantic series about a base building game here

---
Tags: unity, 2d, data-structure
---


# Question
Title: Parts of OpenGL rendering area missing/transparent until resize
I am having a weird transparency issue when running my game in windowed mode. Parts of the window, left and top parts in normal window mode, right and bottom when in maximised window, become transparent. It is full transparency not just an uncleared buffer as I can see movement from other windows behind. The size of the area that is transparent varies slightly between runs. I'm pretty sure it worked in January when I last worked on the game.

If I resize or iconify/restore the window either manually or programmatically with GLFW it fixes itself and renders the full window as expected.

`glfwGetFramebufferSize`, `glfwGetWindowSize` and `glGetIntegerv(GL11.GL_VIEWPORT)` all report the same correct values before and after a resize. Calling `glViewport` does not fix the issue. I am not getting any relevant openGL errors.

If I start the game window maximised on the displays connected to the old graphics card R9 290X I do not get this problem but window maximised on newer RX 5700 XT display still has the problem but in bottom right instead of top left. Full screen works fine on all displays.

Have not seen any problems with other games I have but I always run them in fullscreen and they are mostly DirectX or Vulcan.

Has anyone encountered this problem before? I would rather not have to programmatically modify the window size by 1 pixel each start as that is an ugly fix.

If anyone wants to test on their system to see if it is a code or driver error run either the full packaged jar (in sandbox preferably) or checkout minimal error example yourself and execute "./gradlew run".

* Windows 7
* GDX 1.9.11 (also tried 1.9.10)
* LWJGL 3.2.3 (also tried 3.2.2)
* Java AdoptOpenJDK 12.0.2
* AMD driver 20.7.2

# Answer
> 0 votes
AMD driver issue, managed to reproduce it in another previously working (last month) opengl game. Have filed a bug report with AMD.

---
Tags: opengl, java, libgdx, windows, glfw
---


# Question
Title: How to re-calculate orientation vectors when one of them is being changed?
I want to implement a Unity-like API for my transforms, with the ability to set forward, right, up vectors directly and change object's rotation quaternion accordingly.

I got stuck at the math behind it, though. What algorithm should we use to change the other 2 vectors?

I feel that the function should have 2 if branches and check which of the other two vectors to use to compute a cross product with the new vector, to decide which vector to use as the first and which is the second, and vice-versa in another branch.

I came up with something like this so far:

```
void Transform::SetForward(const glm::vec3& v) {
    mForward = glm::normalize(v);
    if (abs(abs(glm::dot(mForward, mUp)) - 1.0f) <= 1e-5) {
        // dot is either -1 or 1 (straight up or down)
        mUp = glm::cross(mRight, mForward);
        mRight = glm::cross(mForward, mUp);
    }
    else {
        mRight = glm::cross(mForward, mUp);
        mUp = glm::cross(mRight, mForward);
    }
    FixRotationQuat();
}

```

# Answer
> 1 votes
You can check the source code for how Unity does it:

```
// The red axis of the transform in world space.
public Vector3 right {
    get { return rotation * Vector3.right; }
    set { rotation = Quaternion.FromToRotation(Vector3.right, value); } }

// The green axis of the transform in world space.
public Vector3 up {
    get { return rotation * Vector3.up; }
    set { rotation = Quaternion.FromToRotation(Vector3.up, value); } }

// The blue axis of the transform in world space.
public Vector3 forward {
    get { return rotation * Vector3.forward; }
    set { rotation = Quaternion.LookRotation(value); } }

```

You can see its approach is to completely disregard the current rotation and directions of the other basis vectors. If you take two objects rotated completely differently, then set the forward (or up, or right) vector on both of them to the same value, you'll get the same orientation from both of them.

---
Tags: 3d, vector, transformation, linear-algebra, orientation
---


# Question
Title: Rotate Object in world space - Raytracing
I’m programming a C raytracing project.

I’ve been wanting to implement object rotations (square, cylinder) for several days but I can’t do it.

For each object I have its position (x, y, z) in the world space and its 3d normalized orientation vector.

For the moment I do nothing more than applying once of the three following functions on the 3d normalized orientation vector. I don’t know if I’m doing it right. Rotation doesn't work well.

For example I want to rotate my object left with the j key and right with the l key (x\_rotation), up with the i key and down with the k key (y\_rotation). I'm not sure how to use the z axis.

I'm starting to despair, can you please help me ?

I will be very grateful for your help :)

```
t_vec x_rotation(t_vec vec, float alpha)
{
    t_vec   res;

    res.x = vec.x;
    res.y = vec.y * cos(alpha) - vec.z * sin(alpha);
    res.z = vec.y * sin(alpha) + vec.z * cos(alpha);
    return (res);
}

t_vec y_rotation(t_vec vec, float alpha)
{
    t_vec   res;

    res.x = vec.z * sin(alpha) + vec.x * cos(alpha);
    res.y = vec.y;
    res.z = vec.z * cos(alpha) - vec.x * sin(alpha);
    return (res);
}

t_vec z_rotation(t_vec vec, float alpha)
{
    t_vec   res;

    res.x = vec.x * cos(alpha) - vec.y * sin(alpha);
    res.y = vec.x * sin(alpha) + vec.y * cos(alpha);
    res.z = vec.z;
    return (res);
}

```

# Answer
As mentioned in the comments, rotation in 3 dimensions has 3 degrees of freedom (you can think of them like yaw, pitch, and roll), but a unit vector in 3 dimensions has only 2 degrees of freedom (latitude and longitude). So we need to store more than just a single unit vector to describe our orientation.

The smallest change from your current code would be to store two perpendicular unit vectors: one representing your forward/facing direction, and one representing your "up" direction. That way the second vector can track any "twist" around the first vector's axis.

When you rotate your forward vector using one of the three methods you've shown, also rotate your up vector by the same method.

To keep rounding errors from building up and making your vectors no longer perpendicular, you'll want to periodically orthonormalize this two-vector basis, something like this:

```
forward = normalize(forward);
up = normalize(up - dot(up, forward) * forward);

```

You can expand this to a full rotation matrix just by computing your third basis vector as the cross product of the other two:

```
// In a left-handed coordinate system. Flip the order for a right-handed system.
right = cross(up, forward);

```

Then \[right | up | forward\] is an orthonormal rotation matrix ready to use in transforming your points.

---

A more conventional solution to this problem is to store your object's orientation as a quaternion. That's four floats instead of six for two basis vectors, and quaternion rotations compose quite nicely:

```
Quaternion Compose(Quaternion after, Quaternion before) {
    Quaternion q;

    q.x = after.w * before.x + after.x * before.w + after.y * before.z - after.z * before.y;
    q.y = after.w * before.y - after.x * before.z + after.y * before.w + after.z * before.x;
    q.z = after.w * before.z + after.x * before.y - after.y * before.x + after.z * before.w;
    q.w = after.w * before.w - after.x * before.x - after.y * before.y - after.z * before.z;

    return q;
}

```

You can construct an axis-aligned rotation like so:

```
Quaternion ZRotation(float angle) {
    Quaternion q;

    q.x = 0;
    q.y = 0;
    q.z = sin(angle/2f);
    q.w = cos(angle/2f);

    return q;
}

```

Or one around an arbitrary unit vector like so:

```
Quaternion AngleAxis(float angle, t_vec unitAxis) {
    Quaternion q;

    float s = sin(angle/2f);
    q.x = unitAxis.x * s;
    q.y = unitAxis.y * s;
    q.z = unitAxis.z * s;
    q.w = cos(angle/2f);

    return q;
}

```

Then you can compose your rotations to get your new orientation:

orientation = Compose(rotationChange, orientation);

You can transform a vector by the quaternion like so:

```
t_vec Rotate(Quaternion q, t_vec v) {
    float x = q.x * 2f;
    float y = q.y * 2f;
    float z = q.z * 2f;
    float xx = q.x * x;
    float yy = q.y * y;
    float zz = q.z * z;
    float xy = q.x * y;
    float xz = q.x * z;
    float yz = q.y * z;
    float wx = q.w * x;
    float wy = q.w * y;
    float wz = q.w * z;

    t_vec rotated;
    rotated.x = (1f - (yy + zz)) * v.x + (xy - wz) * v.y + (xz + wy) * v.z;
    rotated.y = (xy + wz) * v.x + (1f - (xx + zz)) * v.y + (yz - wx) * v.z;
    rotated.z = (xz - wy) * v.x + (yz + wx) * v.y + (1f - (xx + yy)) * v.z;
    return rotated;
}

```

Though you can see here, most of these intermediate calculations don't depend on the vector being rotated. So if you're going to rotate a whole bunch of vectors, it can be more efficient to turn the quaternion into a transformation matrix first, then use the matrix to rotate all the vectors.
> 2 votes

---
Tags: mathematics, rotation, matrix, c, raytracing
---


# Question
Title: Unity 2018.4.25f1 Errors - error CS0118 & error CS0234
I am getting 2 errors in my c# script.

1. `Assets\scripts\playerMovement.cs(8,5): error CS0118: 'PlayerControls' is a namespace but is used like a type`
2. `Assets\scripts\playerMovement.cs(4,19): error CS0234: The type or namespace name 'InputSystem' does not exist in the namespace 'UnityEngine' (are you missing an assembly reference?)`

playerMovement.cs:

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

public class playerMovement : MonoBehaviour
{
    PlayerControls controls;
    Vector2 move;
    void Awake()
    {
        controls = new PlayerControls();

        controls.Gameplay.move.performed += ctx => move = ctx.ReadValue<Vector2>();
        controls.Gameplay.move.canceled += ctx => move = Vector2.zero;
    }
    void Update()
    {
        Vector2 m = new Vector2(move.x, move.y) * Time.deltaTime;
        transform.Translate(m, Space.World);
    }
}

```

I am using the new Input System 0.2.1 in unity 2018.4.25f.

The PlayerControls script is auto-generated from an Actions Input object, and it is in the main root "Assets".

# Answer
> 0 votes
I had to switch over to Unity 2019. Thanks for your help Everyone!

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


# Question
Title: Time passing display on UI in Unity in C#
How can I display the time and how many days on a UI in Unity. Time would be moving faster like a week in 7 minutes?

Should I use Time.deltaTime and how do I excellerate the time it displays?

# Answer
> 1 votes
When your in-game time is very different from real time (as implied by "one week = 7 minutes"), then I would advise against using the Unity time system for this. While you *can* mess with the `Time.timeScale` to do things like running the physics engine in slow motion or speed it up, it is not designed to handle time acceleration factors of that scale.

I would recommend you to do your own time handling in that case. Have some global object with an `Update` method where you add to *your* game-time by multiplying *your* timescale with `Time.deltaTime`, then convert *your* game-time to a human-readable string format and assign it to the text field of a text label.

# Answer
> 0 votes
If you just want to upscale system time to an accelerated game time, you could do it something like this:

```
public class TimeDisplay : MonoBehaviour
{
    static readonly string[] DAYS_OF_WEEK = {
             "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
    };

    const int TICKS_PER_SECOND = 10000000; // File time is measured in 100 nanosecond increments.
    const long TICKS_PER_GAME_DAY = 60 * TICKS_PER_SECOND;
    const long TICKS_PER_GAME_HOUR = TICKS_PER_GAME_DAY / 24;
    const long TICKS_PER_GAME_WEEK = 7 * TICKS_PER_GAME_DAY;

    public string timeDisplay;
    public long ticksWithinWeek;
    public int dayOfWeek, hour, minute;

    // Update is called once per frame
    void Update()
    {
        var time = System.DateTime.Now;

        ticksWithinWeek = (time.ToFileTime() % TICKS_PER_GAME_WEEK);

        dayOfWeek = (int)((ticksWithinWeek / TICKS_PER_GAME_DAY) % 7);
        hour = (int)((ticksWithinWeek / TICKS_PER_GAME_HOUR) % 24);
        minute = Mathf.FloorToInt((ticksWithinWeek % TICKS_PER_GAME_HOUR)
                 * (60f / TICKS_PER_GAME_HOUR));

        timeDisplay = string.Format("{0}:{1} {2}",
                       hour.ToString("00"),
                       minute.ToString("00"),
                       DAYS_OF_WEEK[dayOfWeek]);
    }
}

```

---
Tags: unity
---


title: Unity Isometric Tilemaps Appear Jagged

text:
# Question
Title: Unity Isometric Tilemaps Appear Jagged
I had issues using the isometric tilemaps feature in Unity. Whenever I try to place tiles, they don't seem to line up and create this jagged effect. I've tried messing with the anchor points and am a complete beginner at this.

Edit: My grid component looks like this:

# Answer
Judging by your sceenshot, it looks like the top diamond of your sprite is about 104 pixels tall by 181 pixels wide - though the scene view might be resampling it at a different resolution than your source asset, so be sure to measure in your original texture to get the exact measurements.

That's about 57.5% as tall as it is wide. So in the Cell Size field of your Grid component, you'll want the height to be about 0.575 to a width of 1.0, instead of the 0.5 you have currently.

Again, this is a bit of a crude calculation based on the screenshot, so massage the numbers until you find a fit that looks right.
> 0 votes

---
Tags: unity, tilemap, isometric
---


# Question
Title: How to make balls (water, or fluid) through pipe
I'm working on a project and get stuck for days. I want to make balls going through the pipe like this game:

You can watch this Youtube video for more detail.

How can i replicate this game machenis?

# Answer
So there are going to be various steps to this. I'm not going to write all the code, because any solutions will be moderately complex and certainly more than we can go into here, but I am going to give you the basic building blocks.

**Step 1: Basic graph & linear motion**

You need to get this working before addressing curved paths.

Create a linear graph where each node is the edge of a section of pipe. That is, for `n` pipes, there will be `n+1` edges. This graph can be as simple as a `List<Vector2>` in C#.

Hardcode some positions in, and change them later as you like:

```
List<Vector2> edgePositions = new List<Vector2>();
list.push(new Vector2(10, 10));
list.push(new Vector2(30, 0));
list.push(new Vector2(50, 100));

```

Now let's say you have points `[0]`, `[1]`, and `[2]` in that `List`. And that you have just one ball in the *first* section of pipe `[0]-[1]` (and not the second section which is the range `[1]`-`[2]`). This ball's position in the pipe can be described by `t`, a value between `0.0` and `1.0`. Let's say that right now, the ball is at `t=0.25`between point `[0]` and point `[1]`. Now let's translate this into concrete terms.

First we need to get the difference vector between the two points:

`Vector2 distFull = list[1] - list[0]; //(30,0) - (10,10) = (20,-10)`

...So that is the full distance between these two points. The ball is `0.25` or 1/4 of the way along this difference vector, from point `[0]` (because `[0]` is the starting point):

```
Vector2 dist = diffFull * t; //(20, -10) * 0.25 = (5, -2.5)
Vector2 pos = list[0] + dist; //(10, 10) + (5, -2.5) = (15, 7.5)

```

We now have the ball at the current `t`. All we need to do is change `t` at each update:

```
float t = 0.0f;
float increment = 0.01f; //pretty small as it will need several frames before it reaches 1.0
...
FixedUpdate()
{
    t += increment;
    //do all the above stuff here, utilising t to get pos
    ball.transform.position = pos;
}

```

`t=0.25` should show the ball 1/4 of the way along the pipe section.

**Step 2: Moving between pipe sections & t-remainders**

You will know you have reached the end of a section when `t > 1.0` (let's say `1.04` for sake of example). You now need to take that remainder and use it to move the ball through the next section of pipe:

```
FixedUpdate()
{
    t += increment;
    if (t > 1.0f)
    {
        let tRemainder = t - 1.0f;
        //increase the pipe section index
        p++;
        t = tRemainder; //now we are using this 0.04 as the distance into the next pipe section
    }
    ...
}

```

**Step 3: Curvilinear motion**

I would suggest seeking a C# Bezier curve library to make this easier for you. You will need to do a similar thing with `t` and input this into the curve's parametric function, *however*: (Bezier) curves are by nature non-linear, so for a naive Bezier curve function, `t=0.25` will not show the ball at 1/4 of the way along the curved section of pipe.

Rather use a library whose curve function takes in the bezier curve control points and `t`, and returns a *linear* position along the curve that approximates `t` \- so the library will do the work to get as close to 1/4 of the way along the curve as possible, when you input `t=0.25`, for example.

**Step 4: Branching pipes**

This is optional, but I've included it as it is shown in the game you linked.

You will need to understand the basics of graphs_ and how they are constructed in code (usually just `Node`s with references to other `Node`s which they connect to). You will have to then forego your nice easy `List<Vector2>` above in favour of these `Node`s.
> 1 votes

---
Tags: unity, game-mechanics, water, fluid-dynamics
---


title: PyGame QIX clone, filling areas

text:
# Question
Title: PyGame QIX clone, filling areas
I'm playing around with PyGame.

Now I'm trying to implement a QIX clone.

I have my game loop, and I can move the player (cursor) on the screen.

In QIX, the movment of the player leaves a trace (tail) on the screen, creating a polyline.

If the polyline with the screen boundaries creates a polygon, the area is filled.

How I can accomplish this behaviour ?

How store the tail in memory ?

How to detect when it build a closed shape that should be filled ?

I don't need an exact working solution, some pointers, algo names would be cool.

At start, there is only the gray border, where the player can move his cursor around.

* First scenario:

The user moves his cursor from point A trough point B, drawing the red multiline until point C. At this point, because of crossing the border, the point A should be connected with point C automaticaly, creating a polygon, which should be filled (that orange stuff on my drawing). Filling the polygon is damn simple in PyGame, because I provide the sequence of points,and PyGame cares of the rest.

* Second scenario:

The user moves on the border to point D, from where he draws a line to point E. Because he is crossing the line of the previous polygon, and with his lines and the border another polygon can be created, it should be filled too. (the green one).

* Third scenario:

The player moves further on the polygon (he can move on existing polygon lines), and draws a line from point G to point F. Here again, because of the border and the existing lines, another polygon should be filled (the blue one).

# Answer
Here's how I'd approach it:

1. There is always a single open area, represented by a polygon. All other areas are irrelevant.
2. A line starts when you move from the perimeter of the polygon into the polygon's interior.
3. A line stops when you move from the polygon's interior back onto the perimeter.
4. When you stop the line, you have *divided the polygon* into two polygons.
5. You then decide which of the two polygons to fill, and which to keep as the open area. In Qix, the side that the Qix (enemy) was on stayed open and the other side was filled.

How do you subdivide the polygon? You use the endpoints of your line to divide the polygon perimeter into two sections, then use the new line to complete those two sections into new polygons.

For example, let's say your open area is a polygon with points `[p0, p1, p2, p3, p4, p5]`. Your start point `A` occurs between `p1` and `p2`, and your end point `B` occurs between `p3` and `p4`. The new line that was drawn is `[A, s, t, u, v, B]`. We first split the polygon into two segments `[A, p2, p3, B]` and `[B, p4, p5, p0, p1, A]`. These two segments together form the original polygon. Then we glue the new line into each (once forwards, once backwards), forming `[A, p2, p3, B, v, u, t, s]` and `[B, p4, p5, p0, p1, A, s, t, u, v]`. You fill one of these polygons and keep the other as your new open area.

I've not implemented this and don't know for sure if it will work, but that's the approach I would use: polygon subdivision instead of polygon filling.
> 6 votes

# Answer
This is a problem involving multiple discrete substeps. Here is an outline of what I'd suggest:

* Wait until the player forms an intersection of multiple lines
* Get a pixel from each side of the intersection
* Pathfind to see if they can connect to each other
* Pixels that cannot connect to each other are separate areas
* Perform a flood-fill to get all pixels in the area

I would store the state of the game's pixels in a Numpy array (numpy dot scipy dot org). Color could be three separate arrays for RGB, but the array I'll be focusing on is the line/no line array. Just initialize it with zeros and set it to the size of your game field, and every time the player passes through a pixel, set the corresponding item in the array to 1. You'll want to display these on the screen as a different color, as they're your line!

Every time the player pixel moves, I would check to see if it passed (and drew a line next to) an existing line. If so, I would get a pixel from each possible division:

```
. . . | .
. . . | .
. . . | x
. . x < -

```

Dots are empty pixels, lines are (obviously) lines, and Xs are the empty pixels we want to select. We can do so in the following manner:

* Add all empty pixels adjacent to the player/intersection to a list.
* Loop through the list removing pixels if the next item in the list is adjacent (in the game field) to the one you're on.

Once you have pixels from all possible sides of the intersection, run A\* on each possible pair. (See http://www-cs-students.stanford.edu/~amitp/gameprog.html#paths or Google a-star for more information.) If a path can be found between a pair, remove one of the connected pixels from the list.

After looping and pathing for all pairs, the pixels that remain should each be in a separate, enclosed area! To get all the pixels in each area, perform a flood fill from that area's pixel. See http://en.wikipedia.org/wiki/Flood\_fill.

Good luck!
> 1 votes

# Answer
Your areas are just series of points. The hard work comes with taking the series of points forming (usually) a concave polygon and triangulating them so you can render and probably project a texture on to them. See http://en.wikipedia.org/wiki/Polygon\_triangulation for more details
> 0 votes

# Answer
What I did was represented the main area with a grid, with values depending on grid content (empty area (0), inner polygon (1), current path(2), old (4), fast filled (8), ...). Single byte is enough to store the information of a grid.

In order to have newly created polygon at least size 1 + all borders, minimum movement in each directions was always 3 grids.

Inner polygon is the polygon which borders unclaimed area. Movement is only possible on grids that belong to *inner polygon* (other values are mainly for painting purposes).

My approach was:

* You draw a path, until you intersect with current inner polygon
* The properties of this path are: first (`path[0]`) an last (`path[-1]`) points lies on current inner polygon, but for the second point (`path[1]`) this holds true in all cases: if we find grids in all four directions, two grids would be on the path, one would be in the area without Qix (`inner`) and one would be in the area with Qix (`outer`).
* for the duration of searching I set the second point (`path[1]`) in the path to empty (0)
* I randomly select one of the two points (`inner`, `outer`)
* I perform A\* from Qix's location to `path[1]`
* if `outer` was selected, it would be found as previous node of the node corresponding to grid `path[1]` (there is no need to reconstruct the path, we check the previous node of node we searched for).
* the value of `path[1]` is set back to *current path*.

Now we clearly know which point is `inner` and which is `outer`. But, before we continue, we need to identify the common edges of polygon which still belongs to inner polygon and newly created claimed polygon:

* we create new point (TBP, temporary blocking point), we will use this point to force A\* to search in a single direction only
* if `outer` lies on inner polygon then `TBP <- outer`, else TBP is point that lies in an opposite direction of vector `path[0]` -\> `path[1]`, from `path[0]` (two cases: whether we start new polygon perpendicular on some edge or as extension ...)
* set value of TBP to empty space (0)
* set values for first (`path[0]`) and last node (`path[-1]`) in path to *inner polygon*
* perform A\* from first (`path[0]`) and last node (`path[-1]`). We are searching only on grids that has values *inner polygon*. Only one solution is possible. Change values to nodes in the path to *old*. This path is removed from *inner polygon* and movement on it are not possible anymore.
* set value of TBP to *inner polygon* (1)

And finally:

* set all nodes in the `path` to *inner polygon* (1)
* perform FloodFill from `inner` point

Algorithm can be applied in any language.
> 0 votes

---
Tags: algorithm, pygame
---


# Question
Title: How to set the z axis bound of the collider of child of an instantiated object to zero
I have attached a script to an empty `GameObject` to instantiate a prefab and the script is:

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

public class Circles : MonoBehaviour
{
    [SerializeField] float Xmax;
    [SerializeField] float Xmin;
    [SerializeField] float Ymax;
    [SerializeField] float Ymin;

    [SerializeField] float outsideMaxsize;
    [SerializeField] float outsideMinsize;
    float insideMaxsize;
    float insideMinsize;

    public GameObject[] enemy;
    GameObject enemyObject;

    int enemyNo;

    float Xpos;
    float Ypos;
    float outsideSize;
    float insideSize;

    // Start is called before the first frame update
    void Start()
    {
        enemyNo = Random.Range(0, 4);

      instantiator();
    }

    // Update is called once per frame
    void Update()
    {

    }
    public void instantiator()
    {
        Xpos = Random.Range(Xmin, Xmax);
        Ypos = Random.Range(Ymin, Ymax);

        outsideSize = Random.Range(outsideMinsize, outsideMaxsize);

        Vector2 circlePos = new Vector2(Xpos, Ypos);
        transform.position = circlePos;

        enemyObject = GameObject.Instantiate(enemy[enemyNo], transform.position, transform.rotation,transform.parent) as GameObject;

        var enemies = enemyObject.transform;
        var outsideComponent = enemies.GetChild(0);
        var insideComponent = enemies.GetChild(1);
        outsideComponent.transform.localScale=new Vector2(outsideSize, outsideSize);
        insideMaxsize = outsideSize * 0.5f;
        insideMinsize = 0.15f;
        insideSize = Random.Range(insideMinsize, insideMaxsize);
        insideComponent.transform.localScale = new Vector2(insideSize, insideSize);

        enemyNo = Random.Range(0, 4);
    }
}

```

And I have attached a script to the prefab which is being instantiated and that script is:

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

public class destroyer : MonoBehaviour
{

    Circles circles;

    CircleCollider2D collider1;
    Collider2D collider2;

    private void Start()
    {

        circles = FindObjectOfType<Circles>();

        print("1 max"+collider1.bounds.max);
        print("1 min" + collider1.bounds.min);
        print("2 max" + collider2.bounds.max);
        print("2 min" + collider2.bounds.min);

    }

    private void OnEnable()
    {
        collider1 = gameObject.transform.GetChild(0).GetComponent<CircleCollider2D>();
        collider2 = gameObject.transform.GetChild(1).GetComponent<Collider2D>();
    }

    void OnTriggerStay2D(Collider2D other)
    {
        print("star max"+other.bounds.max);
        print("star min" + other.bounds.min);

        if (collider1.bounds.Contains(other.bounds.max) && collider1.bounds.Contains(other.bounds.min))
       {

            if (other.bounds.Contains(collider2.bounds.max) && other.bounds.Contains(collider2.bounds.min))
            {

                    Destroy(other.gameObject);
                    Destroy(gameObject);
                    circles.instantiator();

            }

        }
    }
}

```

the problem is that the z axis bounds of the colliders are coming out to be 15.8 when the prefab is instantiated and when I drag the prefab to scene then the z axis bounds of the collider is 0. I want the z axis bounds of the colliders to be 0 when the prefab is instantiated

# Answer
The simplest way to fix this is to spawn your prefab at a position that places its children in the same z-plane as the objects you're hoping to detect.

So for example if the object you want to detect is at z=0, and your prefab's children are at z = 1 relative to their parent, and their parent isn't scaled in the z axis or rotated in the x/y axes, then you would need to spawn the parent at z = -1 to cancel-out the child colliders' offsets so they'll sit at the z = 0 plane.

Since you haven't shown us enough details of your setup for us to tell you exactly what position values to change, another option is to exclude Z from consideration in your test. We can do this by adding an extension method:

```
public static class PhysicsExtensions {
    public static bool Envelops2D(this Bounds a, Bounds b) {
        return (b.max.x <= a.max.x)
             & (b.max.y <= a.max.y)
             & (b.min.x >= a.min.x)
             & (b.min.y >= a.min.y);
    }
}

```

Then you can change your if clauses to...

```
if (collider1.bounds.Envelops2D(other.bounds))
{
    if (other.bounds.Envelops2D(collider2.bounds))
    {
         Destroy(other.gameObject);
         Destroy(gameObject);
         circles.instantiator();
    }
}

```

Note that this is using only the bounding rectangles of your colliders, not their actual shapes. So for example this will say a radius-8 circle collider at (0, 0) envelops a radius-1 circle collider at (7, 7), even though that second circle is completely outside the first, but still inside its bounding rectangle. You can use radius and distance checks instead of bounds checks if you want to take the circular shape of the colliders into account.
> 0 votes

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


title: Shifting Skill Tree

text:
# Question
Title: Shifting Skill Tree
I have been thinking of implementing a system like Wolcen does for their skill tree, however I want to use it for level unlocks.

Nodes grouped in segments and multiple segments from a ring (see picture attached)

Each inner segment touches two of the next outer ring' segments, and when each ring is rotated, the nodes are able to be connected the newly rotated section.

A static model of this is simple using a tree structure, where each segment is a tree-node in the tree and each tree-node contains an array of skill-nodes.

How would one achieve a the shifting functionality?

**EDIT:**

Starting State:

```
      1             Level 1
    /   \
   2     3          Level 2
 /     /   \
4     7     8       Level 3

```

Trying to Achieve:

```
      1             Level 1
    /   \
   3     2          Level 2
 /     /   \
4     7     8       Level 3

```

in other words, the children should not be affected of the parent shifting position.

# Answer
Let's say you have two ordered lists of nodes that connect two rings. For this example:

* `list1` is the more inner ring with nodes `a b d c`
* `list2` is the more outer ring with nodes `Q R S T`

I'm going to refer to the nodes & edges between rings as 'spoke nodes & edges' and I'm going to assume that they line up in a one to one fashion. That means there will be the same number of spoke nodes connecting one ring to the next and each has exactly one spoke edge.

So maybe we have something like this:

```
Q-----R
|\   /|
| a-b |
| | | |
| d-c |
|/   \|
T-----S

```

To shift or rotate a ring, all you need to do is go through the spoke nodes of each list & shift the relevant connections:

```
rotateOuterRingBack(list1);

void rotateOuterRingBack(List<Nodes> list){
  Node tempSpokeNeighbor = list.get(0).getSpokeNeighbor();

  for(int a=0; a<list.size()-1; a++){
    Node currNode = list.get(a);
    Node nextNode = list.get((a+1)%list.size());
    Node currNode.setSpokeNeighbor(nextNode.getSpokeNeighbor));
    Node currNode.getSpokeNeighbor().setSpokeNeighbor(currNode);
  }
  Node lastNode = list.get(list.size()-1);
  Node lastNode.setSpokeNeighbor(tempSpokeNeighbor);
  Node lastNode.getSpokeNeighbor.setSpokeNeighbor(lastNode);
}

```

Applying this to the example given, the result would be:

```
R-----S
|\   /|
| a-b |
| | | |
| d-c |
|/   \|
Q-----T

```

Rotating in the opposite direction is similar, but requires traversing the list in the opposite direction.

This could be extended to handle ring to ring connections that aren't one to one - the basic idea remains the same, but the implementation gets more complex.
> 1 votes

---
Tags: game-design, architecture, algorithm
---


# Question
Title: Player jitters when Jumping at object edges
So I have a bit of an issue with my Player controller script. Everything works fine except with very specific jump cases. If I jump at an object and I don't reach the top edge I will just fall normally with no issue. However, when the object is short enough for me to possible jump on top of it, if I collide with its side when jumping my player will halt in that spot, jitter for a second and then fall normally.

Here is my code:

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

public class ThirdPersonPlayerController : MonoBehaviour
{
    public CharacterController controller;
    public Transform camera;
    public Transform groundCheck;

    Vector3 direction;
    Vector3 velocity;

    public float moveSpeed = 10f;
    public float turnSmoothTime = 0.1f;
    private float turnSmoothVelocity;
    public float gravity = -39.24f;
    public float groundDistance = 0.4f;
    public float jumpHeight = 3f;

    public LayerMask groundMask;
    private bool isGrounded;

    // Update is called once per frame
    // Unity is currently working on a new input system***
    private void Update()
    {
        IsPlayerGrounded();

        float horizontal = Input.GetAxisRaw("Horizontal");
        float vertical = Input.GetAxisRaw("Vertical");
        direction = new Vector3(horizontal, 0f, vertical).normalized; // direction player is moving

        if (Input.GetButtonDown("Jump") && isGrounded)
        {
            Jump();
        }

        MoveAndRotate();
        Gravity();
    }

    private void MoveAndRotate()
    {
        if (direction.magnitude >= 0.1f)
        {
            float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + camera.eulerAngles.y;
            float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
            transform.rotation = Quaternion.Euler(0f, angle, 0f);

            Vector3 moveDirection = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
            controller.Move(moveDirection.normalized * moveSpeed * Time.deltaTime);
        }
    }

    // Implemented proper gravity from /_\ y = 1/2g * t^2
    private void Gravity()
    {
        velocity.y += gravity * Time.deltaTime;

        controller.Move(velocity * Time.deltaTime);
    }

    // Check if player is grounded and reset velocity
    private void IsPlayerGrounded()
    {
        isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

        if (isGrounded && velocity.y < 0)
        {
            velocity.y = -2f;
        }
    }

    private void Jump()
    {
        velocity.y = Mathf.Sqrt(jumpHeight * -2 * gravity);
    }

    // Current issue (Not yet fixed): When jumping against a wall the player will stick/jitter (starts to jitter at the top edge).
}

```

Here is a visual representation of what I mean by colliding near its top edge

Any help at all is greatly appreciated. Note: I thought it had something to do with objects having the Ground layer attached to them, but the bug is still present if they don't have a layer.

# Answer
I combined the two controller.Move in one single line (on my personal script) like this :

```
controller.Move(((move * speed) + velocity) * Time.deltaTime);

```

or this (more readable) :

```
controller.Move(move * speed * Time.deltaTime + velocity * Time.deltaTime)

```

And it fixed my issue.

Hope it works on your game
> 1 votes

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


# Question
Title: Unity Animator animations fail to play only when triggered by user input
I have a unity animator setup like so. When the game runs, I can trigger each state in the state machine with user input. I can use `HasExitTime` flag to trigger the animation, and it will play through and loop infinitely as expected.

However, when I try to use the `GearChange` trigger, the state machine progress bar plays, the correct box is triggered, but the animation itself doesn't play! I'm at a total loss as to what the problem is here, as everything else is exactly the same, minus the user input.

The console isn't showing any errors, the animation simply doesn't respond to the state machine. What am I missing here?

Unity version 2020.1.0f1

So I deleted the animator, and setup everything again the exact same way. Now the animation won't play, period. The state machine progress bars are still triggered as expected, but the animation won't play.

In the transition preview, the animation won't play there either.

# Answer
> 0 votes
The problem here turned out to be the lack of assignment of an avatar to the animator. Without an avatar assigned, the behavior of the animator component was all over the place. Sometimes working, sometimes not working for the exact same settings.

When I assigned the animator an avatar (you can use the unity tools to do so via: Find your animation file -\> Select 'Rig' -\> Under Avatar Definition Select 'Create From Model'

Unity will then create an avatar for your animation. When add the animator to your game object, you can assign an avatar to the component. Pick the one unity generated.

My best guess is that this unexpected configuration caused a bug in Unity. IMHO, they'd be better off to throw an error for you, but it's immaterial now.

---
Tags: unity
---


# Question
Title: SetCursor: Cursor does not contain a definition for "SetCursor' or why can't I re-assign the cursor in Unity 20194.7f?
Here is the code I used on Cursor script, attached to a chest object.

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

public class Cursor : MonoBehaviour
{

    public Texture2D cursorArrow;
    // Start is called before the first frame update
    void Start()
    {
        //Cursor.visible = false;

        Cursor.SetCursor(cursorArrow, Vector2.zero, CursorMode.ForceSoftware);
    }

}

```

For some reason, I can no longer reset cursor properties and I don't know why. Please help?

# Answer
You named your MonoBehaviour class "`Cursor`" so when you write the word "`Cursor`" inside the body of that class, the compiler thinks you're trying to refer to your MonoBehaviour (which has a method called `Start`, and no method called `SetCursor`)

Solution: name your class something that does not collide with other types you want to use, like `public class CustomCursor : MonoBehaviour ...`
> 1 votes

---
Tags: unity, mouse, settings
---


# Question
Title: Cannot find folder when building game to .jar LibGDX
Whenever I run my game from my IntelIJ IDEA the game runs fine. It finds every folder and every asset in there. But whenever I build my game with `:desktop:dist` and run it it will not see the folder I try to open as a folder and it will have 0 contents.

This is the code I use to open the folder:

```
        FileHandle mapFolder = Gdx.files.internal("maps");

    System.out.println(mapFolder.list().length);

    for (FileHandle entry : mapFolder.list()) {
        System.out.println("something is in");
        maps.add(new Map(entry.toString()));
    }

    loadMap(maps.get(0));

```

The length it prints is 0. It does not print `something is in`so im fairly sure this is not working.

Whenever I try `Gdx.files.classpath` I get this error: `Caused by: com.badlogic.gdx.utils.GdxRuntimeException: Cannot list a classpath directory: maps`

For clarification: It's a desktop only project. So no android.

I cannot figure it out, and I've looked at a lot of topics to try and fix this issue.

# Answer
> 1 votes
Just like the error says, you can not list all assets in a `classpath` FileHandle. The reason you're seeing this error even though you're using an `internal` file handle is because `internal` files are added to the `.jar` when the game is built (where else would they go?) and as such they must be added to the classpath to be readable. This is also the reason you can't write to an `internal` file, since internal files are converted to `classpath` files when the jar is built, and you can not edit classpath files.

Since you know all the files in the classpath at runtime you are expected to simply manually list them:

```
final String[] files = { "map1", "map2", ... };
final FileHandle[] handles = Stream.of(files).map(Gdx.files::internal);

```

If you want to be able to actually list contents of a file handle it has to be `external` or `local`. An `external` file is just any file on the user's computer. A `local` file is the same as `external`, except that the source directory is the same folder that your game's jar is inside. E.g. if your jar is inside `C:/Program Files/MyAwesomeGame/game.jar` then all `local` files would be relative to `C:/Program Files/MyAwesomeGame/`. This is especially useful when you want files to be editable, e.g. configuration files and save files.

# Answer
> 0 votes
Try to rebuild the project. Maybe it is corrupted.

Try creating again the folder and it's contents. I saw a guy with a similar problem and he said creating everything again worked.

---
Tags: java, libgdx, file
---


# Question
Title: get access to Transform of a Clone in Unity
In my game when you lose, A panel with a button on it appears and if you don't have enough coins, You may be directed to shop by hitting shop button. when buying is completed you can return to the scene from where you left it and resume the game. I'm using PlayerPrefs to save properties like slider.value my player position timescale etc, But I can't access to Transform of an Instantiated GameObject (Clone). it acts like obstacle and is Instantiated continuously. Here is my script;

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using CodeStage.AntiCheat.ObscuredTypes;
using CodeStage.AntiCheat.Detectors;

public class Spawner5 : MonoBehaviour {

    public float maxTime=1;
    public float Timer = 0;
    public GameObject pipe;
    public float height;

    // Use this for initialization
    void Start () {

        pipe = GameObject.FindGameObjectWithTag ("Gear");
    }

    // Update is called once per frame
    void Update () {

        if (Timer > maxTime) {

            GameObject newpipe = Instantiate (pipe);

            newpipe.transform.position = transform.position + new Vector3(4, Random.Range (-height, height) ,0);

            Destroy (newpipe, 15);
            Timer = 0;

        }

        Timer += Time.deltaTime;
    }
}

```

# Answer
I solved my problem by using ***LoadSceneMode.Additive***
> -1 votes

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


# Question
Title: Working with Screen Space - Overlay canvases
So, say you've started a new project. You drop your in desired sprite. You can see how big it is relative to the Main Camera. That's cool.

Now you want to add a persistent bit of UI to the game, so you use a canvas in the "Overlay" mode. That canvas is added in but is hundreds of times bigger than your Main Camera view.

My question is, are you all just cool with that? Or is there something I should do? It's a bit odd that there's some massive UI taking up so much space in my Scene view. If I want to add something to it, I have to zoom out for a while before it fits in my view.

I'm new to Unity development, so it's possible that's just how things are. But I was wondering if I'm misunderstanding something.

# Answer
It's like this because UI is usually laid out in pixel coordinates, rather than the game's world coordinate system.

I usually just double-click or hit F to center on what I need to look at, and use the Game window for verifying the look of the whole.

You can adjust your Canvas settings and PPU/reference PPU values to bring this layout space smaller, but in my experience that's been more trouble than it's worth.
> 2 votes

---
Tags: unity, unity-ui
---


title: Irregular Shaped Colliders For Unity

text:
# Question
Title: Irregular Shaped Colliders For Unity
Is it possible to create an irregular-shaped collider? If so, how? Would I need to create a couple objects and group them up into one Game Object?

# Answer
> 4 votes
Mesh colliders and parented objects are the only real way to do things, Unity or otherwise. Note that mesh colliders can be a lot more expensive, but are the only choice if you need fairly detailed collision handling for "irregular" objects.

# Answer
> 3 votes
If you don't want to use a mesh collider (maybe for performance reasons), you can build a compound collider as described halfway down this page.

# Answer
> 0 votes
I know it's 8 years later, but Unity still doesn't seem to have an inbuilt solution for irregular 3d shapes.

I ended up writing a class for irregular boxes. If 2 boxColliders collide, it checks further if the meshFilter's meshTriangles of box A intersect with meshFilter's meshTriangles of box B. It's not cheap at all, but for 12 triangles per cube it's fast enough. I use a different method when other mesh types are involved.

Heron solved quite all the problems some time ago, what a genius! This link also helped me a lot, check for `PlanePlaneIntersection`.

---
Tags: unity
---


# Question
Title: GLSL: How can I optimize this lighting (fragment) shader? Basic 2D game, 30+ light sources cause significant frame loss
I am using a fragment shader to create circular light sources in my 2D game. Full code at the bottom.

Essentially, an array of light source objects (called Lights in the code) are passed into the shader in groups of 40. The shader runs through a for loop for each light source in the batch (up to four) and attenuates the brightness of that pixel based on how far away from the light source it is. If there are more than forty light sources, additional passes of this shader are done until all the light sources on the screen are processed. Limiting the lights per shader pass is done to limit how much data is pushed to the GPU at once (this is what the book I am reading is telling me to do) to improve performance.

It works fine, but I notice pretty dramatic frame rate loss when the number of light sources on the screen exceeds 30 or so. By the time I'm at 80 or 90 light sources, the frame rate is down to about 10 fps. Not cool.

Some questions:

1. What sticks out in the loop as the most expensive operations, and how can they be done better? I have been commenting out some of these I try to see what effect each line has. Is there a better way to do this? **How do I profile a shader program?** I am new to this. Any help would be appreciated.
2. As you can see, I am using an older version of GLSL because I am using macOS X (version 1.20). Would this shader work more efficiently on a different platform with a new version of OpenGL?
3. I'm considering the possibility that 30+ light sources is simply too much I need to seek a way to optimize the shading process outside of this shader loop. I am using a deferred rendering process, but I have read about how some games render lighting using a partition light sources into different regions. I.e., a light source only affects pixels within a region around it (that it could reasonably affect), so that you don't have to run a calculation for every single pixel on the screen for each light source. Kind of like doing a broad-phase pass for collision detection. **How do 2D games typically handle many light sources?**

```
#version 120
uniform sampler2D LastPass;
uniform sampler2D DiffuseMap;
uniform vec3 AmbientLight;
uniform int LightCount;
uniform int PassNumber;

struct LightInfo {
    vec3 position;
    vec3 color;
    float radius;
    float falloff;
};

const int MaxLights = 40;
uniform LightInfo Lights[MaxLights];

void main()
{
    vec4 pixel = texture2D(LastPass, gl_TexCoord[0].xy);
    vec4 diffusepixel = texture2D(DiffuseMap, gl_TexCoord[0].xy);

    vec4 finalPixel = gl_Color * pixel;

    for(int i = 0; i < LightCount; ++i) {

        LightInfo light = Lights[i];
        vec3 L = light.position - gl_FragCoord.xyz;
        float distance = length(L);
        float d = max(distance - light.radius, 0);
        L /= distance;
        // calculate basic light attenuation
        float attenuation = 1 / pow(d/light.radius + 1, 2);
        // scale and bias attenuation such that:
        //   attenuation == 0 at extent of max influence
        //   attenuation == 1 when d == 0
        attenuation = (attenuation - light.falloff) / (1 - light.falloff);
        attenuation = max(attenuation, 0);

        //This line runs VERY slow when there are many light sources.
        finalPixel += (diffusepixel * ((vec4(light.color, 0.4) * attenuation)));

    }
    gl_FragColor = finalPixel;

}

```

Thanks for any help.

# Answer
> 3 votes
Switching to deferred shading would be the best solution with this many lights. ( https://en.wikipedia.org/wiki/Deferred\_shading )

> I am using a deferred rendering process

```
vec4 pixel = texture2D(LastPass, gl_TexCoord[0].xy);

```

That is not proper deferred rendering.

You're supposed to accumulate all the light values by drawing additively into a lighting buffer (letting the GPU's memory/cache subsystem do the accumulation) and when this is completed combine both the diffuse and lighting buffers in one final pass.

And draw each light as a quad/triangle over the lighting buffer covering only their visible radius.

But without re-engineering the whole pipeline the first thing would be to remove some of the divisions and use pre-calculated reciprocals.

Transform:

```
attenuation = (attenuation - light.falloff) / (1 - light.falloff);

```

Into:

```
attenuation = (attenuation - light.falloff) * light.one_minus_falloff_inverse;

```

By pre-calculating `one_minus_falloff_inverse` as `1.0f/(1 - light.falloff)` on the CPU.

Turn `d/light.radius` into `d*light.radius_inverse`...

And this is a red-herring:

```
    //This line runs VERY slow when there are many light sources.
    finalPixel += (diffusepixel * ((vec4(light.color, 0.4) * attenuation)));

```

Commenting out this line makes everything faster because the shader compiler eliminates the entire loop and removes one texture lookup because nothing in the entire calculation is useful when that line of code is gone.

See "Dead code elimination" ( https://en.wikipedia.org/wiki/Dead\_code ) done by compilers.

# Answer
> 3 votes
The method used by Doom 3 - which is, admittedly, fairly old, but that probably makes it more relevant to the downlevel GLSL version you're using - goes like this:

* Clear to black (you could make this your ambient light colour if you wish).
* Do an initial depth-only pre-pass of the entire scene.
* Enable additive blending (via glBlendFunc (GL\_ONE, GL\_ONE)).
* For each light:
    + Draw all surfaces hit by that light.

This obviously requires multiple passes over your scene rather than doing everything in a single pass, but - as I indicated - the existence proof that it works is Doom 3.

The key difference is that your shader now only handles one light, but you get the ability to have any arbitrary number of total lights in your scene; it also simplifies your shader and removes any ambiguity about whether that's a bottleneck for you.

Of course Doom 3 is not a 2D game, but there's no reason why this method couldn't be used in a 2D game as much as in a 3D game.

---
Tags: opengl, glsl
---


# Question
Title: Unity: How to Retrieve Port Number Used for Test Build
## SUMMARY

I am looking for a straightforward way to get the port number that the Unity editor is using to serve WebGL test builds after the build's browser window has been closed.

I'm supporting Unity students who are not computer savvy. I'd like to know if there's an easy way to get this information from the editor itself, short of rebuilding the project.

## DETAILS

To test my Unity WebGL project from the Unity Editor, I select the menu "File \> Build and Run."

Once the project is built, a Chrome window opens with a location of the form "http://localhost:53587/", where 53587 is a random port number.

## WHAT I HAVE TRIED

Google searches haven't given me an easy way to discover this port.

Using Window's Resource Monitor, I can find all the ports unity test servers are listening on, but this method requires many steps and external tools. I'd like know if there is a way within Unity to discover this information.

## Complicated Method

1. Press Ctrl+R to open the Run window.
2. Type `resmon.exe` and press `ENTER`
3. Select the `Network` tab
4. Select the `Listening Ports` bar
5. Sort on image by clicking on the `image` column header
6. Search for image `mono.exe`
7. Get port number(s) from `Port` column.

This is relatively complicated, Windows-specific method and it's inexact; it can return multiple instances of test builds being served. I'd like an easy way of discovering the port being served for the project currently being edited.

# Answer
> 2 votes
There doesn't seem to be a way to do this. I did a bit of digging on a fresh install of Unity 202.1.1f1. Note that on different versions the behaviour might be different, but I would assume that at least for reasonably recent versions the following holds:

A forum thread here mentioned that Unity starts `<Version>\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\SimpleWebServer.exe` to run the game locally. This executable accepts the port to start the server on is passed via a command line parameter, so we need to find the place where this is generated.

This happens to be in `<Version>\Editor\Data\PlaybackEngines\WebGLSupport\UnityEditor.WebGL.Extensions.dll`, under which a class called `HttpServerEditorWrapper` can be found via decompilation. This contains code for launching `SimpleWebServer.exe`, but unfortunately, it turns out that it uses a function named `GetRandomUnusedPort()`, which essentially uses the C# `TcpListener` to open a temporary connection with the default port `0`, which the C# documentation says the following:

> In this case, the service provider will assign an available port number between 1024 and 65535.

After opening the temporary connection, the opened port is queried, temporary connection is closed, and the available port is passed as a command line parameter to `SimpleWebServer.exe`.

As a result, it seems that you are at the mercy of the operating system. Perhaps you could look into hosting the built project via an alternative custom method where you can configure the port yourself? Search engines know more about this, but for an example Python comes with a ready to use HTTP server that one can start in a directory to serve its contents.

---
Tags: unity
---


# Question
Title: How can I add orbit effect to the camera?
On my player I have the component Animator , Rigidbody , Capsule Collider , Third Person User Control script , Third Person Character script.

On the Main Camera there are two scripts but only one is activated for now : Camera Follow and Mouse Orbit With Zoom :

The Camera Follow script is working fine. The problem is when I'm activating the Mouse Orbit With Zoom script if I move the player with the keys WASD and also rotate orbit the camera with the mouse the player lose focus. He does change his direction according to the mouse rotation but also lost focus :

And also for some reason I can make the camera rotation to be diagonal:

The reason Main Camera is not child of the player is that it's making the camera stuttering and rotating very fast on place. That is why I added the Camera Follow script.

The Camera Follow script :

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

public class CameraFollow : MonoBehaviour
{
    public Transform player;
    public Vector3 offset;

    // Update is called once per frame
    void Update()
    {
        transform.position = player.position + offset;
    }
}

```

The orbit script :

```
using UnityEngine;
using System.Collections;

[AddComponentMenu("Camera-Control/Mouse Orbit with zoom")]
public class MouseCameraOrbit : MonoBehaviour
{
    public Transform target;
    public float speed;

    private void Update()
    {
        if (Input.GetMouseButton(0))
        {
            transform.RotateAround(target.position,
                                            transform.up,
                                            -Input.GetAxis("Mouse X") * speed);

            transform.RotateAround(target.transform.position,
                                            transform.right,
                                            -Input.GetAxis("Mouse Y") * speed);
        }
    }
}

```

My game is adventure game type and the main goal is to make player movement to be with the keys and also to be able to look around like orbiting with the mouse because only following the player will not show where to go , that is why I'm trying to add orbiting, but the orbiting part is just not working good.

# Answer
> 1 votes
You might be able address the "camera stuttering" issue by replacing `Update` with `LateUpdate` in `CameraFollow.cs`

**This uses `LateUpdate()` which ensures the camera positioning occurs after any transforms in Player.Update() and any physics effects**

```
public class CameraFollow : MonoBehaviour
{
    public Transform player;
    public Vector3 offset;

    void LateUpdate()
    {
        transform.position = player.position + offset;
    }

...

```

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


title: How to select light as sun source

text:
# Question
Title: How to select light as sun source
I tried to add a sun in the lighting setting. I have a directional light in my scene, but i can't select it as sun source in lighting setting. The light does not appear in the list. Does anyone know what is wrong ?

# Answer
Make sure that your tab is set to "Scene" instead of "Assets" (shown in image), since it defaults to the latter.
> 1 votes

---
Tags: unity
---


# Question
Title: Load order of networked objects in Unity
I am making a 2D RTS, and am trying to get a multiplayer version working. I've run into some problems with the order that scripts are getting executed. For the host everything runs fine, but when a new client connects, I get a lot of bugs. What's happening is that the objects that I've spawned already are getting loaded into the new client's scene before things they depend on, like the map itself. When I was writing the code, I was thinking that there's no way that something user-created could get get loaded before the map, because the map gets loaded right when game starts, but the order in which UNET loads spawned items seems to be weird like that.

Is there anything I can do to change this, or do I just need to rewrite things so that the loading of spawned items doesn't require the map to be loaded?

Thanks

# Answer
> 1 votes
Through some more experimentation, I think I've fixed the problem. The messages were all getting sent in the right order and getting received in the right order. The problem before was that the map wasn't networked, so it wasn't in that sequence of messages, and actually got started after all those messages were processed.

I ended up just making the map networked, which I should've done to start with anyway, so now it's the first thing that gets started, and the problem is solved.

# Answer
> 0 votes
The best way to create things in the correct order is to have a single point of entry, that is, a function that creates everything in order.

Also, if you have objects with cross-references, another option would be to create the objects first, and then create the references.

---
Tags: unity, networking, unity-networking
---


# Question
Title: How can I avoid a stack overflow when recursively checking adjacent game objects?
I am building a simple game on Unity to learn the system. I am using C#.

The game is a basic "blocks" game, whereby when the player clicks on a block, the block and its neighbours of the same colour all disappear (get destroyed).

My process is this:

* To keep a track of which blocks are neighbours of the same colour, on each refresh each block checks their details on the event `OnCollisionEnter` and adds these collision neighbours to a List of valid neighbouring gameobjects.
* When a block is clicked, this list is checked and each neighbour has its own neighbours list checked, after list checking each block is distroyed.

Somehow, this process is causing a StackOverflowException

> StackOverflowException
> UnityEngine.GameObject.GetComponent\[setupscript\] () (at C:/buildslave/unity/build/artifacts/generated/common/runtime/GameObjectBindings.gen.cs:35)
> setupscript.checkNeighbours () (at Assets/scripts/setupscript.cs:86)
> setupscript.checkNeighbours () (at Assets/scripts/setupscript.cs:87)
> setupscript.checkNeighbours () (at Assets/scripts/setupscript.cs:87)
> setupscript.checkNeighbours () (at Assets/scripts/setupscript.cs:87)
> ....

Here is my script, first my List establishment:

```
 private List<GameObject> neighbours = new List<GameObject>();

```

Next, here is how the neighbours list is populated:

```
void OnCollisionEnter (Collision other)
{
    Rigidbody other_rb = other.rigidbody;
    if(rb.velocity.magnitude < 1f && other_rb.velocity.magnitude < 1f
        && other.gameObject.tag == tagName && !neighbours.Contains(other.gameObject)) {
    /***
     * Same tag so add to list of valid neighbours
     ***/
        neighbours.Add(other.gameObject);
    }
}

```

Now, there are four conditions \[above\] to check when adding to the list:

* Is the current block stationary.
* Is the "other" colliding block stationary (so they're at rest next to each other).
* do these blocks have the same tag (so they're the same type/colour)
* does this block not already exist in this list.

So once all four conditions are met, the block `GameObject` is added to the List.

( On conditions of `OnCollisionExit` blocks are removed from the List in a similar fashion. )

Now, my `CheckNeighbours()` script:

```
public void checkNeighbours(){
    if (neighbours.Count > 0) {
        foreach (GameObject othercube in neighbours) {
            setupscript otherCubeScript = othercube.GetComponent<setupscript>();
            otherCubeScript.checkNeighbours();
        }
    }

    Destroy (gameObject);
}

```

This should, as far as I understand it, run once through each List element and check that element for any neighbours who match.

As I write this question out I *think* I'm realising that the issue is that we're in a loop as block 1 references neighbour block 2, which references neighbour block 3, which references neighbour block 1, etc. etc.

But my StackOverflow exception occurs when there are only two blocks, so one refers to the other, refers to the first, etc. But as they should destroy after running the reference, this shouldn't (ideally) be an issue? **Do I need to make the `checkNeighbour()` a Corountine to allow it to not hold up destroying the GameObject?**

If this \[repetition cycling\] is indeed what's going on, what would be the best way of getting each neighbour to be checked only once? Or checking that the GameObject referenced in the List still exists in the game itself?

I have a quick edit here:

```
foreach (GameObject othercube in neighbours) {
    if (othercube != null){
        setupscript otherCubeScript = othercube.GetComponent<setupscript>();
        otherCubeScript.checkNeighbours();
    }
}

```

But I'm not sure this will work as I feel this List will purely be a reference rather than the actual GameObject in the level?

# Answer
You are correct in that your problem is caused by two objects referencing each other. That causes each object to call "check neighbors" forever on its neighbor.

`checkNeighbors` calls `checkNeighbors` on adjacent objects *before* it even attempts to `Destroy` a game object, although fixing that ordering problem would likely lead you to a different issue: trying to call `checkNeighbors` on a destroyed object (`Destroy` will not, on its own, remove an object from a neighbor list).

A typical way to handle these kinds of "flooding" recursive algorithms is to *mark* objects you have visited already. You can do this with a flag on the object itself, although this is somewhat brittle. You can also do it by keeping a `HashSet<T>` or similar of all the objects you have visited.

`checkNeighbors` would then take an extra parameter, this set, and would do something like:

```
if (set.Contains(thisObject)) {
  return; // Already processed.
}

set.Add(thisObject);

// ...do work...

```
> 6 votes

# Answer
also two oncollenters in two scripts on both bodies seems to create an indeterminate condition...

try deleting one of the collider/scripts. let it think of one thing at a time.
> -1 votes

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


# Question
Title: Reacting to button holds of different durations for an anxiety game
I am working on an interactive game to aid with anxiety management.

In one of the gameplay options, the player has to press buttons for a certain amount of time. Only after the required time has elapsed (with the player holding the buttons down), will the avatar move. So for example, the instruction will be "Press the buttons for 20 seconds to move the player". This part is working.

As this is an anxiety game, however, I want to incorporate some breathing activity/instruction into the gameplay. I have chosen to use the 4-7-8 second rule, whereby the player breathes in for 4 seconds, holds their breath for 7 seconds and exhales for 8 seconds. I have no idea how to incorporate something like this into my existing game. I understand that a second timer would be needed, but how would that be able to discern between the 4 seconds, 7 seconds and 8 seconds?

Attached is my timer script:

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

public class Timer : MonoBehaviour
{
    public int timeLeft;
    public Text countdownText;
    private bool timerStarted;

    int start;

    public void BeginTimer()
    {
        StartCoroutine(LoseTime());
    }

    void Awake()
    {
        start = timeLeft;
    }

    public void StopTimer()
    {
        StopAllCoroutines();
        Respawn.Instance.Player2.transform.position = Respawn.Instance.RespawnPoint2.transform.position;
        PlayerController.Instance.timerStarted = false;
        timeLeft = start;
        countdownText.text = "Time Left= " + start;
    }

    private IEnumerator LoseTime()
    {
        while (timeLeft > 0)
        {
            yield return new WaitForSeconds(1);
            timeLeft--;
            countdownText.text = "Time Left= " + timeLeft;
        }

        PlayerController.Instance.Character.GetComponent<Rigidbody2D>().AddForce(PlayerController.Instance.height, ForceMode2D.Impulse);
         //SphereController.Instance.Player.GetComponent<Renderer>().material;
        print("hi");
    }

    public void ChangeLevel()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
    }
}

```

And my playercontroller script:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO.Ports;
using UnityEngine.UI;

public class PlayerController : MonoBehaviour
{
    public static PlayerController Instance { set; get; }
    public float Speed;
    public Vector2 height;
    public float xMax, xMin, yMin, yMax;
    public bool buttonPressed = false;

    public Rigidbody2D Character;
    public Timer timer;
    public Rigidbody2D _rigidbody;

    public bool timerStarted = false;

    private SerialPort sp = new SerialPort("\\\\.\\COM4", 9600);

    Animator anim;
    string value;
    int button;

    private void Awake()
    {
        FetchReferences();
        Instance = this;

        //print("hi");

        if (AvatarChooser.ava == 1)
        {
            anim = GameObject.FindWithTag("Player").GetComponent<Animator>();
            anim.runtimeAnimatorController = Resources.Load<RuntimeAnimatorController>("3");
            //print("hi");
        }

        if (AvatarChooser.ava == 2)
        {
            anim = GameObject.FindWithTag("Player").GetComponent<Animator>();
            anim.runtimeAnimatorController = Resources.Load<RuntimeAnimatorController>("1");
        }

        if (AvatarChooser.ava == 3)
        {
            anim = GameObject.FindWithTag("Player").GetComponent<Animator>();
            anim.runtimeAnimatorController = Resources.Load<RuntimeAnimatorController>("2");
        }
    }

    [ContextMenu("FetchReferences")]
    private void FetchReferences()
    {
        if (!Character) Character = GameObject.FindWithTag("Player").GetComponent<Rigidbody2D>();
        if (!timer) timer = GameObject.Find("Timer").GetComponent<Timer>();
    }

    private void Start()
    {
        if (!sp.IsOpen)
        {
            sp.Open(); // Open
        }
        sp.ReadTimeout = 1;

        //print(AvatarChooser.ava);
    }

    private void Update()
    {
        if (sp.IsOpen)
        {
            try
            {

                value = sp.ReadLine(); //Read the information
                button = int.Parse(value);

                if (button == 9)/*(Input.GetKeyDown(KeyCode.Space))*/  //jump
                {
                    buttonPressed = true;

                   if (!timerStarted)
                    {

                        timerStarted = true;
                        timer.BeginTimer();
                    }
                }
                else
                {

                    timer.StopTimer();
                }
            }
            catch (System.Exception)
            {

            }
        }
    }

    private void FixedUpdate()
    {
        Character.position = new Vector3
                    (
                        Mathf.Clamp(GetComponent<Rigidbody2D>().position.x, xMin, xMax),
                        Mathf.Clamp(GetComponent<Rigidbody2D>().position.y, yMin, yMax)
                    );
    }

    void OnDisable()
    {
        sp.Close();
    }

}

```

# Answer
It looks like you're also reading your input from a specialized device of some kind. I'll show a conventional version with Unity's built-in input first, for simplicity, then mention how we can incorporate your custom input.

First we can set up a data structure you can use to associate a particular hold duration with a specific action:

```
// If you're using Unity 2020 you can skip this and use UnityEvent<float> directly.
[System.Serializable]
public class HoldEvent : UnityEvent<float> {}

[System.Serializable]
public struct HoldAction {
    public float targetDuration;
    public HoldEvent onHoldComplete;
}

```

This gives you a nice little inspector where you can wire up a function to call when the player releases the button after this hold.

I gave it a float argument so you can pass the signed error value: if the player released half a second too early, we still call the function, but with `-0.5f` as the argument. `0.0f` means they hit the target exactly, and greater than zero means they released late.

You can use this to give different effects and feedback for early/late releases - just be sure to give some tolerance for the limited update rate. eg. `if (Mathf.Abs(errorSeconds) <= 2.0f/30.0f)` will check if they were within about 2 frames of the target time.

Then we can make a script that takes an array of these hold actions, and steps through them in a sequence, 4-7-8-4-7-8... each time the player completes one hold, it advances to the next target duration automatically.

```
// Name of the button to read.
public string inputName;

// Ordered collection of holds you can set up in the inspector.
public HoldAction[] holdSequence;

// Which step of the 4-7-8 we're on now.
int _sequenceIndex;

// How many seconds we've been holding for.
float _holdDuration;

// This will return the current progress as a ratio versus the current target.
// 0 = not started, 1.0f = 100% complete, 1.1f = still holding 10% too long.
// You could use this to animate a progress bar or other feedback.
public float GetHoldProgress() {
    return (_holdDuration) /  (holdSequence[_sequenceIndex].targetDuration);
}

// If something breaks the player's rhythm, you can call this to start them back
// at the first hold in the sequence again.
public void ResetToStartOfSequence() {
    _sequenceIndex = 0;
}

void Update() {
    // You can release and re-press the input on the same frame if you're super fast
    // or the framerate is sluggish, so we check for a release first:
    if(Input.GetButtonUp(inputName)) {

        // We call the appropriate method for this step in the sequence,
        // passing the error as our argument.
        var reaction = holdSequence[_sequenceIndex].onHoldComplete;
        if (reaction != null)
            reaction.Invoke(_holdDuration - holdSequence[_sequenceIndex].targetDuration);

        // Then advance to the next hold in sequence (wrapping around),
        // and zero our held duration to be ready to start the next hold.
        _sequenceIndex = (_sequenceIndex + 1) % holdSequence.Length;
        _holdDuration = 0;
    }

    // If the player is holding the button, we add time to our accumulator.
    if(Input.GetButton(inputName)) {
        _holdDuration += Time.unscaledDeltaTime;
    }
}

```

Here's what this can look like when all set up. I made a little `Breathe` script with a bunch of methods like `public void Inhale(float error) { }` to demonstrate how the events can be wired up.

To make this work with your custom input device, all you need to do is make a component that has a similar interface as the built-in Input system. Specifically, for this script we need to be able to read two different booleans: one that's true on the frame the button has been released, and one that's true as long as the button is pressed/down/held.

With that in place, you can add a reference to your custom input monitoring script, like

```
public SerialInputReader serialInput;

```

Then you can replace `Input.GetButtonUp()` with `serialInput.ReleasedThisFrame()` and `Input.GetButton()` with `serialInput.IsPressed()`
> 2 votes

---
Tags: unity, c#, game-mechanics, timer
---


# Question
Title: RigidBody or Character Controller for Zero Gravity first person shooter
I am developing a single person, first-person shooter that takes place in space. I want to be able to simulate zero gravity. Should I use a Rigid-Body or a Character Controller?

# Answer
> 1 votes
If you want free-floating Newtonian physics, that's exactly what a Rigidbody provides.

The CharacterController is for cases where you want to avoid dealing with physics directly, where you don't want to fight the physics engine to stop the character from feeling "slippery" or "floaty" or to give the movement more control and personality than a basic physics object.

But in your case, the "floatiness" of raw Newtonian physics is actually a feature, not a detriment.

---
Tags: unity, physics, first-person-shooter
---


title: Move Object θ Degrees Over T Time

text:
# Question
Title: Move Object θ Degrees Over T Time
**Note, this happens on click and not in the update cycle**

I have a game object that i rotate at a given angle, around a point without a time component like this(works as intended):

```
void Rotate(a)
{
    var parent = transform.parent;
    Vector3 point = new Vector3(0, 0, 0);
    Vector3 axis = new Vector3(0, 0, 1);

    parent.transform.RotateAround(Pivot.bounds.center, axis, a);
}

```

note that the parent is an empty to manipulate the anchor point

I wish to animate the rotation over time, however each method produces an inaccurate result. The two functions I have tried:

```
IEnumerator RotateOverTime(float byAngles, float inTime)
{
    var parent = transform.parent;
    Vector3 axis = new Vector3(0, 0, 1);

    var stepAngle = byAngles/ (inTime/ 1000f);

    float timer = 0;
    while (timer <= (inTime/ 1000f))
    {
        parent.transform.RotateAround(Pivot.bounds.center, axis, stepAngle * Time.deltaTime);
        timer += Time.deltaTime;
        yield return null;
    }
    yield return null;
}

IEnumerator RotateMe(Vector3 byAngles, float inTime)
{
    var parent = transform.parent;
    var fromAngle = parent.transform.rotation;
    var toAngle = Quaternion.Euler(parent.transform.eulerAngles + byAngles);
    for (var t = 0f; t < 1; t += Time.deltaTime / inTime)
    {
        parent.transform.rotation = Quaternion.Lerp(fromAngle, toAngle, t);
        yield return null;
    }
}

```

**The Problem:**

The above two methods doesn't rotate the object by the exact amount of degrees, see image below where the angle in question is 90deg. You can clearly see by the grid what the issue is

# Answer
> 2 votes
The problem with the second routine is this:

```
for (var t = 0f; t < 1; t += Time.deltaTime / inTime)

```

That continues the loop while `t < 1`. The loop will stop when `t` \>= 1, which means the `Lerp` will never execute while `t` = 1.

You could change it to `t <= 1`, but it's extremely unlikely that `t` will ever exactly equal 1, so that may not help anyway.

The solution for either function is dead simple: add this line to the end of your coroutine:

```
parent.transform.rotation = toAngle;

```

---
Tags: unity, rotation, vector, quaternion
---


# Question
Title: Is reobfuscating javascript every time the page is loaded a valid option for a multiplayer game?
I am looking for ways to prevent cheating on a multiplayer browser game. I saw this answer where it was mentioned that obfuscation is not an effective technique.

My plan is not only to obfuscate the code differently every time the page is loaded but periodically change the protocol that the client uses to communicate with the server. This would mean that even if they were able to deobfuscate the client-side code, they would need to update the protocol every time I changed it or they wouldn't be able to communicate with the game servers. I know that this will be difficult to implement, but I believe that I can do it.

Would this work? I know that it's impossible to outright prevent cheating, but I believe that this would make it extremely difficult.

# Answer
> 1 votes
Summarizing the comment thread above:

No amount of obfuscation will stop cheaters. The most it will do is slow them down by a little - and if your game gets popular, the amount it slows them down will be much less than the time it takes you to implement these obfuscation features. Time you could be spending making your game better for all your non-cheating players.

The strongest protection against cheating is to design your game in such a way that a player gains no advantage by cheating. If you want to prevent wall hacks, ensure that seeing through walls gives no advantage - because the game client doesn't know about players on the other side of the wall until they're about to become visible anyway. The server deliberately withholds this information so cheaters and non-cheaters alike need to actually get in position to see around the corner.

Distinguishing an aimbot from a very skilled player is very challenging, but obfuscation wouldn't stop aimbots anyway — a hacker can intercept the graphics driver calls to find the locations of on-screen targets, and fake input to take the reticle there, without ever touching the game's code. So you need to catch it on the server. Usually by watching for patterns of inputs and looking for telltale artifacts of a script's calculated values moving differently than a mouse or analog stick driven by a human hand.

---
Tags: javascript, anti-cheat, html
---


# Question
Title: How should bullet reflections be implemented?
I'm working on a tank game where bullets are reflected off of walls. The formula for a reflection is:

$$ r=d−2d⋅n∥n∥2n $$

where \\$d\\$ is the incoming vector and \\$n\\$ is the normal of a wall.

My bullets stick to the walls and then "bounce" off at the corners; an undesirable effect. I'm honestly questioning my formula implementation at this point.

This is my current implementation:

```
func collision():
    for i in get_slide_count():
        var collision = get_slide_collision(i)
        if collision.collider.is_in_group(globals.wall_group):
            var normal = collision.normal
            velocity = velocity - ((2 * velocity.dot(normal)) / normal.length_squared()) * normal
            rotation = velocity.angle() + PI

```

If I use the `is_on_wall()` function and simply negate the velocity this does produce a bouncing effect but not a correct one. I still need the normal.

I originally used rigid bodies as seen in the image above. But I have switched to kinematic bodies.

# Answer
> 0 votes
I've figured out a solution:

```
func collision():
    for i in get_slide_count():
        var collision = get_slide_collision(i)
        if collision.collider.is_in_group(globals.wall_group):
            var normal = collision.normal
            velocity = velocity - ((2 * velocity.dot(normal)) / normal.length_squared()) * normal
            rotation = velocity.angle() + PI
            return

```

Returning after detecting a single collision point ensures that it does not get stuck on the walls and bounces off correctly.

---
Tags: godot, gdscript
---