title: Problem with Rotation clamping in Unity

text:
# Question
Title: Problem with Rotation clamping in Unity
I'm trying to get a simple cannon to rotate to point at the mouse, but I only want it to follow the mouse for 180 degrees and then stop following the mouse, and pick up again when the player re-enters the 180-degree area. I got the cannon to follow the user's mouse but when I tried to camp it to the 180-degree area I found it worked for one side, but when I went to the other it "teleported" to the other side.

I video to explain my issue: https://i.stack.imgur.com/ZVNCn.jpg Sorry about the crude graphics, frame rate, and the software doesn't show my mouse making things more difficult, but as you can see, the clamp works fine when I move my mouse to the right, but when I move it to the left it "teleports" or instantly moves to teh right no matter where my mouse is.

Here is my code:

```
public int rotationOffset = -90;

    // Update is called once per frame
    void Update()
    {
        var mouse = Input.mousePosition;
        var screenPoint = Camera.main.WorldToScreenPoint(transform.localPosition);
        var offset = new Vector2(mouse.x - screenPoint.x, mouse.y - screenPoint.y);
        var angle = Mathf.Atan2(offset.y, offset.x) * Mathf.Rad2Deg;
        float finalRotation = angle + rotationOffset;

        // I have tried both the normal Mathf.Clamp and the if statments below and I get the exact same result.
        //finalRotation = Mathf.Clamp(180, 0, finalRotation);

        if (finalRotation >= 89f)
        {
            finalRotation = 89f;
            Debug.Log("Left");
        }

        else if(finalRotation <= -89f)
        {
            finalRotation = -89f;
            Debug.Log("Right");
        }

        transform.rotation = Quaternion.Euler(0, 0, finalRotation);

    }

```

I don't know if this might be a bug in Unity, But I've spent days trying to fix it, I'm tired, I'm stressed, I don't know how to fix it.

# Answer
> 2 votes
As you've found, clamping an angle can be surprisingly tricky. To illustrate your particular problem, here's a couple of crappy diagrams:

This is the output from `atan2` for some various vectors. Note that it wraps at 180/-180. (The Unity docs do not specify this, but it's how the function normally operates regardless of the framework.)

Then, here is the output after applying your -90 degree offset (in other words, the value of `finalRotation`):

You might notice something - the value of the angle *never goes above 90*. That means the body of the if statement which checks for `finalRotation >= 89f` is basically never executed.

For a quick fix, just looking at the angles in the above diagram, you should be able to do something like this:

```
if (finalRotation < -90)
{
  if (finalRotation > -180)
  {
    // we're on the right
  }
  else
  {
    // we're on the left
  }
}

```

However, I'd suggest you look into more generic angle clamping/comparison functions. As you noted, `Mathf.Clamp` will not do the job because it doesn't know that angles wrap around a circle. Something like the one described in this post might do the job.

---

As a word of encouragement, the final plea for help in your post is something I've felt all to commonly when running into problems like this. I've found it helpful to take a deep breath, step back, and view the problem analytically before losing hope. If all else fails, remember you can easily get a second opinion - just like you've done here - before you reach the point of utter frustration.

---
Tags: unity, 2d, unityscript, debugging, bug
---


# Question
Title: how to make the capsule move during anims
I'm trying to make a cartwheel/ dodge to the side in ue4 but when the animation plays it moves out of the capsule and slides back. Is there a way to make the capsule move with the character in the animation.

# Answer
It sounds like your animation is moving off of the root position. There are two options here out of the box. You could try using Root Motion https://docs.unrealengine.com/en-US/Engine/Animation/RootMotion/index.html, which would allow you to use the animation as is, while moving the capsule. However, Root Motion is limited, and I wouldn't advise heavy use of it. If you plan on using the navmesh for path finding, for example, Root Motion does not support path finding out of the box. It is also limited in multiplayer.

The proper way to do it is to kill all of the root motion on your animation and re-import it, or use the "Force Root Lock" checkbox in the animation asset editor. This will lock the animation at the root, and thus will always stay at the local space location of the skeletal mesh component. Then, you will need to procedurally move the character while playing the animation.

If you want to look at a BASIC example of how to set up animations, as well as a basic animation state machine the Unreal way, download the Epic Games Launcher and download https://www.unrealengine.com/marketplace/en-US/slug/paragon-shinbi. There is also a tutorial https://www.youtube.com/watch?v=yP4ygKHwlS0 which shows you some basics. In the description of this tutorial, there are other parts you can watch which cover different things. This is by no means the best way to do it, but this will get you started in the right direction, so you can understand the basics of the pipeline, and get your character working.
> 1 votes

---
Tags: animation, unreal-4
---


# Question
Title: Removing texture wrapping artifacts in OpenGLES
I'm drawing an 2D array of cubes in 3D space using OpenGLES. The texture that I have bound is spritesheet-style; that is, it's multiple textures packed into one. If you look closely at the front of the image below, you can see 1-pixel thick lines that are lighter than the crates. And, thicker lines in the back of the image. They are not supposed to be there, and are what I believe to be pixels from another texture in the spritesheet.

I'm using `GL_NEAREST_MIPMAP_NEAREST` and `GL_NEAREST` for the min and mag filters, and I've tried all of the different clamping modes and nothing changes (`GL_CLAMP_TO_EDGE`, `GL_REPEAT`, `GL_MIRROR_REPEAT`).

At first I thought it was float precision error, but now I think it's something else (since using `precision highp float` in the shader makes no difference).

# Answer
> 3 votes
I figured out what was going on. The problem was not floating point precision, and not that I needed to make my own mipmaps to blend each level correctly. There were actually 2 problems:

1. I was using the Max Rects packer algorithm with non-power-of-2 sized images to create the texture atlas.
2. I wasn't setting `GL_TEXTURE_MAX_LEVEL`

What I was doing:

* Use Max Rects on non-power-of-two packing to create a texture atlas. Textures are aligned at pixel boundaries.
* `glGenerateMipmap(GL_TEXTURE_2D);` making blending the texture atlas textures into each other even on level 1

What I'm doing now:

* All textures are power of 2. 128x128 is the smallest sized texture in a 4096x4096 texture atlas.
* `glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 7);` \- This is new. Don't allow anything below mipmap level 7, because 4096 / (2^7=128) = 32. This makes the code stop generating mipmaps once the smallest texture in the atlas becomes 1 pixel by 1 pixel.
* `glGenerateMipmap(GL_TEXTURE_2D);` \- Now scales down the atlas correctly because all the textures are aligned to 1/32 of the width or height of the atlas rather than 1/width or 1/height.

And now the min filter can use 2 modes without texture bleeding:

* `GL_NEAREST_MIPMAP_NEAREST`
* `GL_NEAREST_MIPMAP_LINEAR`

The following 2 min filter modes still have bleeding issues, but I'm not planning on using them anyway:

* `GL_LINEAR_MIPMAP_NEAREST`
* `GL_LINEAR_MIPMAP_LINEAR`

The reason is because they are interpolating the mipmaps to sizes that are not powers of two, which makes the textures in the texture atlas aligned to points in between pixels, causing the bleeding. The only way I think this can be solved is by adding a border around each texture in the texture atlas. The only problem with that is that the border would have to be 128 or 64 pixels, the size of the smallest texture or half the size of the smallest texture (if you use half pixel offset). And that's a huge waste of video RAM.

So I went with `GL_NEAREST_MIPMAP_LINEAR`:

# Code

```
uint8_t* pixels = /* Fixed number of pre-generated mipmaps */;
size_t pixels_len = /* length of pixels */;
size_t width = /* width of first mipmap */;
size_t height = /* height of first mipmap */;

assert(pixels_len >= width * height * 4);
unsigned int new_texture;
glGenTextures(1, &new_texture);
glBindTexture(GL_TEXTURE_2D, new_texture);
// Rendered smaller than texture
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
    GL_NEAREST_MIPMAP_LINEAR);
// Rendered bigger than texture
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(
    GL_TEXTURE_2D,
    0,
    GL_RGBA,
    width,
    height,
    0,
    GL_RGBA,
    GL_UNSIGNED_BYTE,
    pixels
);

// Generate mipmaps
int mipmap_level = 0;
int offset = width * height * 4;
while(width > 1 && height > 1 && offset != pixels_len) {
    // Divide width & height.
    width >>= 1;
    height >>= 1;
    // Increase mipmap level.
    mipmap_level += 1;

    glTexImage2D(
        GL_TEXTURE_2D,
        mipmap_level,
        GL_RGBA,
        width,
        height,
        0,
        GL_RGBA,
        0x1401,
        pixels + offset,
    );

    offset += width * height * 4;
}

glTexParameteri(
    GL_TEXTURE_2D,
    GL_TEXTURE_MAX_LEVEL,
    mipmap_level,
);

```

---
Tags: textures, opengl-es2, texture-atlas
---


# Question
Title: Best way to de-clutter name tags on units in RTS
This is an RTS-MMO mobile game I am building, Each unit has health-bar and name of the unit and owner on top of it and a small circle indicating if the unit is friendly and/or has weapons activated or not.

Problem is, when there are a lot of units in one spot, the tags become so cluttered and the critical information becomes lost.

I have tried making the name tags more transparent but this does not help. Tried putting some name tags above the unit, other tags under the units, also to no avail. Tried removing the healthbars unless the unit is damaged, didn't help much either!

How does RTS games solve this issue? I have seen some RTS games remove the healthbars for non-damaged units, but this didn't have any impact on how it looks, and having no name tags or at least no owner-name-tags will be a no-go as this information is critical when attacking/approaching other units, or when picking own units (as units might be equipped with different tools and be named by their owner to be recognized.)

# Answer
If you're troubled by the overlapping text, one thing you could do is have a list of "top 20" names along the side of the screen, with neat vector lines pointing to which unit in the main viewport that is (maybe only when you hover over the name?). This at least prevents overlaps.

You could also make this list scrollable if you have pointer / touch access.

This is like looking for someone in a crowd in real life - it's going to take time to pick them out. Still better than not being able to make them out at all.
> 4 votes

# Answer
You basically can't solve this problem by changing drawing, rendering, etc. You are essentially showing too much information on the screen at once. Every game has this kind of issue, any time players are all clustered.

A few things you CAN do are...

* Give players control over what is shown on screen. It looks like you are showing the worst case of everything on. Let the player's decide.
* Only show some info when players hold down a key like alt or shift. Perhaps treat these keys separately, like alt gives name, shift gives health, etc. This doesn't work on a mobile interface, but you didn't specify if you were mobile only so I'm adding it.
* Just let go of the idea of showing everything

In the end, like I said. You just plain have too much on your screen. Not just the labels over players, but everything else. It's too complex. UX redesign combined perhaps with game redesign can fix this, transparency and UI tricks are going to have a lot harder time.

I'll add that if you were doing this on a regular computer monitor, it would work. But in the limited space of a phone, it's a challenge.
> 4 votes

---
Tags: game-design, user-experience, user-interface
---


# Question
Title: How to load assets into the game engine editor fast?
I am making a game engine with C++ and OpenGL. Currently I'm stuck making the asset explorer. I would like to be able to import assets into an engine project and then when I open the project just use them in various game scenes (like in Unity). However the only thing I am doing right now is loading everything from the 'Assets' folder of the opened editor project. That is incredibly slow even when done asynchronously with multithreading. I don't understand how does Unity load assets so fast. I've noticed that it takes a while to import the assets for the first time but then it's very fast anytime you open the project after the first import. Is there any way to cache loaded assets? And should I generate all the buffers for OpenGL right on the asset import or should I wait for the asset to be 'used'?

Unity's asset explorer:

All imported assets can be inspected like that, and then you can use them in the scenes (for example drag and drop a model into the scene):

# Answer
I ended up solving the problem (thanks to DMGregory's hints) by generating meta files for each asset. The meta files contain the path to the preview image used in the asset explorer window, and import settings. Only when the asset is 'inspected' I fully load it into memory. That way the engine start's niceley without having to wait for files to load everytime, excpet for the first import where the meta files are generated.
> 1 votes

# Answer
If I understand correctly, you have a game engine with a GUI, and you want to display to the programmer the assets that the current project is using?

A lot of GUI programs (I believe unity too) create small thumbnails for images, which are a lot smaller in size than the original assets, so they can be displaying without issue. How big or small those should be depend on what your GUI looks like. You can make them as small as 50x50 and it will still be recognisable.

original (220x220)

resized (50x50)

Assuming that most assets are 200x200 or more, that means each asset now needs x4 times less resources, which can make loading faster but also reduced the amount of memory your engine needs to run. Keep in mind that even if the texture is resized for display purposes, when compiling your game you take the original texture, so the game is not affected by this change.

You may want to save the cache the resized images the first time this happens, this is why most programs take a while the first time they run and run way faster afterwards.

If you want to account for project scalability, you'd probably want to separate your assets into "categories" as well (maybe like per scene?) and load a specific group of assets when needed and not all assets at all times.

Note: Numbers are random-ish, you can use different numbers based on the needs of your project. The image was taken from Wikipedia - Cat intelligence
> 0 votes

---
Tags: opengl, c++, architecture
---


# Question
Title: How to connect nodes in a star pathfinding for platformer games?
In this thread, it tells that in 2d platformer games, I should pre-define and connect node to find the correct path.

But I don't understand how to find the node's children. In my program, I define map as following, 0=free space, 1=solid terrain, 2=node

the original map definition is:

```
numpy.array([ [0,0,0,0,0,0,0,0,0,0,0],
              [0,0,0,0,0,0,0,0,0,0,0],
              [0,0,0,0,0,0,0,0,0,0,0],
              [0,0,0,0,0,0,0,0,0,1,1],
              [1,1,1,1,1,1,1,0,0,0,0],
              [0,0,0,0,0,0,0,0,0,0,0],
              [0,0,0,0,0,0,0,0,0,0,0],
              [1,1,1,1,1,1,1,1,1,1,1], ])

```

the map after adding nodes

```
numpy.array([ [0,0,0,0,0,0,0,0,0,0,0],
              [0,0,0,0,0,0,0,0,0,0,0],
              [0,0,0,0,0,0,0,0,0,2,2],
              [2,2,2,2,2,2,2,0,0,1,1],
              [1,1,1,1,1,1,1,0,0,0,0],
              [0,0,0,0,0,0,0,0,0,0,0],
              [2,2,2,2,2,2,2,2,2,2,2],
              [1,1,1,1,1,1,1,1,1,1,1], ])

```

so the map should be so

In the original A\* (A star) algorithm, it searches 8 directions and every direction checks only one node if available.

But in a platfomer, I don't know how to deal with this, there are too many possibilities. For example, assuming the character's jump value is 3, then we go to left now I can:

* jump to left using 200% power, (keep pressing left while jumping and falling, move 6 steps actually)
* jump to left using 166% power
* jump to left using 133% power
* jump to left using 100% power
* jump to left using 66% power
* jump to left using 33% power
* just walk (the paths 1-7 in the pic)

8 directions and bigger jump value lead to more possibilities. What's more, there are countless possibilities when falling from a high solid terrain.

For every possibility, in order to connect the nodes, I need to check the corresponding coordinate in the map (array) if existing node.

So I am confused. Am I over-complicating / misunderstanding A\* or did I miss something because it requires a huge calculation for every node in a big map like 500\*500?

# Answer
> am I overcomplicating/misunderstanding

I'm afraid, you are (to some extent). All you really need to build the graph is to walk through all of your nodes (2) and connect them using a mask like this.

```
--UJU--
-UUJUU-
U0W*W0U

```

where

* `*` -- Anchor point, that's the position of the node we are currently testing
* `-` -- nodes we can't reach (directly) from the current one, so we won't connect to them
* `J` -- if there is the node -- you can jump to it if you can jump through the blocks
* `U` -- nodes you can jump up on (or from, it works both ways) to
* `W` -- nodes you can walk to
> 0 votes

# Answer
You are correct in your understanding that increasing the number of choices will significantly increase the problem size. Whether or not it increases it too much depends on many factors. For instance, I've seen A\* extended all tiles within a distance of three (Directional-48 search) in order to path find with turning radius constraints. That doesn't necessarily mean that your problem won't grow out of scope - the only way to know that is to either build and test or do the math / theory needed to determine the time required.

Regarding your representation, I'm not sure I agree with your distinction between nodes & empty space. For one thing, it doesn't account for jumping to get power-ups, avoid enemies, etc. It also seems like to be accurate you either need to calculate it all by hand or already have made reachbility calculations. If it works well enough for your needs, that's great, but it's something you might need to revisit later on.

I my limited experience with platformer AI, the problem space is somewhat restricted by reducing the look-ahead. For instance, the solver might only consider one screen's worth of the level at a time rather than the entire map. This could be scaled up or down depending on the performance.

It may be the case that A\* is not a good fit for this problem or may need additional techniques to make it competitive. The previous research I've seen tended to focus more on heuristic search algorithms such as Monte Carlo methods, but that may just have been a consequence of what I was working on at the time. There's a lot of great research connected to Mario AI Compitition & they have a code framework available. Because the research is geared toward competition, it tends to be more practical & results oriented and less theoretical & hand wavy.
> 0 votes

---
Tags: path-finding
---


# Question
Title: How do I launch a ballistic projectile to hit a moving target, given: launch position & angle, target position & velocity?
This problem is in 3D space. My question is: How do you find the initial velocity of a projectile that flies under constant gravity, so that it hits a target moving with constant velocity, given the parameters:

* Launch Position
* Launch Angle
* Target Position
* Target Velocity
* Acceleration due to Gravity

Most of the answers I find solve the problem using Launch Speed instead of Launch Angle.

The reason why I want to use Launch Angle, rather than Launch Speed, is because the arc of the projectile doesn't look good when solving with Launch Speed. The low angle is too low, and the high angle is too high.

My goal is to be able to adjust the arc of the projectile to be more visually pleasing, while still being able to hit the moving target 100% of the time.

# Answer
> 2 votes
I'm assuming that your gravity acts on the vertical axis, and that your launch angle is an altitude (measured vertically from the horizon, so 0° means firing horizontally, and 90° means firing straight up). Our turret is still free to pivot on the azimuth (side to side) to track the target and intercept it if it's moving laterally.

The first thing we'll do is take the absolute target position \\$\vec p\_T\\$ and launch position \\$\vec p\_L\\$ construct a relative target position vector \\$\vec r\\$, and its projection on the horizontal plane \\$\vec r\_h\\$ and vertical axis \\$r\_v\\$:

$$\begin{align} \vec r &= \vec p\_T - \vec p\_L\\ r\_v &= \vec r \cdot \vec {up}\\ \vec r\_h &= \vec r - r\_v \vec {up} \end{align}$$

This lets us take launch position right out of the equation. We can apply the 2nd & 3rd steps to the target's velocity vector \\$\vec v\\$ to split it into a horizontal vector \\$\vec v\_h\\$ and a vertical component \\$v\_v\\$.

Now if we want to hit the target at an initially unknown time \\$t\\$ seconds after launch, we'll need to cover the horizontal displacement \\$\vec r\_h + \vec v\_h t\\$ in a straight line in time \\$t\\$. So the horizontal component of our launch velocity \\$\vec l\_h\\$ is:

$$\vec l\_h = \frac {\vec r\_h + \vec v\_h t} t$$

Given our desired launch angle \\$ \theta \\$, we know the ratio between the horizontal and vertical launch speeds is:

$$\begin{align} \tan \theta &= \frac {l\_v} {\\| \vec l\_h \\|}\\ \tan \theta \cdot \\|\vec l\_h\\| &= l\_v\\ \tan^2 \theta \cdot l\_h^2 &= l\_v^2\\ \tan^2\theta \left( \frac {\vec r\_h + \vec v\_h t} t \right)^2&= l\_v^2\\ \tan^2\theta \left( \frac {r\_h^2} {t^2} + 2 \frac {\vec r\_h \cdot \vec v\_h} t + v\_h^2 \right) &= l\_v^2 \end{align}$$

Now we want to know if that vertical launch velocity will bring us to our target's height at the end of the arc at time \\$t\\$:

$$\begin{align} l\_v t - \frac g 2 t^2 &= r\_v + v\_v t\\ l\_v &= \frac {r\_v} t + v\_v + \frac g 2 t\\ l\_v^2 &= \frac {r\_v^2} {t^2} + \frac {2 r\_v v\_v} t + r\_v g + v\_v^2 + v\_v g t + \frac {g^2} 4 t^2\\ \tan^2\theta \left( \frac {r\_h^2} {t^2} + 2 \frac {\vec r\_h \cdot \vec v\_h} t + v\_h^2 \right) &= \frac {r\_v^2} {t^2} + \frac {2 r\_v v\_v} t + r\_v g + v\_v^2 + v\_v g t + \frac {g^2} 4 t^2\\ \tan^2\theta \left( r\_h^2 + 2 \vec r\_h \cdot \vec v\_h t + v\_h^2 t^2 \right) &= r\_v^2 + 2 r\_v v\_v t + r\_v g t^2 + v\_v^2 t^2 + v\_v g t^3 + \frac {g^2} 4 t^4\\ 0 &= t^4 \cdot \left(\frac {g^2} 4 \right)\\ &+ t^3 \cdot \left( v\_v g \right) \\ &+ t^2 \cdot \left(r\_v g + v\_v^2 - \left( \tan \theta \right)^2 v\_h^2 \right)\\ &+ t \cdot 2 \left(r\_v v\_v - \left( \tan \theta \right)^2 \vec r\_h \cdot \vec v\_h \right)\\ &+ r\_v^2 - \left( \tan \theta \right)^2 r\_h^2\\ \end{align}$$

Now we have a quartic equation in one variable with known real number coefficients. As described in this answer, you can apply your favourite quartic solving routine (there's an example in the comments) to find potential values of \\$t\\$ that satisfy the equation. In general there could be up to four solutions. We're looking only for those that...

* are real numbers (zero imaginary component)
* are greater than zero (negative values correspond to shots the *target* could have lobbed at *us* to strike us at our launch angle at time 0)
* yield a positive vertical launch velocity \\$l\_v\\$. (Since the formula we solved involved only the square of the angle's tangent, we discarded the sign, so we can get some false positives that aim downward instead of upward)

If you have multiple candidate solutions that meet those criteria, you can choose freely between them. Generally the smaller the time value \\$t\\$ the shallower the arc, but also the less time the target has to change course and dodge. Higher \\$t\\$ solutions typically correspond to taller arcs (we spend more time flying up and down through the air), giving the target more time to evade.

With your chosen time \\$t\\$ in hand, you can substitute it into the equations above to find your horizontal & vertical launch velocity components, and combine them into the final velocity.

# Answer
> 0 votes
Thank you again very much! You are very generous with your time sir. This got me 90% of the way there. For me, I had to make a bit of a modification to the final quartic equation to get it working properly:

$$\begin{align} \\ t^4 \left(\frac {g^2} 4 \right) \+ t^2 \left(r\_v g - \left( \tan \theta \right)^2 v\_h^2 \right) \+ t \left( 2 \left( \tan \theta \right)^2 \vec r\_h \cdot \vec v\_h \right) \+ \left( \tan \theta \right)^2 r\_h^2 \- \vec r^2 &= 0 \end{align}$$

---
Tags: mathematics, algorithm, geometry, projectile-physics, aiming
---


# Question
Title: Unity3D: Move the parent gameobject relative to the child
So, I have `X and Y game objects`. I have a vector `Z = X - Y` which is indicated by the green line.

Also, I have a `Parent` game object and it has a `Child` game object. How do I move the parent such that the child game object is at the `Point Y`

I tried,

```
                  Z -= new Vector3(child.localPosition.x, 0, child.localPosition.z);
                  Parent.transform.position = Z

```

which is not working as expected. Thank you!

# Answer
> 2 votes
Did you try something like this?

```
childToTarget = targetPosition - child.position;
childToTarget.y = 0;

parent.position+= childToTarget;

```

---
Tags: unity, c#, mathematics, vector, gameobject
---


title: Why do games suggest you take a break?

text:
# Question
Title: Why do games suggest you take a break?
A lot of games will suggest you take breaks from them every 30 minutes or so, I think this is especially common in Nintendo games, but they aren't the only ones to do it. What is the advantage to this? Does this somehow help get you to play it more or does it help sell more copies?

# Answer
This generally isn't a reverse psychology tactic. The aim is actually to remind players how much time they've been spending in front of the screen and, in some cases, suggest that it might be time for a break.

This is because it can be unhealthy for a variety of reasons, to play games for extended periods of time, and the developers want to look out for their players.

There are far more effective techniques for getting people to play *more*. "You've been playing for..." reminders are generally somebody trying to do the right thing, or (from a more self-interested perspective) establish a defensive legal position, or to self-regulate in order to avoid the creation of actual, legal, regulations.
> 9 votes

---
Tags: game-design
---


# Question
Title: Question about Unity C# skill cast interface and class design
So I have skill class and it's children which have the Use() interface and functionality code of the skill, what want to do is have the item can also be used to cast skill, or have some wrapper to record use time or consume item of a individual character or something like that, So what I came up is use a wrapper class to wrap the the skill functionality, like below:

```
public interface ICastable
{
    ICastable skill {get;}
}

public interface ICastOnSelf: ICastable
{
    void Use(GameObject user);
}

public interface ICastOnTarget: ICastable
{
    void Use(GameObject user, GameObject target);
}

public abstract class Skill: ScriptableObject {}

public class SomeSkillCastOnSelf: Skill, ICastOnSelf
{
    public ICastable skill {get { return this; }}
    public void Use(GameObject user)
    {
        print(something);
    }
}

public class SomeSkillCastOnTarget: Skill, ICastOnTarget
{
    public ICastable skill {get { return this; }}
    public void Use(GameObject user, GameObject target)
    {
        print(something);
    }
}

public class SomeItemContainsASkill: Item, ICastOnSelf, ICastOnTarget
// Have to implement all interfaces since it could contains different kind of skill
{
    public ICastable skill {get { return acctualSkill; }}

    public Skill acctualSkill;

    public int timeUsed;

    public void Use(GameObject user)
    {
        var skillCastOnself = skill as ICastOnSelf;
        if (skillCastOnself == null)
        {
            print("Can't cast this skill on self")
            return;
        }
        skillCastOnself.Use(user);
        timeUsed += 1;
    }

    public void Use(GameObject user, GameObject target)
    {
        //same idea...
    }
}

public class SkillWapper: ICastOnSelf, ICastOnTarget
{
    //same idea as SomeItemContainsASkill class
}

public class Caster: MonoBehaviour
{
    public List<ICastable> wrappers;

    public IEnumrator cast()
    {
        foreach (var item in wrappers)
        {
            if (item.skill is ICastOnSelf)
            {
                // ... ask and wait for player input here
                item.Use(this)
            }
            else
            {
                // ... ask and wait for player input here
                item.Use(this, target)
            }
        }
    }
}

public class Inventory
{
    List<ItemSlot> items;
}

public class ItemSlot
{
    Item item;
    int stack;
}

```

edit: Inventory class contains itemslot which is recording the current stack of the item, but if I want to consume item after using it, there must be a way to reference to which inventory and which slot is using. so the difficulty of reference this is the Itemslot is wrapper class but itself could be a non ICastable class depending on the item it is holding. Hope this makes it more clear. But the whole thing is kinda messy, so any idea of a better design? Thanks.

# Answer
Your design does seem massively overcomplicated.

I find it useful to think about the divisions of responsibilities. You say that

* You want items that may have skills associated with them that activate when the item is used.
* Items in your inventory can be stacked and some items may be consumed when used.

These are two different things, and I believe that the responsibility for dealing with removing items that get consumed on use lies with the inventory system, *not* the skill system (nor the items themselves). If you have questions about that, I'd encourage you to ask them separately.

As for the skills, it seems to me like you can simplify greatly. I don't see the need for the number of interfaces in your example, and I don't understand the rationale for why you need these "wrapper" types.

I would expect to see a system that looked more like:

```
interface ICastable {
  // Returns true if the skill did successfully activate.
  bool Activate(GameObject caster, GameObject target);
}

```

Whether or not an `ICastable` supports self-targeting can simply be handled in `Activate`: if `caster == target`, return false for abilities that cannot self-target.

At the other end of thing, your `Item` class should just contain an optional reference to an `ICastable` that is the associated skill:

```
class Item {
  public ICastable OnUseSkill = null;

  void Use() { /* ... */ }
}

```

In `Use`, if `OnUseSkill` is non-null, call the `Activate` method. You'll need targeting information, naturally, but how you pass that depends on how you determine it at the gameplay level.
> 0 votes

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


# Question
Title: Verlet chain with two fixed points is not converging properly
I am trying to create a simple chain between two fixed endpoints. The problem is that I can't seem to get the chain to reach a stable state. Further, the chain is always biased toward one of the endpoints.

Here are my constants and variables:

```
const NUMBER_OF_LINKS = 100
const CHAIN_LENGTH = 400
const DIST_BETWEEN_LINKS = CHAIN_LENGTH / NUMBER_OF_LINKS
const ITERATIONS = 20 # number of times we iterate through constraints each frame
const GRAVITY = Vector2(0, 300)

var anchor1
var anchor2

var prev_link_positions = []
var links = []

```

Here's what I do on initialization:

```
create_links(NUMBER_OF_LINKS)

var first_link = links[0]
var last_link = links[NUMBER_OF_LINKS - 1]

first_link.global_position = anchor1.global_position
last_link.global_position = anchor2.global_position

```

And here are the adjustments I do each frame:

```
links[0].global_position = anchor1.global_position
links[NUMBER_OF_LINKS - 1].global_position = anchor2.global_position

for i in range(NUMBER_OF_LINKS):
    var acceleration = GRAVITY
    acceleration *= delta * delta
    var prev_position = links[i].global_position
    if not i in [0, NUMBER_OF_LINKS - 1]:
        links[i].global_position = 2*links[i].global_position - prev_link_positions[i] + acceleration
    prev_link_positions[i] = prev_position

for iteration in range (ITERATIONS):
    for i in range(NUMBER_OF_LINKS):
        var link = links[i]

        var prev_link_position
        if i == 0 or i == NUMBER_OF_LINKS - 1:
            prev_link_position = links[i].global_position
        else:
            prev_link_position = links[i-1].global_position

        var next_link_position
        if i == 0 or i == NUMBER_OF_LINKS - 1:
            next_link_position = links[i].global_position
        else:
            next_link_position = links[i+1].global_position

        # get vector to previous link and adjust position
        var vec_to_prev_link = prev_link_position - link.global_position
        link.global_position += vec_to_prev_link.normalized() * max(vec_to_prev_link.length() - DIST_BETWEEN_LINKS, 0) / 2.0

        # get vector to next link and adjust position
        var vec_to_next_link = next_link_position - link.global_position
        link.global_position += vec_to_next_link.normalized() * max(vec_to_next_link.length() - DIST_BETWEEN_LINKS, 0) / 2.0

```

When I run this, I almost get what I want, except the chain contorts and never reaches a stable state. Also, it is biased in the first direction I look at when solving the constraints.

It looks something like this:

**What am I doing wrong? How can I get a chain that stabilizes with links more uniformly distributed?**

# Answer
> 2 votes
The problem is that you first move every link closer to one of its neighbors, then closer to the other, without saving the original position. These two should happen at the same time, so that the position of the current links stays fixed throughout.

```
    # get vector to previous link and adjust position
    var vec_to_prev_link = prev_link_position - link.global_position
    var adjust1 = vec_to_prev_link.normalized() * max(vec_to_prev_link.length() - DIST_BETWEEN_LINKS, 0) / 2.0

    # get vector to next link and adjust position
    var vec_to_next_link = next_link_position - link.global_position
    var adjust2 = vec_to_next_link.normalized() * max(vec_to_next_link.length() - DIST_BETWEEN_LINKS, 0) / 2.0

    link.globalPosition += adjust1 + adjust2

```

The alternative is to get the vectors pointing to the previous and next chains before you adjust the current one

---
Tags: 2d, physics, movement, rope-physics, cloth
---


# Question
Title: Do UV coordinates need correction for moving object?
The image above is a static capture of a dynamic OpenGL project I created in which I wrapped a NASA albedo, i.e., sans clouds, image on an OpenGL generated sphere. In so doing, I also generated the UV coordinates associated with each vertex position.

This was an incremental learning effort in which I had already applied model matrix corrections to the vertex positions for the rotating and translating (orbiting) "Earth".

I was surprised to find that I did **not** have to apply a model matrix correction to the UV coordinates.

I have **tentatively** concluded that once the jpg image coordinates are associated with the corresponding vertex positions with the UV coordinates in the range of \[0, 1\], they are fixed and need no further correction.

Does that sound correct, or is there more to the situation?

# Answer
> 1 votes
That is correct: the texture coordinates for a model don’t need to change as you move that model around a scene or manipulate it. They are mapping parts of the geometry surface to parts of an image and thus stay fixed.

You may need to update texture coordinates if you want to do some kind of animation of the texture across a surface (although there are still other ways to do that) or similar more complex effect. But in general, you don't.

---
Tags: opengl, uv-mapping
---


# Question
Title: How do I let people make Steam Workshop mods for my game?
I want to know how to make a game compatible with Steam Workshop. Basically, I want to be able to let players make mods for my game. Using Google, I keep finding tutorials for how to make mods for popular games, but not how to make one generically.

I am using Godot engine which has builtin support to make it easy to let people mod your game. My game is network enabled and uses ENet with RPC calls (I don't think the networking matters, but in case it does, I am mentioning it).

How do I let people upload mods they made for my game so others can just subscribe to it and have it loaded in the game?

I did check out Valve's Create a Mod page, but it only talks about how to make one for source engine games. Looking at Valve's Mods on Steam page, they mention to ask the developer how to upload mods if it is not a source game, but if it is a source game, to use their guide on how to upload.

# Answer
> 4 votes
The first thing you need to do is familiarize yourself with the Steamworks documentation.

Searching for "workshop" from the documentation homepage will bring up the references for the Steam Workshop Overview and the Steam Workshop Implementation Guide.

Starting with the overview, you'll first need to decide on which workshop model you want to support:

* The Ready-To-Use Workshop allows anyone can upload content and players can download content without any curation.
* The Curated Steam Workshop place content in a queue for customers to vote on and the developer must approve items for use. This model typically requires an item server or use of the Steam Inventory Service for tracking ownership.

The implementation information can be found on the previously mentioned page of the same name. The specific details are too broad to cover here. As a starting point, you'll need to make use of the `ISteamUGC Interface`, which contains the "functions to create, consume, and interact with the Steam Workshop."

Regarding not being able to find a tutorial for how to make a generic mod: the problem is that mods change the game in one way or another & every game is for the most part, unique. Games that share an engine/platform may have a standardized protocol for getting content to the game, but *how* that content gets used by the game is going to be highly dependent on the game itself.

That said, SpaceWar (the example app that comes with Steamworks SDK) demonstrates a subset of the `ISteamUGC` API, including:

* Checking if a workshop item is downloaded and installed
* Requesting info about an item
* Retrieving the list of workshop items for the based on user subscription

---
Tags: modding, godot, steam
---


# Question
Title: Bullet prefab gets stuck to target after hitting
As the title says, I am having an issue with prefabs: I am trying to make a bullet follow a curve and then hit a target using this method:

```
private IEnumerator BezierShooting()
{
    GameObject shotInstance = new GameObject();
    shotInstance = Instantiate(shotPrefab, transform.position, Quaternion.identity);
    Vector3 currentPosition = new Vector3();
    if (shotInstance != null)
    {
        while (t < 1 && shotInstance != null)
        {
            currentPosition = Mathf.Pow(1 - t, 3) * controlPoint0.position +
                            3 * Mathf.Pow(1 - t, 2) * t * controlPoint1.position +
                            3 * (1 - t) * Mathf.Pow(t, 2) * controlPoint2.position +
                            Mathf.Pow(t, 3) * controlPoint3.position;
            Debug.Log(currentPosition);
            shotInstance.transform.position = currentPosition;
            t += 0.02f;
            yield return new WaitForEndOfFrame();
        }
    }
    else
    {
        currentPosition = transform.position;
        t = 0;
        yield break;
    }

}

```

Where `t` is a float variable that I initialised before as well as the transforms `controlPoint0`, `controlPoint1`, `controlPoint2` and `controlPoint3`.

The bullet is succesfully following the path that I created, however the problem is that once the bullet hits an object in position (x, y, z) and gets destroyed, if I call the method again the prefab will spawn in the last position it was on. I thought that final `else` statement would do the trick, but appearantly I am missing something. Can somebody help me please?

# Answer
> 1 votes
It looks like you want this:

```
private IEnumerator BezierShooting()
{
    var shotInstance = Instantiate(shotPrefab, transform.position, Quaternion.identity);
    while (t < 1 && shotInstance != null)
    {
        float invT = 1f - t;
        var currentPosition = invT * invT * invT * controlPoint0.position
                            + 3 * invT*invT * t  * controlPoint1.position
                            + 3 * invT * t * t   * controlPoint2.position
                            +     t * t * t      * controlPoint3.position;
        Debug.Log(currentPosition);
        shotInstance.transform.position = currentPosition;
        t += Time.deltaTime/bezierDuration;
        yield return null;
    }

    t = 0;
}

```

Some mistakes I corrected above:

* Don't create a `new GameObject()` you never use, only to replace the reference with the result of `Instantiate`.
* Your `while` already doubles as an `if`, so you don't need to wrap it in an `if`.
* You want `t = 0` to execute once you're done no matter what, so don't restrict it to an `else` branch. (Or, if you don't use `t` outside this coroutine, you could just make it a temporary variable in this method, initialized at the start, so you don't need to do anything to reset it later)
* `currentPosition = transform.position` doesn't accomplish anything - it's a temporary variable that's about to be thrown out when we end this coroutine anyway.
* `Mathf.Pow()` is generally more expensive than a multiplication, if all you need is a low power.
* You'll want to use `Time.deltaTime` to get a consistent speed along this curve regardless of frame rate.

---
Tags: unity, 2d, transformation, coroutines
---


# Question
Title: How To Find Child Object and set is own criteria/condition?
I am Making 2D Game.

I Apply a Two Tag On Multiple Child Game Object..

Crate A Empty Game Object and Put Script Obstacle.cs and Rigidbody2d.

Child GameObject -\> Static OnTriggerEnter2D

```
Obstacle.cs

    void Start()
    {
        foreach (Transform item in GetComponentsInChildren<Transform>())
        {
            if (item.tag == "someobstacleslow")  //7 child game object find successfully
            {
                Debug.Log("someobstacleslow:" + item.tag);
            }

            if (item.tag == "someobstaclefast") //4 child game object find successfully
            {
                Debug.Log("movefastobstacle:" + item.tag);

            }
     }

```

Referance:

https://i.stack.imgur.com/i7nnM.jpg

I want to some obstacleslow is going slow and someobstaclefast is going fast but nothing happens.

Output: all obstacle going very fasy?? what i miss my programme??

But Child GameObject not working its own condition?

```
Obstacle.cs

   float speed = 2.5f;                             //normal speed

    float movefastobjectspeed = 3f;                //fast spped

    void Update()
    {
        goTopToDown();
    }

    void goTopToDown()
    {
            foreach (Transform item in GetComponentsInChildren<Transform>())
            {
                if (item.tag == "someobstacleslow")   //issue here
                {
                    //move top to down object normal speed
                    transform.position += Vector3.down * speed * Time.deltaTime;

                    Debug.Log("GameObject obstacle object:" + item.tag);
                    Debug.Log("inside obstacle object");

                }

                if (item.tag == "someobstaclefast") // issue here
                {
                    //move top to down object fast speed
                    transform.position += Vector3.down * movefastobjectspeed * Time.deltaTime;

                    Debug.Log("GameObject movefast object:" + item.tag);
                    Debug.Log("inside movefast object");
                }

            }
    }

```

When My Obstacle Touch My Player then Ontrigger2d Is fire

```
Obstacle.cs

 void OnTriggerEnter2D(Collider2D other)
    {
        foreach (Transform child in GetComponentsInChildren<Transform>())
        {
            if (child.tag == "someobstacleslow" || child.tag == "someobstaclefast")
            {
                Debug.Log("chiildtag:" + child.tag);
                gameovertext.SetActive(true);

                StartCoroutine(gameover());
                Debug.Log("inside triggerfire");
            }
        }
    }

```

But Issue Is all obstacle going very fast(See in referance).I want to some obstacleslow is going slow and someobstaclefast is going fast but nothing happens.??help

# Answer
You are changing the parent's transform. Instead change the children's transform.

```
void goTopToDown()
{
        foreach (Transform item in GetComponentsInChildren<Transform>())
        {
            if (item.tag == "someobstacleslow")   //issue here
            {
                //Instead of 'trasnform'(parent's transform) you need 'item' (child's transform)
                item.position += Vector3.down * speed * Time.deltaTime

                Debug.Log("GameObject obstacle object:" + item.tag);
                Debug.Log("inside obstacle object");

            }

            if (item.tag == "someobstaclefast") // issue here
            {
                item.position += Vector3.down * movefastobjectspeed * Time.deltaTime;

                Debug.Log("GameObject movefast object:" + item.tag);
                Debug.Log("inside movefast object");
            }

        }
}

```
> 0 votes

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


title: Bird flight simulation (physics)

text:
# Question
Title: Bird flight simulation (physics)
I tried to search something about bird-like animal flight simulation but it looks like everything is spammed with flappy bird 2D questions.

I want to have in my 3D game bird-like animals with realistic flight, for example we have a scene where player attacked by predator birds and he must attack them with gun. When I say bird-like, I mean that animal has wings.

As I understand I need to apply force to bird object to compensate gravity force, but if I do this strictly, it looks very unnatural. So could someone provide good description or maybe links to good articles about such simulation for 3D game?

# Answer
If I were doing a 3D game, I'd not go into physical simulation of birds but rather a simplified kinematic trajectory model of a flying thing.

The trajectory of a bird in flight is simply three accelerations and three orientations.

Once you determine (at runtime) the accelerations of the bird (or the trajectory of the bird), you add corresponding animation sequences (e.g. bird slowing down, bird diving, bird gliding, bird speeding up).
> 2 votes

---
Tags: physics, 3d
---


# Question
Title: How to deal with VBO and obj files for physics simulation?
I'm having a hard time struggling with obj files and clothing simulations. I first made the obj file processor class that deals with the typical obj file problem: having multiple indices for vertex position, vertex texture coordinates, and vertex normals like this `f 52/49/224 57/54/224 279/270/224`. I made a function that shrinks the multiple index arrays to one index array.

```
class VERTEX{
public:
    glm::vec3 position;
    glm::vec2 uv_coord;
    glm::vec3 normal;
};

std::vector<VERTEX> out_vertices;
std::vector<unsigned int> out_indices;

void reorderData(){
        for(int i=0;i<vertexIndices.size();i++){
            VERTEX vertex;
            // add -1 to each index as indices for obj files start from 1, not 0.
            int vi = vertexIndices[i]-1;
            int uvi = uvIndices[i]-1;
            int ni = normalIndices[i]-1;
            vertex.position = temp_vertices[vi];
            vertex.uv_coord = temp_uvs[uvi];
            vertex.normal = temp_normals[ni];
            //assign new index here for the VERTEX object
            int index = getVertexIndex(vertex);
            //If it's a new index, it means it's a new VERTEX. Store it in out_vertices.
            if(index==out_vertices.size()){
                out_vertices.push_back(vertex);
            }
            out_indices.push_back(index);
        }
    }

```

Then I use `out_vertices` and `out_indices` to set up the VAO, VBO, and EBO for rendering. The problem here is that in the VBO, there are multiple VERTEX objects that have the same `position` value.

However, in order to do physics simulation, I need a `particle` class that deals with calculating the force, speed, position for every loop of each cloth particle.

```
class particle{
public:
    glm::vec3 position;
    glm::vec3 force;
    glm::vec3 speed;
    float mass;
}

```

And if I just copy the the `VERTEX` objects' position values to the `particle` objects, then there will be multiple `particle` objects with the same position value. But this doesn't seem right as there should be only one `particle` object for each unique position.

So my solution at the moment is, to first make `particle` objects that each have unique position values. Then, after each physics loop calculating a particle's speed, force, position, I update all the `VERTEX` objects whose position value has changed for the corresponding 'position' object. Lastly I update the VBO.

Would this be the right approach? I am afraid that linearly searching the multiple VERTEX objects who have the same `position` value as the particle object is going to take a lot of time. Any help would be appreciated. Thanks in advance!

---

To be short what I want to seek advice about is how to seperate and handle the rendering data and the physics simulation data efficiently.

# Answer
> 0 votes
Assuming that your object is made up of triangle faces, use the center of those triangles for the position data of that particular face.

This will get rid of all duplicate vertex data.

---
Tags: opengl, physics, particles, vbo, simulations
---


# Question
Title: Dealing with more complex entities in an ECS architecture
Preamble: I'm working on a level editor for my engine, which uses an ECS architecture. I have around a dozen component types so far, mostly dealing with graphics, like lighting components, model, and other mesh related things like skeleton and collider components.

My engine only supports 1 of each component type per entity, and systems can deal with optional components as well.

---

Today I realized I was uncertain on how I should tie-together the building block components used for basic entities into a more complex one.

For example, let's say I want to make a torch / flaming stick, using the components found in a model entity and a lighting entity.
If the model's origin is in the center of the shaft, then the light and fire would appear at the center of the model.
Further, if I wanted a weird torch with fire on one end of the stick and smoke on the other, they would both need different offsets before rendering.

Do I need to create a system just for torch's, adjusting all the components to fit the model? This doesn't sound like it scales well to different models needing 'decorations'.

Should I instead be creating an attachment component, with its own offset variables? What dictates which components of an entity use the offset? Should I be making attachment types for every component type that could need an offset?
Or rather should most components just have a spatial offset as another parameter the user can control?

Anyone know any commonly used solutions?

# Answer
> 8 votes
Games typically approach this type of issue using a transformation hierarchy.

In this model, each entity can be treated as a "child" of a "parent" entity. The entity's local position and orientation components are interpreted to be relative to the position and orientation of the parent.

Parent entities may in turn have their own parents, grandparents, etc., all the way up to "root" objects that are positioned absolutely in world space.

This lets us build complex articulated structures - like a car with independently spinning/suspended wheels and passengers/cargo that follow it along for the ride, or a humanoid character with a hand that pivots at the wrist of a forearm that pivots at the elbow of an upper arm that pivots at the shoulder... all using one simple transformation composition rule, rather than adding special-case offsets and variants throughout all our components.

Contrary to the concern raised in the comments, this does not need to be unduly unfriendly to the cache. In a simple model, we can associate the following data with each entity, usually in a "transform" component, though it could be subdivided into more granular components:

* a local position
* a local orientation
* a local uniform scale
* a parent entity index (-1 for "this is a root entity")
* a world position
* a world orientation
* a world uniform scale
(these last three could be combined into a world transformation matrix)

Most systems make updates only to the local properties (say, a skeletal animation system rotating each bone's local orientation about its pivot) so they don't need to peek into the hierarchy at all and can do their work strictly on one entity at a time (friendly for parallelization). We can defer updates to the world properties until the next physics or rendering step where we need final positions & such.

If we store our entities in non-decreasing order of parent entity ID (this is not too onerous to maintain, since re-parenting is very rare compared to routine transformation updates), then we can update the whole hierarchy's world properties in one linear scan:

* First, we update all the root entities by copying their local parameters to their world parameters
* Next, we walk these lists of components with two indices: the current entity we're updating, and the parent index.

Both these indices move strictly forward through the arrays, so we're not jumping back and forth randomly thrashing the cache. In fact we'll often update several entities in a row with the same or adjacent parents, getting excellent cache utilization despite the indirection.
* For each of these entities, we update the global properties like so:

```
parent = parentIndex[current];
worldPosition[current]    = worldPosition[parent]
                          + worldOrientation[parent] * localPosition[current];
worldOrientation[current] = worldOrientation[parent] * localOrientation[current];
worldScale[current]       = worldScale[parent]       * localScale[current];

// or

Mat4x4 localTransform   = TranslateRotateScale(
                             localPosition[current],
                             localOrientation[current],
                             localScale[current],
                          );
worldTransform[current] = worldTransform[parent] * localTransform;

```

You can even parallelize this work if needed, by dividing your root objects between separate arrays, and placing child objects in the same array as the root. Then each array can have its hierarchy updated independently of the others.

Most interaction between entities in the hierarchy can be accomplished with message systems. So the Torch system doesn't need to directly manipulate the Light Source component on the torch's child entity. It can just leave it a "Turn on" / "Turn off" message when it needs to change state, and the Light system can process that message when it iterates its Light Source components later in the frame.

Now, there will be occasional scripts that do need to reach across to different entities make their decisions and updates. Like an AI awareness system that needs to gather information about nearby entities to update the current entity's state. That's OK though - and largely unavoidable anyway, even with a flat hierarchy. The goal of a data-oriented ECS is not to outright forbid reference-following, it's to keep costly reference-chasing out of the hottest code paths - the things we need to iterate thousands of times per frame.

You can have thousands of animated characters swinging tens of thousands of individual bone transforms around with minimal cache misses, so the less predictable parts of your game scripts - like the player character control logic that only needs to run for a handful of local players each frame - has the breathing room to do its work.

Use the data orientation where it helps you do lots of stuff quickly, but don't let it be a wall that stops you from getting the gameplay behaviour you want.

---
Tags: component-based, entity-component, game-component, entity-component-system
---


title: How to implement arcade-style spawning?

text:
# Question
Title: How to implement arcade-style spawning?
In many arcade-style games with a horizontally scrolling camera, enemies spawn offscreen, either left or right, and traverse the screen in the opposite direction.

Spawning enemies is easy enough, but my question concerns the logic of getting them to spawn in an arcade-type way, just offscreen and according to the predefined patterns of the designer.

One idea I thought of was designating trigger areas in my level. When the player enters a trigger, enemy spawn points associated with that trigger then spawn enemies. But with a scrolling camera, sometimes as the camera scrolls, those spawn points enter the viewport and enemies spawn on screen out of nowhere.

**What is a good technique to achieve arcade-style enemy spawns?**

Here are two examples of the types of spawns I am thinking about:

https://youtu.be/Z7lAZExM21k?t=310 (Blazing Chrome by Joymasher) https://youtu.be/UAOFcpOfOVs?t=362 (Nightmare Busters by Arcade Zone)

# Answer
Don't trigger based on the camera's position. Trigger based on the player's.

Once the player enters the trigger you spawn the enemies just outside the edges of the camera's view. Since the camera should be following the player anyway, you can derive the edges of the screen from its position and the screen dimensions. Then it's a simple matter of adding/subtracting to the calculated position to hide the pop-in off screen.
> 4 votes

---
Tags: 2d, spawning, arcade
---


# Question
Title: Unity Pre Build Script - Add target dependent UI Elements
I wrote a postbuild script that deploys my builds to google drive. That works great, but when I tried to use the same type of logic on a pre build script, it fails. I'm trying to enable all game objects with the tag `Mobile` if the platform is mobile (andriod or ios). Otherwise turn those off. This is what I have for a script:

```
#if UNITY_EDITOR
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using UnityEngine;
using UnityEditor;

public class PreBuild : IPreprocessBuildWithReport
{
    public int callbackOrder => 0;

    public void OnPreprocessBuild(BuildReport report)
    {
        var mobileGameObjects = GameObject.FindGameObjectsWithTag("Mobile");
        switch (report.summary.platform) // todo: make sure all targets are populated here
        {
            // mobiles
            case BuildTarget.Android:
            case BuildTarget.iOS:
                //enable all game objects
                foreach (var mobileGameObject in mobileGameObjects)
                {
                    mobileGameObject.SetActive(true);
                }

                break;
            // standalones (desktops)
            case BuildTarget.StandaloneWindows:
            case BuildTarget.StandaloneLinux64:
            case BuildTarget.StandaloneOSX:
                foreach (var mobileGameObject in mobileGameObjects)
                {
                    mobileGameObject.SetActive(false);
                }

                break;
            // todo: consoles
        }
    }
}
#endif

```

The build runs fine, but when I run in mobile, none of the UI elements are there (off by default). Here is the heirarchy of them in my project: (screenshot not working):

```
- UI (Canvas Game Object)
  - Mobile ("Empty" Game Object, is tagged with "Mobile")
    - Joystick1
    - Joystick2
    - ActionButton

```

What am I missing?

# Answer
> 3 votes
A few notes:

First, FindGameObjectsWithTag only finds active GameObjects. You would need every GameObject you wanted to possibly have enabled be active in the scene when saving it.

Second, that build preprocessor does not run with a specific scene loaded. You perhaps want to use a per-scene processor:

`IProcessSceneWithReport.OnProcessScene`

This processor runs in play mode in the editor as well, so that should be taken into account (by checking `if (report == null)`), unless it is desirable to have this behavior in the editor during testing.

Third, this script should go into an Editor folder so you don’t need to include #if UNITY\_EDITOR.

So here’s my take (warning: untested):

```
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using UnityEngine;
using UnityEditor;
using System.Linq;

public class PreBuild : IProcessSceneWithReport
{
    public int callbackOrder => 0;

    public void OnProcessScene(UnityEngine.SceneManagement.Scene scene, BuildReport report)
    {
        if (report == null) return;
        foreach (var root in scene.GetRootGameObjects())
        {
            ProcessHierarchy(root.transform, report);
        }
    }

    private void ProcessHierarchy(Transform root, BuildReport report)
    {
        var allTransforms = root.GetComponentsInChildren<Transform>(true);
        var mobileGameObjects = allTransforms.Where(t=>t.CompareTag("Mobile")).Select(t=>t.gameObject);
        BuildTarget bt = report.summary.platform;
        bool isMobile = bt == BuildTarget.Android || bt == BuildTarget.iOS;
        foreach (var mobileGameObject in mobileGameObjects)
        {
            mobileGameObject.SetActive(isMobile);
        }
    }
}

```

---
Tags: unity, build-process
---


# Question
Title: Generate random number in Unity without class ambiguity
I have a problem in Unity (C#) where I would like to create a random number. I wanted to use `System.Random` (reference: using `System`) but Unity complains that it's ambiguous to their own `UnityEngine.Random`. I can not specify the reference (using `System.Random`) as `random` is not a namespace. How do I specify that I want to use the system random and not the Unity one?

# Answer
> 30 votes
You could specify the namespace explicitly:

```
System.Random random = new System.Random(seed);
random.Next();

```

# Answer
> 26 votes
You can use a using alias directive to give System.Random a new name as well:

```
using Rng = System.Random;

```

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


# Question
Title: Unity animation tool doesn't save changes
I'm trying to create an animation inside Unity using the animator tool, however the record tool isn't recording my changes and I'm struggling to get this to create animations.

I have created an example here: https://i.gyazo.com/91f88b3531b4fb3ffd4100d40f06bdcf.mp4

I have tried recreating the animation file, but no matter what I do it refuses to record the element?

Any information would be appreciated, as it appears unity may be bugged.

When applying an update between tweened keypoints the fields for X Y Z are red and do not apply changes

# Answer
What you need is to add key frames to the animation.

There is a button on the right of where it says "Samples 60", a sort of diamond with a cross hair in it this is how you add key frames.

So add one key frame at the start of the animation for what position/rotation whatever the animated object starts in (which you can see in your screen shot as the diamonds in a column)

Then add another keyframe at the end with the end value you want to animate to, obviously you can add more keyframes, I would check https://docs.unity3d.com/Manual/animeditor-AnimatingAGameObject.html for a better understanding.

You also dont have to record the animations as such if you wish, you could define the first key frame with a position (0,0,0) then add another key frame and set the objects position to (0,10,0) then press play and watch it animate between start and end values.
> 1 votes

# Answer
I faced this problem too. I got it to work using the auto keyframe recorder (the red dot button) on the Animation tab.
> 0 votes

---
Tags: unity, animation, rigging
---


title: Best way to retrieve const data

text:
# Question
Title: Best way to retrieve const data
My game uses big const data which i need to retrieve it to use data used on each level when its needed data security is important

I got two options in my head which one is better?

Note the data is const and it never changes during game and only i can change it on coding for using it on some levels and after build it always same data

**1: using return "data"**

Something like this which means data stored in script and finding script will expose data

```
if(level_number < 10)
{
switch level_number

case 1:
return data_1;
.
.
.
}
if(10<level_number <20)
{
.
.
.
}

```

**2: saving in binary file**

Check if the file exist read it and if it isn't then create it during game and use it next time

This one uses binary formatter to save/load data and there is two options for this too

2.1: creating file during game which still have same problem like first solution

2.2: creating file on the editor and load it from plugin folder etc

And second one also have storage usage when first one just a script which returns some const data

I know you cant stop hackers from hacking offline file but i'm also looking better way to save this big const data and retrieve it to use it

Which one is better and if you have better solution i'm happy to hear it

# Answer
From a security standpoint, as you note, they're basically equivalent (which is to say *not secure* at all). So it doesn't particular matter on that front.

Generally speaking I'd suggest you keep data (constant or otherwise) distinct from code, because then you don't have to go through the process of rebuilding the game (and in some cases repackaging it also) to change some data.

That implies storing it in a file along with the levels or (in the case where sometimes the same set of data is shared between multiple levels) alongside the levels in separate files.

In your case, however, it sounds like the whole question is a bit irrelevant, since you note that one option related to storing it a file is to

> Check if the file exist read it and if it isn't then create it during game and use it next time

which implies you *already have the data in memory* (otherwise you couldn't create a file with anything meaningful in it). In your case, since your dataset seems very small and simple, it may be more pragmatic at this point to simply keep continuing with the data (a list of strings, as you note in the comments) in code.
> 1 votes

# Answer
When you want to prevent your players from reverse-engineering your game, you are fighting a battle against windmills. You can make them jump through hoops, but you can not prevent it. And if anyone ever finds your level details and secret items through the regular ingame methods, they will just create a wiki and share it with the whole community. You can't keep secrets in the Internet age.

If you want to manage static data in Unity, then you might want to look into `ScriptableObject`s. ScriptableObjects are a technique which allows you to create custom, data-based assets which you can create and manage in the Unity editor and assign to inspector-exposed fields of your MonoBehaviours. Just like any of the regular Unity assets.
> 1 votes

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


title: Game movement in 2D SFML game

text:
# Question
Title: Game movement in 2D SFML game
I am making simple 2D game, imagine it as 2D Minecraft where you can dig blocks and build other things.

Currently I am struggling with movement. I have none experience in game development, but I am quite familliar with C++, that is why I am using SFML.

What situations I am considering in movement:

1. Collision while moving on the X axis
2. Collision when jumping ( on the Y axis )
3. Fall down if there is no block under

My player sprite is 64x32 (h x w) and block is 32 x 32. I store blocks as `vector<vector<unique_ptr<Block>>>` so I can calculate the index of the block as `x_pos DIV 32, y_pos DIV 32`

This is how I currently check if there is block ( X axis ):

```
new_position = actual_pos + velocity; // calculate new position
face_level = new_position.y DIV 32; // level 0 is the ground
feet_level = face_level + 1; // +1 is good, cause we increase level by going down
x_level = new_position.x DIV 32;
if (block_exists[feet_level][x_level] || block_exists[face_level][x_level]) {
    return Collision::Block_Collision;
}

```

and then check

```
collision = check_collision();
if ( collision == Collision::Block_Collision ) {
    // X axis
    stop_moving();
}
if ( collision == Collision::No_Block_Under ) {
    // falling
    fall_down;
}
if ( collision == Collision::Block_Above ) {
    // Y axis, actually do nothing, "dont jump"
}

```

If going left, I consider left border of the player. If going right, I consider right border of the player.

This was the easiest part.

What position should I use for the falling part? Should it be the middle of the player, or left/right border combined ? If I used the middle position, then player would fall into the block if he was standing on the left/right half.

Question is, what would be the best approach generally to solve these 3 situations.

# Answer
When going left/right, you use the *whole* left/right border (aka collider/detector) to check if player collides. If going up/down, you should use the *whole* top/bottom border of the player to check the collision. This means you have to check for *all blocks* that detector overlaps.

This will complicate your collision detection, but doing it right will spare you from nasty bugs like player falling into the terrain, of phasing through the obstacles.
> 1 votes

# Answer
your character should only fall if there is nothing underneath him as in he shouldn't be colliding with any block underneath him from the left extent of his bounding rectangle to the right extent of the bounding rectangle.

if you have moving objects that you need to consider the relative velocities of each or of one to the other.

Easiest to perform is a sweep test where you take the bounding rectangle and drag it and the resulting area is what you test against the other object.

So basically it resolves to polygonal collision detection.
> 0 votes

---
Tags: c++, 2d, sfml
---


title: How to change material color (LWRP)

text:
# Question
Title: How to change material color (LWRP)
I've upgraded my project to LWRP, I've changed my materials to: LWRP/lit. But in one of the gamemodes i need to change one my materials' color by script. I used to do it simply like `wallMat.color = Color.red`, but at LWRP that code doesn't work, how to fix it?

**Edit:** LWRP = Light Weight Render Pipeline

# Answer
You can do this with a MaterialPropertyBlock, just like you would in the old pipeline to reduce the overhead of instantiating modified copies of materials. The only difference is that the shader property is called "\_BaseColor" not "\_Color":

```
// You can re-use this block between calls rather than constructing a new one each time.
var block = new MaterialPropertyBlock();

// You can look up the property by ID instead of the string to be more efficient.
block.SetColor("_BaseColor", Color.red);

// You can cache a reference to the renderer to avoid searching for it.
GetComponent<Renderer>().SetPropertyBlock(block);

```
> 5 votes

# Answer
This works fine as well:

`material.SetColor("_BaseColor", color);`
> 7 votes

# Answer
I've tried matName.CopyPropertiesFromMaterial(otherMatName); and it worked! Creating another materials isn't the best way but in my case i've already had those materials and this way was the solution for me.
> 0 votes

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


# Question
Title: Find the co-ordinates of collided objects in Python
I have a group containing my aliens and another containing the bullets I have fired. When I detect their collisions, I want to pull the alien's x-y co-ordinates during it's deletion so I can put an explosion animation in that location. How do I achieve this? My attempts so far give an error saying group items cannot be indexed.

This is my first real coding project - so still new. I'm using Pygame to make the game.

Current collision detection code:

```
def check_bullet_alien_collisions(ai_settings,screen,stats,sb,ship,aliens,bullets,bombs):
"""Respond to bullet-alien collisions"""

collisions = pygame.sprite.groupcollide(bullets,aliens,True,True)

#Collect X-Y co-ordinates here

if collisions:
    for aliens in collisions.values():
        stats.score += ai_settings.alien_points * len(aliens)
        sb.prep_score()
        stats.aliens_hit += 1
        stats.calc_accuracy()
        sb.accuracy()
    check_high_score(stats,sb)

```

# Answer
After much trial and error, I've found a solution that works. Rather than having a central function that loops through the groups to find collisions, I split it out so each object checks for and detects it's own collisions. It then calls the explosion animation function before deleting itself. The extra scoreboard updates have remained behind and are updated by a separate call during each run through the main loop instead.

```
class Alien(Sprite):

    #other functions truncated

    def update(self,ai_settings,screen,stats,aliens,bullets,explosions):
        """Move aliens to the right or left"""
        self.x += (self.ai_settings.alien_speed_factor * self.ai_settings.fleet_direction)
        self.rect.x = self.x

        if pygame.sprite.spritecollide(self,bullets,True):
            stats.score += ai_settings.alien_points
            stats.aliens_hit += 1
            target_x = self.rect.centerx
            target_y = self.rect.centery
            gf.explode(ai_settings,screen,target_x,target_y,explosions)
            self.kill()

```
> 1 votes

---
Tags: collision-detection, pygame, coordinates
---


# Question
Title: Improve velocity obstacle calculation algorithm/performance
**My goal**

My goal is to calculate the (velocity) obstacle that is imposed by unit B onto unit A. So I want to calculate the velocities from the center of unit A (circle) that will lead to a collision with unit B assuming unit B is not moving. The illegal velocities would be all velocities that are between the two tangents from the center of unit A to unit B (circle).
Thus I actually only need the angle of the two tangents relative to some other velocity.

Here is a simple drawing to illustrate my approach:

The "other vector" (=green) is the "optimal velocity" for unit A, that is calculated through higher level pathfinding. My goal is then to choose the velocity that is closest to the optimal velocity, but not within the blocked/illegal velocities.

**My approach**

I already have a working demo, but it is too slow.

Note: In my implementation I extruded the radius of unit B by the radius of unit A.

My (primitive) approach to calculating the angles is:
1. Calculate the line from the center of unit A to Unit B
2. Calculate the first tangent point using trigonometry
3. Calculate the closest point from the first tangent point to the line from (1) (i call it the mirrorPoint)
4. Mirror the first tangent point along the mirrorPoint
5. Calculate angle1 and angle2 using Vector.SignedAngle

After wards i still have to do some work to find the closest legal vector to the optimal velocity, but that is not too time consuming.

Here is an image taken from the editor:

The purple line is (1)
The green lines are the lines from the center of Unit B to the tangent points.
The black line (in unit B) are the lines from the mirrorPoint to the tangent points
The blue and the red line are the lines from the center of unit A to the tangent points
The orange line is the optimal velocity
The black line (starting at the center of Unit A) is the legal velocity that is closest to optimal velocity

Here is the code that i use to calculate the angles:

```
public Vector2 GetDesiredSteering(VelocityObstacleSteeringInput input)
    {
        TestUnit unit = input.Unit;
        List<TestUnit> neighbors = GetNeighbors(unit);
        foreach (TestUnit neighbor in neighbors)
        {
            Vector2 tangent1;
            Vector2 tangent2;
            CalculateTangent(unit.Pos, unit.Scale.x, neighbor.Pos, neighbor.Scale.x, out tangent1, out tangent2);

            Vector2 relativeTangent1 = tangent1 - unit.Pos;
            Vector2 relativeTangent2 = tangent2 - unit.Pos;
            float angle1 = Vector2.SignedAngle(relativeTangent1, input.OptimalVelocity);
            float angle2 = Vector2.SignedAngle(relativeTangent2, input.OptimalVelocity);
            Debug.Log("angle1: " + angle1 + " angle2: " + angle2);
        }

        //return dummy for this stripped down version
        return Vector2.up;
    }

 bool CalculateTangent(Vector2 unitPos, float unitRadius, Vector2 otherPos, float otherRadius, out Vector2 tangentPoint1, out Vector2 tangentPoint2)
    {
        Vector2 hypo = unitPos - otherPos;
        float hypoLen = hypo.magnitude;
        float combinedRadius = (unitRadius + otherRadius) / 2.0f;
        float ratio = combinedRadius / hypoLen;
        float alpha = Mathf.Acos(ratio);
        hypo.Normalize();
        Vector2 rotated = GeometryHelper.RotateRad(hypo, -alpha);
        Vector2 centerToTangent = rotated * combinedRadius;
        tangentPoint1 = otherPos + centerToTangent;
        tangentPoint2 = GeometryHelper.CenterToOtherTangentPoint(otherPos, hypo, tangentPoint1, out Vector2 curMirrorPoint);
        return true;
    }

 public static Vector2 RotateRad(Vector2 aPoint, float rad)
    {
        float s = Mathf.Sin(rad);
        float c = Mathf.Cos(rad);
        return new Vector2(
            aPoint.x * c - aPoint.y * s,
            aPoint.y * c + aPoint.x * s);
    }

//linePointhas to be center of unit
 public static Vector2 CenterToOtherTangentPoint(Vector2 linePoint, Vector2 lineDirection, Vector2 tangentPoint1, out Vector2 returnMirrorPoint)
    {
        Vector2 mirrorPoint = FindNearestPointOnLine(linePoint, lineDirection, tangentPoint1);
        returnMirrorPoint = mirrorPoint;
        Vector2 tangentPointToMirrorPoint = mirrorPoint - tangentPoint1;
        return mirrorPoint + tangentPointToMirrorPoint;
    }

 public static Vector2 FindNearestPointOnLine(Vector2 origin, Vector2 direction, Vector2 point)
    {
        direction.Normalize();
        Vector2 lhs = point - origin;

        //t = how far to move from the origin along the direction to reach the closest point
        float t = Vector2.Dot(lhs, direction);
        return origin + direction * t;
    }

```

**My Problem**

I need to be able to scale this approach to at the very minmum 100 units (but I would very much prefer 200 units), which currently is not possible, because the algorithm/implementation is too slow.

So I am wondering if somebody can think of an improvement to this approach. Either mathematically(i.e. some better method/shortcut to calculate the angles) or other tips how to improve my code.

# Answer
The first and best optimization you can make is to **cut down on the number of times you need to do this calculation at all**. You may already be doing this, but since we can't tell from your question, here's a quick intro to the idea:

If every moving object needs to compute steering angles vs every obstacle object, then your total cost is:

```
[# moving objects] * ([# obstacles] * [cost per angle range calc]
                      + [cost of velocity selection])

```

This grows quadratically as you add more stuff to your world (assuming the ratio of moving objects to obstacles remains similar)

But, if each moving object only needs to consider the obstacles "close" to it, and there's on average ~3 obstacles in that range, then your expected cost drops to:

```
[# moving objects] * (3 * [cost per angle range calc]
                      + [cost of velocity selection]
                      + [cost to find close obstacles])

```

Now this grows *linearly* as your scene expands (with suitable implementation choices). You might even be able to skip obstacle computations for some moving objects entirely, if they're in open space.

Of course, this depends on having a fast way to gather the few relevant obstacles without iterating over the whole collection. You can use a spatial partition data structure for this, so you only need to search the partition cells within your avoidance radius. If you're using physics colliders, then Physics2D.OverlapCircleNonAlloc gives you a quick way to query this using the built-in physics engine's spatial partition, rather than maintaining your own. Or you could use a trigger collider to detect when new obstacles come into range and prune them as they leave your range.

---

Okay, so let's assume we've done everything in our power to limit the number of obstacles we're considering for each mover, and we're still finding the `[cost per angle range calc]` is too much. What can we do to bring that down?

As others have pointed out, it's really the transcendentals that are the slowest here. (That's the trig functions like sin, asin, atan2 - used inside the `Angle()` / `SignedAngle()` methods even when you don't write them explicitly)

Estimates vary depending on the processor, but you can generally expect addition/subtraction/multiplication to have extremely high throughput and low latency. Costs for division can be ~10 times more than the other arithmetical operators, and square roots ~20 times more. Trig operations however can be more like ~100 times more costly.

So **what if we tried to put off that trigonometry for as long as possible?**

Instead of computing absolute angles, let's compute tangent ratios of angles relative to our current velocity. These increase monotonically with angle over the 180-degree arc in front of our object, so the overlapping ranges of "tangent ratio obstacles" we calculate this way will correspond 1:1 with the velocity obstacles we want to find. Once we've identified a range of tangent ratios that we want to steer toward, we can convert just the two endpoints of that range back to angles, rather than doing it for every intermediate calculation.

(This method does not scale gracefully to the full circle, unfortunately, but we can work around this: if we find an object that's completely blocked from 90° left to 90° right, we can check the arc behind us as a fallback; hopefully this case is rare)

To do this, we'll exploit some trig identities....

$$\begin{align} \tan(\theta + \alpha) &= \frac {\tan\theta + \tan\alpha} {1 - \tan\theta \tan\alpha} = \frac { \frac y x + \frac r c} {1 - \frac y x \frac r c} = \frac { \frac {yc + xr} {xc} } {\frac { xc - yr} {xc}} = \frac {yc + xr} {xc - yr} \\ \tan(\theta - \alpha) &= \frac {\tan\theta - \tan\alpha} {1 + \tan\theta \tan\alpha} = \frac { \frac y x - \frac r c} {1 + \frac y x \frac r c} = \frac { \frac {yc - xr} {xc} } {\frac { xc + yr} {xc}} = \frac {yc - xr} {xc + yr} \end{align}$$

First, for each moving object we can pre-compute the following:

```
object.forward = object.velocity.normalized;
object.left = new Vector2(-object.forward.y, object.forward.x);

```

(Or, if you're already rotating your objects to face their velocity, their transform components will already pre-compute this for you)

Now, when considering each obstacle, we can compute:

```
Vector2 offset = objectB.position - objectA.position;
Vector2 localOffset = new Vector2(
                          Vector2.Dot(forward, offset),
                          Vector2.Dot(left, offset)
                      );
// Or localOffset = transform.inverseTransformPoint(objectB.position);

float radiusComplement = Mathf.Sqrt(localOffset.sqrMagnitude - objectB.radius * objectB.radius);

float xr = localOffset.x * objectB.radius;
float xc = localOffset.x * radiusComplement;
float yr = localOffset.y * objectB.radius;
float yc = localOffset.y * radiusComplement;

float minTan = (yc - xr)/(xc + yr);
float maxTan = (yc + xr)/(xc - yr);

// If we've crossed the y-axis, clamp to 90° left / right.
if(minTan * localOffset.y < 0f) minTan = minTan * float.NegativeInfinity;
if(maxTan * localOffset.y < 0f) maxTan = maxTan * float.NegativeInfinity;

```

Note that in the above we needed just one square root per moving object / obstacle pair (to compute \\$c\\$ AKA `radiusComplement`), comparable to the magnitude operations in the other solutions. Everything else is multiplication, addition, and subtraction, which are very cheap, and two divisions, which are more costly but still not as much so as a square root or trig function.

After we've computed the `minTan` and `maxTan` for all obstacles in range and found the best viable gap, we can convert it back to an absolute velocity, again without trig functions, like so:

```
Vector2 newDirection = (forward + chosenTangent * left).normalized;
Vector2 newVelocity = newDirection * speed;

```

So the total count of expensive ops is:

* per moving object:

+ 2 square roots
    + 4 divisions (dividing each of `x` & `y` by length in the two `.normalized` calls, though it's possible these will be vectorized so we pay more like the cost of 2)
    + 0 trig functions
* per mover/obstacle pair:

+ 1 square root
    + 2 divisions
    + 0 trig functions

---

**Edit:**

Come to think of it, we might be able to do this better using a (modified) sine ratio instead of the tangent ratio, to cover the full 360° in one pass:

```
float inverseSquare = 1f / localOffset.sqrMagnitude;

float maxSine = inverseSquare * (yc + xr);
float minSine = inverseSquare * (yc - xr);

if (xc - yr < 0) maxSine = Mathf.Sign(maxSine) * 2f - maxSine;
if (xc + yr < 0) minSine = Mathf.Sign(minSine) * 2f - minSine;

if(minSine < maxSine) {
    AddObstacleRange(minSine, maxSine);
} else {
    AddObstacleRange(-2f, maxSine);
    AddObstacleRange(minSine, 2f);
}

```

These values will sit in the range -2...2, with the values between -1...1 corresponding to the sine of the angle within the 180° arc in front of the moving object. Values outside this range correspond to the 180° behind the mover, "unfolded" so that we get a non-decreasing function over angles from -180° to +180°.

---

With either solution, you can merge obstacle ranges as you find them, like so:

```
void AddObstacleRange(float min, float max) {
    for(int i = 0; i < obstacleRanges.Count; i++) {
        // Leave any ranges that don't intersect this one as-is.
        if(obstacleRanges[i].min > max || obstacleRanges[i].max < min)
           continue;

        // Expand the range to encompass any other ranges it rouches.
        min = Mathf.Min(min, obstacleRanges[i].min);
        max = Mathf.Max(max, obstacleRanges[i].max);

        // Remove any ranges subsumed in this way.
        UnorderedRemove(obstacleRanges, i--);
    }
    // Add our (possibly expanded) obstacle range to the list.
    obstacleRanges.Add(new ObstacleRange(min, max));
}

```

Then once you've got all the obstacles accounted for, you can scan through them looking for the window edge closest to zero, or zero itself if nothing blocks it:

```
float GetLeastDeviation() {
    // Find the obstacle range that covers zero, and return is nearest edge.
    foreach(var range in obstacleRanges) {
        if(range.min < 0f && range.max > 0f)
            return range.max > -range.min ? range.min : range.max;
    }

    // If there's no obstacle covering zero, then our ideal trajectory
    // isn't blocked, and we can continue without evasive maneuvers.
    return 0f;
}

```

Then you can convert that closest unblocked (pseudo) ratio back into an angle or velocity as needed.
> 2 votes

# Answer
---

## New Answer

Frame challenge: If we are checking if the sphere will collide with another, ee do not need angles. We need to know if the velocity vector we use for reference will lead to a collision of the spheres.

That is, we need to know if the distance from the second sphere to the line defined by the position of the first sphere and the velocity vector passes closer than the sum of the radius of the first sphere and the radius of the second sphere.

We, start by working with the center of the first sphere as origin. Then project the position of the second sphere (respect to the origin, a.k.a. the center of the first sphere) to the velocity vector. Then we take the distance of the projection to it, and see if it is too close.

Thus:

```
bool isOutOfRange(sphere1, sphere2, velocity)
{
    var L = sphere2.position - sphere1.position;
    var projected = velocity* dot(L, velocity) / dot (velocity, velocity);
    var check = L - projected; // order of operands is irrelevant
    var r = sphere1.radius + sphere2.radius;
    return length(check) > r;
}

```

Now, we have no angles, and no trigonometry. We have an sqrt hidding there still... we can get rid of it by comparing the square of the length:

```
bool isOutOfRange(sphere1, sphere2, velocity)
{
    var L = sphere2.position - sphere1.position;
    var projected = velocity* dot(L, velocity) / dot (velocity, velocity);
    var check = L - projected;
    var r = sphere1.radius + sphere2.radius;
    return (check.x * check.x + check.y * check.y) > (r * r); // 2D, right?
}

```

Et voilà, no trigonometry, and no sqrt.

---

**Addendum**

OP says:

> Do you also have an idea how I could efficiently select the closest angle to the optimal velocity that is not within one of the angle-ranges that are blocked by the neighbors/velocity obstacles (obviously that could also be the optimal velocity if it is not blocked)?

For a single obstacle, assuming the velocity vector does not match the vector the center of the other sphere, then this is easy: Having the vector that goes from the center of the second sphere to its projection on the velocity vector, we can get a point that is just outside the range. Then if we scale it to the velocity we have our new velocity.

```
vector getFixedVelocity(sphere1, sphere2, velocity)
{
    var L = sphere2.position - sphere1.position;
    var projected = velocity* dot(L, velocity) / dot (velocity, velocity);
    var check = projected - L; // order is important now
    var r = sphere1.radius + sphere2.radius;
    if ((check.x * check.x + check.y * check.y) > (r * r))
    {
        return velocity;
    }
    var just = sphere2.position + r * normalize(check);
    return length(velocity) * normalize(just);
}

```

This is the vector that has the same length as the input velocity, does not hit the obstacle and is closer to the input velocity. To get the other velocity (the one that is further away) you can reflect the `just` vector.

Also Notice I introduced three sqrt. If you can pass the unit velocity, you can get rid of one. The other two are actually `1/sqrt` for which there are well known optimizations (which hopefully `normalize` already uses).

This is the code to get both vectors:

```
(vector, vector) getFixedVelocity(sphere1, sphere2, velocity)
{
    var L = sphere2.position - sphere1.position;
    var projected = velocity* dot(L, velocity) / dot (velocity, velocity);
    var check = projected - L;
    var r = sphere1.radius + sphere2.radius;
    if ((check.x * check.x + check.y * check.y) > (r * r))
    {
        return (velocity, null);
    }
    var just = sphere2.position + r * normalize(check);
    var reflected = (2 * dot(just, L) / dot(L, L)) - just;
    return (length(velocity) * normalize(just), length(velocity) * normalize(reflected));
}

```

*Note*: We can solve the problem `velocity` and `L` are vectors on the same direction by adding a small offset to `velocity`. Dirty, I know.

---

Then to find a velocity direction with no obstacles, we can do a Breadth-first search. If bychecking a velocity vector against the obstacles we get the same vector back always, that is success. Otherwise we got a list of new candidate velocity vectors to check. They should be moving away from the original velocity vector.

If you consider the original velocity vector a node, and the new candidate vectors you get after checking new nodes. You have a tree, and you should do breadth-first search.

If a candidate vector is closer to the original velocity vector than one that has already been discarted, you can discart it too... and to check that, you can compare the dot product of their unit vectors (no need to take `acos`). In fact, work only with unit velocity vectors so you can avoid unnecesary `sqrt`s.

You might think that you need to sort the vectors by their dot product with the original velocity vector. However, that is not true, all you need to take care of is make sure you are doing breadth-first search.

*However, it is useful to sort the obstacles by that criteria.*

If the dot product with any candidate reaches -1, then you searched the whole circunference. You can stop the search. If at that point no candidate is clear from obstacles, then you are surrounded, there is no path.

---

## Old Answer

If I understand correctly, you need to solve this:

That is a triangle with one side `L` being the segment from the center of one sphere to the other, another side `r` is the sum of the radius of the spheres.

We know `L`, and `r`. We know that the triangle has a right angle (because one side is a tangent and another side is a radius). And we want to find `θ`.

---

We are working on a plane, that would be defined by the two centers of the sphere and whatever velocity vector you are using as reference. And we actually want two angles, one is the angle between the reference velocity vector and vector that goes from the first sphere to the second plus `θ`, and the other is the same angle but minus `θ`.

---

We can find `θ` like this:

```
r/sin(θ) = L/sin(τ/4) where τ = one turn
=>
r/sin(θ) = L/1
=>
r/sin(θ) = L
=>
r = L*sin(θ)
=>
r/L = sin(θ)
=>
asin(r/L) = θ

```

---

Then your angles are

```
var referenceAngle = angle(velocity, L);
var angle1 = referenceAngle - θ;
var angle2 = referenceAngle + θ;

```

---

Complete pseudo code:

```
(float angle1, float angle2) getAngles(sphere1, sphere2, velocity)
{
    var L = sphere2.position - sphere1.position;
    var r = sphere1.radius + sphere2.radius;
    var θ = asin(r/L);
    var referenceAngle = angle(velocity, L);
    return (referenceAngle - θ, referenceAngle + θ);
}

```

If you only want to check if the velocity is out of the range, then:

```
bool isOutOfRange(sphere1, sphere2, velocity)
{
    var L = sphere2.position - sphere1.position;
    var r = sphere1.radius + sphere2.radius;
    var θ = asin(r/L);
    return angle(velocity, L) > θ;
}

```

---

Sure, you can use table lookup for the trigonometry if that is a problem.
> 2 votes

# Answer
Not a complete answer, but this might help.

The slowest parts of your code are the `Mathf.Sin`, `Mathf.Cos` and `Mathf.Acos` commands.They are usually evaluated by libraries at runtime using mathematical series and are accurate to last bit of float. (up to 1.5 * 10^(-45)) That is way to much precision required just for a game.

I suggest substituting them with a look up tables of precalculated values for each degree, decydegree or centydegree depending on how much memory you can spare. You can also make it more precise, but much more complited by using a nonuniform partition.

Having such tables you can ether simply use the nearest value from the table, or if more precision is required use linear interpolation between each two rows in the look up table. Both algorithms will be much faster then using a series, and if you experiment with table sizes the imperfection will be unnoticeable.

This should dramatically increase performance.

I used similar technique to quickly calculate Sqrt when I needed to calculate gravity between 300 simulated planets in real time at 60 fps.
> 1 votes

---
Tags: unity, 2d, mathematics, movement, performance
---


# Question
Title: Unity how do I play an intro only the first time the player starts the game?
I have an intro animation scene in my game that I want to play the first time the player hits play from the main menu. How do I do this?

# Answer
I've never done this, and I'm not familiar with Unity, but here's how I'd do it.

You could use the PlayerPrefs to implement that feature. When your player hits "Play", start first by checking if they have a preference saved. If they have, skip the intro, if not, save the preference and play the intro.

```
if ( PlayerPrefs.HasKey("HasSeenIntro")
{
    // skip to what shows up after they've been show the intro animation
}
else
{
    PlayerPrefs.SetInt("HasSeenIntro", 1);
    // play the intro
}

```

I think until you have a more complex mechanism of saving the game, this should be enough.
> 4 votes

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