# Question
Title: Controlling loop frequency in a Coroutine
I want this coroutine to execute continuously and change the colors. But right now it just waits 1 second at the start and then loops the Coroutine very fast.

So my question is how can I loop the Coroutine every 2 seconds.

```
public class control : MonoBehaviour
{
    public bool gravity = false;
    public bool m_isRunning = false;
    public SpriteRenderer m_spriteRenderer;
    private Rigidbody2D rb;

    private void Update()
    {
        if (gravity)
        {
            rb.gravityScale = 1;
        }

        StartCoroutine("Changecolor", 3f);
    }

    private void Start()
    {
        m_spriteRenderer = this.GetComponent<SpriteRenderer>();
        rb = GetComponent<Rigidbody2D>();
    }

    private IEnumerator Changecolor() <--- this coroutine
    {
        yield return new WaitForSeconds(1);

        int random = Random.Range(1, 4);
        if (random == 1)
        {
            m_spriteRenderer.color = Color.blue;
        }
        else if (random == 2)
        {
            m_spriteRenderer.color = Color.red;
        }
        else if (random == 3)
        {
            m_spriteRenderer.color = Color.green;
        }
        else
        {
            m_spriteRenderer.color = Color.yellow;
        }

        this.StartCoroutine("Changecolor", 3f);
    }

    private void OnMouseDown()
    {
        gravity = true;
    }
}

```

# Answer
You're making the classic mistake of starting a new coroutine every frame in Update.

* So in your first frame you start a coroutine, which waits one second.
* Then in your next frame, you start another coroutine, which waits one second. Meanwhile the first has only 1 second minus 1 frame left to wait.
* In your third frame, you start another coroutine...
* ...
* After one second, your first coroutine finishes waiting, and changes the colour, then itself starts *another* coroutine.
* The very next frame, your second coroutine finishes waiting, changes the colour, and starts *another* coroutine...

So you change the colours every frame after the initial delay, and gradually fill up your memory and frame time with unwanted copies of the coroutine.

You can do all of this much simpler.

```
// Lookup table for colours.
static readonly Color32[] randomColors = new Color32[] {
    new Color32(0, 0, 255, 255),  // Blue
    new Color32(0, 255, 0, 255),  // Green
    new Color32(255, 0, 0, 255),  // Red
    new Color32(255, 255, 0, 0)   // Yellow
}

public bool gravity = false;
public bool m_isRunning = false;
public SpriteRenderer m_spriteRenderer;
private Rigidbody2D rb;

void Start()
{
    m_spriteRenderer = this.GetComponent<SpriteRenderer>();
    rb = GetComponent<Rigidbody2D>();

    // Start the coroutine just once, in Start. Call it directly, not via a string.
    // You can pass your desired loop delay as an argument.
    StartCoroutine(ChangeColor(2f));
}

IEnumerator ChangeColor(float loopDelay) {
    // Loop this one coroutine instance forever.
    while(true) {
        // Select a new random colour from the array.
        int colorIndex = Random.Range(0, 4);
        m_spriteRenderer.color = randomColors[colorIndex];

        // Wait the specified duration before looping again.
        // Move this to the top of the loop if you want a delay before changing colour the first time.
        yield return new WaitForSeconds(loopDelay);
    }
}

void Update() {
    if (gravity) {
        rb.gravityScale = 1;
    }

    // Do not start ever more copies of the coroutine here.
}

```
> 1 votes

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


# Question
Title: 2D active ragdoll/physics-based procedural animation
I'm trying to make a 2D quadraped robot stand and walk via physics.

My robot looks like this. (art is not mine. Source is vapgames)

It's rigged via Unity's 2D animation package and each joint/bone has it's own collider + rigidbody with the legs also having hingejoints connecting the lower part to the upper part and the upper part to the main body of the robot. I've also set up IK for both legs using the 2D IK package with the IK target being attached to their respective leg via fixedjoint and can be moved programmatically to move the legs with respect to IK.

I want it to stand up, as at the moment is just falls and acts as a generic limp ragdoll. I've tried these methods:

* Adding downward force to the legs via the IK targets
* Adding upward force to the torso
* Animating the IK targets to try and get the bot to stand up with animatePhysics enabled.

All of these failed (downard force to legs did pretty much nothing, upward force to torso just made it float if there was no ground, animating the IK targets was too glitchy).

I'm out of ideas on how to actually do this now. I've looked around for guides but there seems to be nothing good (I keep getting this suggested to me but it doesn't help. It's in 3D and the only thing that could help, spider legs, isn't finished and probably never will be)

There's very little information on how to do this sort of stuff and even when I find people who know about active ragdolls they just say add force to the head (for a 3D active ragdoll), which I've already tried (see 2. on the list of what I've already tried) and don't explain anyt further.

If anyone could help, that'd be great!

# Answer
> 0 votes
So, I think I've got a solution that's sufficient for me.

My problem was that the legs wouldn't stay in the right position and trying stuff like AddForce and the other methods I said in the OP wouldn't work.

After a while of searching and asking questions someone asked if I had spring joints, which I didn't. After adding spring joints to my rig and setting it up, it seems I finally have the legs to stay in a desired position while not affecting anything else adversly (such as the effect of gravity with AddForce)

My rig now looks like this. The green lines are the springs so you can see how they're connected and to which part.

# Answer
> 0 votes
Generally rag doll only happens when you actually want the rag doll effect to occur. Most games use a completely separate system for movement. And only swap to rag doll when an explosion or large force is applied.

As for procedural movement you may want to look into springs, joints, and hinges.

---
Tags: unity, physics, ai
---


# Question
Title: How can I simulate a bad internet connection for testing purposes?
I am developing an online multiplayer game. It works well when I test it on the local area network, but before I release it I would like to test how the user-experience works out for someone who has not such a good connection to the server. How can I simulate a bad internet connection with high latency, low bandwidth, jitter and occasional packet loss when in a local environment?

# Answer
> 64 votes
I think Dummynet is what you are looking for. Dummynet is a network emulation tool which can simulate bandwidth limitations, delays, packet losses, and many more. You can easily choose which traffic you want to intercept and configure the limitations, e.g. to limit all incoming TCP traffic to 2Mbit/s you do

```
ipfw add pipe 2 in proto tcp
ipfw pipe 2 config bw 2Mbit/s

```

You see the traffic selection is done by the known ipfw firewall and the pipes provide the limitation features.

It is available for FreeBSD, Linux and Windows.

# Answer
> 35 votes
# Network Link Conditioner

If you're on a Mac, you can use Network Link Conditioner.

You can simulate various cases of bad internet connections, including Edge and 3G.

In addition, you can create your own profiles with your own settings:

It is a free download in Xcode (go to Xcode → Open Developer Tool → More Developer Tools… and download the **Hardware IO Tools for Xcode**).

# Answer
> 15 votes
If you are on linux you can use netem to simulate all of the possible problems with network like high latency, low bandwidth, packet losses and many others.

There is an option for windows called NetLimiter but I haven't used it so can't vouch for it.

Just found a Mac App called SlowlyApp.

# Answer
> 12 votes
Clumsy, for Windows Vista & 7.

# Answer
> 8 votes
> How can I simulate a bad internet connection with high latency, low bandwidth, jitter and occasional packet loss when in a local environment?

If you're on Windows, you can try SoftPerfect Connection Emulator. It's basically a driver that injects itself between your application and the network layer (similar to Wireshark/WinPCAP) for the selected NIC and can simulate limited bandwidth, latency, packet loss, and other things. The UI is simple and straightforward.

It's a commercial product, but the trial lets you do 30-second bursts of "interference" that should be good enough for you to judge whether this tool does what you want.

Another cross-platform option is DummyNet, which behaves in a similar manner (via ipfw) but is a bit less easy-to-use.

> I would like to test how the user-experience works out for someone who has not such a good connection to the server.

I think this part of the question could be restated as "how do I deal with network latency in my application?" One commonly-used and effective technique is Dead Reckoning. The linked article explains it better than I can, but the basic idea is that your clients kind of "simulate" where each entity should be and what it should be doing by an algorithm. Whenever an entity deviates from this algorithm (i.e. player input, server-side event, etc), it sends out an update to each client.

# Answer
> 5 votes
I haven't used it in a while, but I've used Charles for testing this. It is an application with various network diagnostics tools, including simulating the problems you mentioned: "a bad internet connection with high latency, low bandwidth, jitter and occasional packet loss"

# Answer
> 0 votes
If you're savvy with Fiddler, and you're **only** interested in HTTP/1 then you can script this.

Fiddler doesn't support HTTP/2, intercepting with it will cause all HTTP traffic to downgrade to HTTP/1.

---
Tags: networking, testing
---


# Question
Title: Can I linear interpolate color along both the X and Y axis of a circle instead of using the distance formula on each individual point?
I've been unable to make it work and I'm not sure whether it's a problem with my code or if this can even be done. I'm sure there is a way to prove whether it is possible mathematically but I don't know how to approach that either.

I'm trying to do a gradient fill on a circle where the center pixel is **BLUE** and all points on the edge are **RED**. Each point within the circle will be a blend of those two colors based on their distance from the center.

Consider this example:

I already have every point along the edge of the circle which I can draw across to fill it. To do a gradient in the southwest quadrant, I thought that I could linear interpolate between *A-\>B* to form a gradient and then draw a line *C-\>D* starting with **RED** to the color interpolated between *A-\>B*.

Would this be equivalent to using the distance between each point and the origin to linear interpolate the color?

## **UPDATE**

For those interested in seeing what this approximation looks like, I did manage to get it working.

WHITE -\> BLACK

RED -\> BLUE

The grayscale image is misleading because there are 256 shades of **brightness** between pure black and pure white and only 127 between any R, G, and B primary colors in 24-bit RGB.

Here is the red/blue image desaturated and adjusted to emphasize how this approximation is drawing the gradient:

# Answer
**Mathematically, it is not equivalent.**

I want to prefix this by saying; *"but if it works for you, is more performant, and the player won't notice - then by all means still do it. Games are nothing but smoke and mirrors."*

---

The easiest way to check whether this will work or not, is to test a simple linear interpolation on a circle of radius 1.

Here, we can intuitively see that the value in the center will be 0, and the value at the edges will be "1". That is, on this unit circle, the value of any point - will be equal to the distance of that point from the center.

This makes it far easier to reason about; we can now pick any point - and knowing how far from the center it is, we know what the value should be. We can then apply your interpolation method; and if the values match, we know your method is correct.

---

Using the following image:

It's clear that any radius coming from the center of the circle (marked O), must start at distance 0 and interpolate linearly to distance 1. As such, the center of such a radius, would be at a value 0.5 - as marked.

For a radius at 45\*, the same applies. However choosing such an angle makes it far easier to do the following calculations.

It can be seen that the center of this 45\* line, (value 0.5), projects onto the x and y axes, at a certain distance. These are marked A (y-axis) and B (x-axis).

Using your method, if we interpolate on the y-axis from O-\>A and then interpolate from there to B on the x-axis, we should get the same value as the distance calculation.

---

From basic trig, we can calculate the A and B components from the 45\* angle, and the length of the hypotenuse (which is intuitively 0.5):

```
 O->A = 0.5 * cos(45degrees)
      = 1 / (2sqrt(2)))

 O->B = 0.5 * sin(45degrees)
      = 1 / (2sqrt(2)))

```

From this, we can then apply your interpolation method:

Starting at 1/(2sqrt(2)) up the y-axis, we interpolate in the direction of the x-axis, along B units.

The general form of linear interpolation is:

```
value = (1-t)(start) + (t)(end)

```

**Noting that t is not simply 1/(2sqrt(2)), as the x-coordinate of the circle's edge is not simply 1 at this point, but in fact sqrt(7/8).**

As such, to get our parameter (t) into the range 0-\>1, as needed, we need to multiply by the reciprocal of this. Giving t as: t = sqrt(8)/(2\*sqrt(2)\*sqrt(7))

Meaning for this case:

```
value = (1 - t)(OA) + (t)(1)
      = (1 - (sqrt(8)/(2sqrt(2)sqrt(7))))(1/(2sqrt(2)) + (sqrt(8)/(2sqrt(2)sqrt(7)))(1)
      = ((2*sqrt(2)*(sqrt(7)) - (sqrt(8)) + (2*sqrt(2)*sqrt(8)) )/ (8*sqrt(7))
      = approximates to ~0.598

```

Which unfortunately shows that the method you've developed is not a mathematical equivalent. (The value we know should be at this point was 0.5)

---

However!

Like most game dev "tricks", I have to emphasize that if in practice it looks good, and it is more performant than your alternatives (and there's no reason you need to be mathematically accurate, e.g. using it for another mechanic) - **then by all means go ahead.**

There is a difference, but arguably it may not be a significant one. The best thing you can do is generate both, and visually decide if the difference is worth the (potential) performance improvement.

*Also, if this is genuinely a performance bottleneck (i.e. you've measured it), then you may wish to consider alternative techniques such as simply pre-generating the circle as a texture.*

---

*Note: if somebody is good at explaining images in words, for those with accessibility needs - please do edit. I unfortunately couldn't think of any sensible way to describe the most important parts.*
> 1 votes

---
Tags: 2d, graphics-programming, color, rasterization
---


# Question
Title: Controlling a balance wheel using a Unity script
I am working on a small demonstration project with Unity like this (screenshot from footage below).

I don't want to use Unity physics, which is too heavy. I plan to create a rotation function with ratio params for gears. But I am not sure how to control the balance wheel rotation like that video, I tried animation tools which is hard to make the acceleration like real physics.

# Answer
> 0 votes
I find it can be simulated by simple harmonic motion function.

---
Tags: unity, physics
---


# Question
Title: Separate data tables for different item types?
I have two types of items in my game, consumables, and equipment. For my database, should I store them in two different tables, or all in one big items table?

# Answer
If you'll be managing both consumable and non-consumable in essentially the same way, it makes sense to put them in the same table.

This will make the management of the inventory *much easier*, and will let you create feature you do not think about now, such as wearing Arrows (because you have different types of arrows, you must let your user which type of arrows they consume).
> 0 votes

---
Tags: unity, sql
---


# Question
Title: What is the design rationale for having armor and magic penetration mechanics?
It seems to me that the penetration stat found in many games adds needless complexity and often is not easily understood.

It is obvious to a player that if they are taking a lot of damage, then they need to get armor.

An opposing player then has to decide whether or not to get an item to do more damage or an item to do armor penetration.

The answer is often not obvious. The player could look up definitions and statistics on the web and not get a clear answer. They can scour forums and find several different explanations both for and against one or the other.

To me this seems needlessly complex. If more damage can't scale with more armor, then shouldn't damage be buffed or armor be nerfed? Am I missing something obvious?

# Answer
I think there are three aspects of this:

* Meaningful decisions.
* Balance.
* Mechanic complexity.

On the meaningful decisions aspect... well, if the answer to armor is more damage, then that is not a decision. It is good for there to exist multiple ways to deal with a situation. I mean, multiple *different in kind* (not just in raw numbers) ways. Not simply picking the attack with more dps.

If just more damage is always the answer, then deciding what attack to use is NOT interesting. It might aswell be automatic. There might aswell be a single kind of attack (and unique equipment).

Ideally we would have unique mechanics instead of more stats. However, from the point of view of meaningful decision, the option of bypassing armor is valid.

> The answer is often not obvious.

It should not be. From the point of view of balance, if there is one single way that is clearly the best, then the options are not balanced. Au contraire, the use of armor penetration or just more damage should be primordially of preferred game style (and then of tactics and availability).

It also makes sense for there to be ways to counter or avoid armor penetration. It can be something that negates damage, something like evasion (if it makes sense in the game, e.g. turn based tactics) or user agility (if it makes sense in the game, e.g. action rpg), it can be attacking from greater distance, whatever.

> To me this seems needlessly complex.

That goes for the particular case of each game, how exactly was the mechanic implemented and what other mechanics it synergy with. Armor penetration can be straight forward: it does this amount of damage ignoring armor. Done.

It can be complex, if the way to counter armor penetration is with armor that have some sort of resistance to armor penetration… then it isn’t really armor penetration, is it? I mean, designer can come up with odd logic for these mechanics.

If the player has to...

> look up definitions and statistics on the web

... to be able to use it. Then we have a problem of clarity. The mechanics are not clear, not easy to understand. It could be that the mechanics should be reevaluated, or it could be just a matter of better UI (if it is not that bad), in fact if the UI designers or the writers are having trouble explaining the mechanic, the game designers probably should have another look at it.

On the other hand, if the player has to...

> look up definitions and statistics on the web

To decide which is better, despite both using armor penetration and more damage (and hopefully other options) being perfectly viable options and easy to use... we have an optimizer player. It is good to have of those. And it is good to have mechanical depth for them. *There is people who enjoy figuring out that stuff. There is people who take pride in having or using the optimal solution.*

Also, web sites, video explanations, wikis, forums, and other online communities spawning around the game are a good thing.

> If more damage cant scale with more armor, then shouldnt damage be buffed or armor be nerfed?

Buffs and nerfs are often not trivial. You need to consider other mechanics. Is there a mechanic that reduces armor? What about one that deals damage overtime? Are there invulnerability mechanics? etc...

While it is true that developers can create a mess, *perhaps by good old accretion.* That does not mean that armor penetration by itself is a bad design.

*It could be it is a bad idea in whatever game you had in mind when writing the question, it does not mean it is in general.*
> 42 votes

# Answer
**For fun**.

Let's consider the most simple mechanic available: a character has N points of Health, and always does 1 point of Damage per Second. When two characters fight, the one with the most points of Health at the start of the fight wins. Done.

Would this be fun? I, personally, would not find it very fun.

---

In RPG/FPS games where these mechanics come into play, players invest time, and wish for their experience and skill to distinguish them. That is the fun that they are looking for.

In order for experience/skill to matter, the player needs to have meaningful choices at their disposal, which in turn means that the player should be facing a variety of situations and the best choice should differ based on the situation. If the best choice is always the same, there is no meaningful choice to be made, and therefore no way to show off the experience acquired or the player's skill.

In order to create such a variety of situations for the players to enjoy, game creators will therefore create multiple (competing) mechanics such as distinguishing between Health and Armor. Even a rudimentary choice between two attacks High Damage/Reduced by Armor vs Medium Damage/Bypassing Armor will require the player to make a timely choice based on the target: a low-armored target is best dealt with the former, a highly-armored target with the latter... and a medium-armored target will require some experimentation, and thus experience.

As a player, though, I would not agonize over the exact threshold at which one attack is better than the other. If a statistical analysis is required to figure it out, after all, it likely means that the difference is slim enough not to matter that much in practice, and other factors will have more impact.
> 19 votes

# Answer
Games often benefit from having soft counters in them. You might have a situation where you want some people to have good DPS against armored targets, while other people have good DPS against healthy targets, but let people increase their damage or armor penetration in response to whether they feel they need to do better against armored targets or against healthy targets.

The math for armor penetration is, in all but the simplest of cases, going to end up at least one step more complicated than the math for how armor works.

Let's take League of Legends for example:

```
If Armor >= 0: damage multiplier = 100/(100+Armor)

```

So Armor 100 makes you take 50% damage, and Armor 300 makes you take 25% damage. Armor penetration makes you treat the armor as though it were lower, so if you have 50% Armor Penetration, you deal 67% damage to someone with 100 Armor (that's equal in value to +33% damage), and you deal 40% damage to someone with 300 Armor (that's equal in value to +60% damage). It's not that complicated in principle, there aren't that many elements you could take away to simplify it, and yet the math needed to determine whether going for +10% Armor Penetration or +15% Damage would be a better deal against each of your five opponents is more than most people can do in the heat of a match.
> 9 votes

# Answer
<sup>\[For this post, whenever the mechanical implementation of attacks is relevant, they are assumed to have a fixed damage component, a random damage component, one or more stat-based components (either multipliers and/or bonuses), and a penetration component (either flat value or percentage). Armour's lower bound is clamped at 0; even with penetration, it can never be negative; it is also capped, with an unspecified upper bound.\]</sup>

Apart from the decision and balance issues, armour penetration is secretly one of the most flexible tools you have as a developer, and can be used as the underlying implementation of a *lot* of seemingly-unrelated mechanics. \[I won't say whether it *should* or not, because that typically depends on the amount of complexity you want, and how much interaction you want there to be between said seemingly-unrelated mechanics. In particular, this becomes less viable if you want different effects to apply their own multipliers, and more viable if you want them to all influence a single, stacking multiplier.\]

For a short list, let's look at...

* Critical hits: Generally, crits increase the damage dealt by an attack. This is usually accomplished by a damage multiplier, but can also be implemented as "ignores \[some/all\] defense"; in particular, "ignores \[some/all\] defense" is a good, logical mechanism for stabbing/piercing weapon crits, on the assumption that you actually *are* poking through one of the little openings in their armour.
* Fixed damage: Fixed damage attacks by definition ignore armour. If you have an armour penetration mechanic, then you can use it to trivially implement a fixed-damage attack: Set the random and stat-based components to zero, and the penetration to maximum (either 100% penetration or equal to the armour cap).
* "Flat-footed" or "Touch AC" mechanics: If familiar with 3.5e or PF, you may be familiar with these; they're both different flavours of armour penetration. \[If not familiar with them, D&D and related games combine your armour and your evasion as your AC (Armor Class, generally equal to 10 plus any relevant bonuses), with 3.5e and Pathfinder in particular having a mechanic that turns off the evasion half (if flat-footed, you don't add your Dex bonus to AC) and one that turns off the armour half (touch AC doesn't include your armour/shield/natural armour bonuses); e.g., if you have +2 Dex, and armour that gives +3 AC, then you have 15 AC normally, 13 AC if flat-footed, and a touch AC of 12.\]

While both of these would need special handling to determine how much of your AC they remove, the amount can just be plugged into your armour penetration mechanic once it's calculated.

+ This can also be used for broader "Bypass Armour" mechanics, which can typically be implemented as "set armour penetration to maximum" unless you need finer-tuned control. \[In cases where you need fine-tuned control, it would likely be because you want to distinguish between different types of armour, in which case it would work similarly to flat-footed vs. touch AC.\]
* Elemental weakness/resistance: In some games, this can be implemented as a weakness multiplier applied to your damage, typically something like 1.5x for weaknesses and 0.75x or 0.5x for resistances. An alternate means of implementing it would be to have weakness and resistance increase and decrease a percentage-multiplier penetration value.

There are likely other effects that could be implemented to rely on armour penetration as well, but none come to mind at the moment. Of course, each of these effects could also be a separate multiplier and/or bonus, representing a distinct step in the damage formula. It all comes down to how you want your game to work, really.
> 3 votes

# Answer
Apart from other reasons it might be dependant on whether the game wishes to simulate a certain (very limited usually) amount of realism. For example, a game I played quite some time ago, (a MUD in fantasy setting), had the armour and melee weapons available to players, which all had base stats and modifiers for different standard damage types: slash/impale/bludgeon.

Therefore a plate mail armour would be quite resistant to slash (slashing swords, axes), also rather resistant to impale (lances and rapiers) and weak against bludgeon - maces, hammers, etc. - damage.

When fighting other players and NPCs it was sometime useful to switch weapons or wear different kinds of armour.

In practice, however, the advantage was frequently nullified by the base stat of the piece, when the modifiers were small.
> 1 votes

# Answer
The easiest example to illustrate that the choice between AP and raw damage is a situation in which there is more than one opponent and the player cannot change the gear option between fighting multiple opponents.

Now the player has a choice. Specialize in defeating the armored opponent, and do less effective damage per attack to the unarmored ones, or specialize in dealing damage to the squishies and do less effective damage per attack to the tanky opponent.

Now regardless of the mathematical complication, or the min/max behavior of the player, or the genre of the game, or many other variables, this decision adds value to the gameplay.
> 1 votes

# Answer
> If more damage cant scale with more armor, then shouldn't damage be buffed or armor be nerfed?

Then there's only one dimension. Every unit can be ranked from better to worse on that scale, and there's no reason to use any but the best unit. One major part of making a game interesting is nontransitivity: Unit A can best Unit B which can beat Unit C which can beat Unit A. One way of doing this is through armor. Unit A has high basic attack and no armor. B has medium basic attack, but high armor penetration. C has high armor and low attack. When A fights B, B has no armor to stop the high attack, and B's penetration is useless since A doesn't have any armor. When B fights C, B's penetration counters C's armor. When C fights A, C's armor stops A's attack.

> To me this seems needlessly complex.

Depends on what you consider "needless". If you want the game to just be about getting the strongest character, then yeah. But if you to have different character types that all have a situation where they're useful, then this sort of thing is needed.

> The player could look up definitions and statistics on the web and not get a clear answer. They can scour forums and find several different explanations both for and against one or the other.

It's not quite clear as to whether you're presenting an issue regarding documentation about the base rules, or availability of higher level strategy. If the effect of armor isn't available in-game, that is an issue of documentation, rather than the mechanism itself. If the rules about what armor and armor penetration are clearly available, but it takes a lot of analysis to decide how useful they are, that's part of playing the game. For instance, if someone's explaining chess, they should mention that bishops move on diagonals and can't jump over pieces, while knights move in L-shapes and can jump over pieces. That's the basic level of the mechanics. There are higher levels, such as "if a bishop starts on a particular color, then it can't move onto the other color", "you can pin pieces with a bishop, but not with a knight", or "it's easier to fork pieces with a knight than with a bishop" that aren't explicitly part of the rules, but are consequences of them, and are part of learning chess strategy. Then there's even higher level facts such as "bishops are generally more valuable than knights" that are going to have a lot of exceptions (this is less true during the opening) that take a lot of mastery to apply, and there's going to be disagreements as to when they apply. If "trading a knight for a bishop is good" were *always* true, then that would take strategic depth away from chess.
> 0 votes

---
Tags: game-design, balance
---


# Question
Title: 'Edit Collider' exits after every adjustment
When I click the *Edit Collider* button I can see the collider's region and the handles to adjust it.

After every adjustment (with the mouse) the collider outline disappears as *Edit Collider* finishes. It's frustrating to use, having to reclick *Edit Collider* after every drag/click.

How do I stop *Edit Collider* mode from exiting after every change and only exit if I click the button, or press some commit key?

# Answer
> 0 votes
When I had an issue like that, it drove me crazy.

It turned out that I had tried to edit the wrong collider.

So, double check that the collider you're clicking on is the collider that you're editing in the Inspector, and not a different instance of the same object, for example.

---
Tags: unity, collider
---


# Question
Title: Help for sorting cars that are 1 lap behind the others (latecomers)
Think of 22 cars running in circuit.

I can sort them based on the order they reach the finish line.

I start to have problems, because over time, the faster cars start to reach the slower cars.

Making the cars slower latecomers/laggards/lapped (blue flag in F1).

**Event (collision car with finish line):**

```
other.position[other.collision]=pilot;
other.lap[other.collision]=timeLap;
other.timeTotal[other.collision]=timeTotal;
other.collision+=1;

if(other.collision>22){
    other.collision=1;
}

```

OBS - The collision event (shown above) is performed on the car. Every variable (other.) Is because it belongs to the finish line.

I use a variable that serves to define which array index will be defined (other.collision).

**Draw Event (Finish Line):**

```
repeat(22){
    draw_text(1280,100+(20*(i-1)),string(position[i]));
    draw_text(1430,100+(20*(i-1)),string(lap[i]));
    draw_text(1530,100+(20*(i-1)),string(timeTotal[i]));
    i+=1;
}

i=1;

```

What happens is that when the first car overcomes the last one, it ends up having the index 22. Becoming the last and vice versa.

I tried to use the time, but the faster car does more turns in less time. Time equals or does not work correctly. So I would also have to use the amount of laps.

That's when I got completely confused.

I am trying to use arrays to order them with the bubble sort, but I didn't get anything functional..

I tried a few more things, but I got lost and I don't even know how to explain it to you.

# Answer
> 0 votes
The other answer gave me the confidence to continue in the code. It is obvious that I needed to correct some things that I had done wrong.

In the code below you will see that I used **counters** (repeat), **arrays** (variable\[\]) and also the principle of the bubble sort algorithm.

**Event (collision car with finish line):**

```
laps+=1;
timeTotal+=timeLap;

other.driver[car]=driver;
other.laps[car]=laps;
other.lastLap[car]=timeLap;
other.timeTotal[car]=timeTotal;

repeat(22){
    i+=1;

    other.ordemDriver[i]=other.driver[i];
    other.ordemLaps[i]=other.laps[i];
    other.ordemLastLap[i]=other.lastLap[i];
    other.ordemTimeTotal[i]=other.timeTotal[i];
}

i=0;

repeat(21){
    repeat(21){
        if(k<23){
            if(other.ordemLaps[j]<other.ordemLaps[k]){
                other.auxOrdemDriver=other.ordemDriver[j];
                other.ordemDriver[j]=other.ordemDriver[k];
                other.ordemDriver[k]=other.auxOrdemDriver;

                other.auxOrdemLaps=other.ordemLaps[j];
                other.ordemLaps[j]=other.ordemLaps[k];
                other.ordemLaps[k]=other.auxOrdemLaps;

                other.auxOrdemLastLap=other.ordemLastLap[j];
                other.ordemLastLap[j]=other.ordemLastLap[k];
                other.ordemLastLap[k]=other.auxOrdemLastLap;

                other.auxOrdemTimeTotal=other.ordemTimeTotal[j];
                other.ordemTimeTotal[j]=other.ordemTimeTotal[k];
                other.ordemTimeTotal[k]=other.auxOrdemTimeTotal;
            }
        }
        k+=1;
    }
    j+=1;
    k=j+1;
}

j=1;
k=2;

repeat(21){
    repeat(21){
        if(k<23){
            if(other.ordemLaps[j]==other.ordemLaps[k]){
                if(other.ordemTimeTotal[j]>other.ordemTimeTotal[k]){
                    other.auxOrdemDriver=other.ordemDriver[j];
                    other.ordemDriver[j]=other.ordemDriver[k];
                    other.ordemDriver[k]=other.auxOrdemDriver;

                    other.auxOrdemLaps=other.ordemLaps[j];
                    other.ordemLaps[j]=other.ordemLaps[k];
                    other.ordemLaps[k]=other.auxOrdemLaps;

                    other.auxOrdemLastLap=other.ordemLastLap[j];
                    other.ordemLastLap[j]=other.ordemLastLap[k];
                    other.ordemLastLap[k]=other.auxOrdemLastLap;

                    other.auxOrdemTimeTotal=other.ordemTimeTotal[j];
                    other.ordemTimeTotal[j]=other.ordemTimeTotal[k];
                    other.ordemTimeTotal[k]=other.auxOrdemTimeTotal;
                }
            }
        }
        k+=1;
    }
    j+=1;
    k=j+1;
}

j=1;
k=2;

```

In some places you can see that I only repeated 21 times, which means once less than the maximum amount of cars.

If there were 15 cars, in those places it would be 14 times.

Note that you will have your own car variable, containing some information (number of laps, lap time, total lap time) and a copy at the finish line. Where you will actually make the comparison and consequently the classification of positions.

Variables that have (other.) are variables that belong to the finish line.

I had to use the amount of laps more the total laps time to get an accurate result.

# Answer
> 3 votes
Add a per car lap counter that increments when they hit the finish line.

That way you can sort the cars by that `lapcount` before you sort those with the same `lapcount` by their position on the track.

To avoid people being able to simply back up and crossing again and again to increment their lap count, you can put invisible checkpoints that all need to be passed in sequence before the lap counter can increment. Which means you have a `nextCheckpoint` per vehicle as well.

---
Tags: game-maker, path, lap
---


title: How to cut a 3D mesh like a lathe?

text:
# Question
Title: How to cut a 3D mesh like a lathe?
How to simulate the object cutting with a lathe, similar to what's done in the CRAFT: Work VR Shop app?

# Answer
> 3 votes
I implemented the effect by doing a virtual lathe. I used Unity for simplicity, but this can be done in pretty much anything. First I had to generate a cylinder:

Instead of simply doing a normal cylinder, I generated a line of points and rotated them around. This way if I change the height of the vertices on that single line, it will affect the whole shape. For instance here's a sine wave:

(I upped the sideways resolution a bit to make it look nicer)

Now let's add a carving tool:

The only thing left to do is to detect when the carving tool gets closer to the object, than the width of it at that point and if it does, remove some of it:

And that's it. It still has some problems you need to fix, e.g.:

* It doesn't do dynamic collision, so if I were to move the carving tool too fast, it would leave strange artifacts
* It's missing dynamic detail. You might not want to spend a lot of rendering time on relatively simple objects

But those should be easy to do (moving the tool only in small increments and checking the distance between vertices every frame respectively).

---
Tags: 3d-meshes, procedural-destruction
---


# Question
Title: Where should I put units and items in a squad-combat ECS-based game?
So I'm working on a game where squads of varied units would explore, fight, trade and build on an overworld map. Combat would be automated more or less, and happen on the overworld. Basically, something like Mount&Blade but without the real-time hack and slash combat.

I'm using an ECS architecture, and even in MVP stages I'm running into confusion: Should each unit be an entity in the grand entity pool, with an ID pointing to the squad it belongs to? Or should they be in an array of units in the squad entity?

When they start having items, should every dagger and boot be part of a gigantic entity pool, or only exist inside units and inventories?

When it'll come to skills and enchantments, buffs... will a "+10% damage" buff float among houses and squads and knives and forests in the entity pool, or will it be part of a buff array?

# If it helps

I'm using Javascript with a homemade ECS, for fast and shareable iterations, and for learning purposes too.

# Answer
> 2 votes
As a general disclaimer and as DMGregory already stated it: The rules of ECS are not written in stone. Doing it on way has benefits, doing it another way has some others. So, you need to know, what either approach does for you.

So, as i don't know your code, i can only theorize what doing it one way would do compared to another. As you should remember, systems only go other components and not necessarily over every single entity you got. And for the most part, entities don't hold values, but as said in the first paragraph, that is not set in stone.

## Units are Entities, Squads are Components

If your entities are units and your squads are some sort of component, then you only iterate over the Units you need for certain actions. If a squad is travelling and nothing happens, you don't need to check for the stats of every single unit of that squad. Also, it would be easier for every single entity to have different equipment.
Negatively is that you got way more entities and it seems that individuals don't really matter except for only a few instances.

## Squads are Entities, Units are Components

If Squads are units, you only have so many components for those to iterate over, except if you got one Unit component for every Unit in that Squad.
Only when individuals are to be requested, it can get complicates as a Unit does not really have a well defined id.

## Squads are Entities,Units are Entities, EVERYONE IS AN ENTITY

Why not both. Squads are Entities that have a Units component with the ID of every single Unit, that are also Entities.
This way you have some more entities, but that's just a slight draw back.

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


# Question
Title: How should I update object movement on Client in a lockstep game?
I have a game that I am implementing a lockstep system for multiplayer on an RTS game. Now the server sends update packets at a higher frequency than the clients with new data.

What I'm stuck on understanding about lockstep systems is how does this tie in with the movement of the units. Should I only move the objects when a new update packet is received?

# Answer
*This answer is under the assumption of an authoritative server.*

> Should I only move the objects when a new update packet is received?

When the user issues an order, the client can start moving the objects, while the order is sent to the server. However, when the update comes from the server, you must synchronize the position to what the server says.

So, no, you are not obligated to only move objects when an update is received. However, that doesn't mean that you have to move objects without an update either. For intance, you have the objects change their animation, and play audio cues that indicate that the client registered the input... and then only move the objects when the update is received.

With that said, for a real time strategy game, you want to relay high level orders. For instance, instead of sending the position of a unit every update, just send its destination. If the client can do the same pathfinding than the server, it will result in the same path, and it is less network traffic.

There might be, of course, instances where the client simulation predicts the update from the server wrong. For example, assuming the client is kept in the dark about the state of whole map (the fog of war exists at network level※), if there is an obstacle that the client is unaware of, the client could pick a different path than the server... well, why would the unit be avoiding an obstacle that it should be unware of? Have the server do pathfinding ignoring anything controlled by other players that is not behind fog of war, so that it picks the path the client would pick.

※: Which is a good thing, because it means that snooping (intercepting) the network communication will not allow to get information of what happens outside of fog of war. And also, it is less network traffic.

*You might be interesting in searching about "client-side prediction", "synced state" and "lag compensation".*
> 1 votes

---
Tags: networking, multiplayer, rts
---


# Question
Title: How do I create a spherical world to explore?
So to preface this question, I have done a lot of research on this, but most of it has proven unhelpful, possibly because I'm not sure the proper way to phrase what it is that I'm trying to ask, so I might make this a little long-winded to get my point across.

The basic idea that I am trying to explore is a small planet that can be navigated by the player, but I also want this planet to be similar, but different for each playthrough (hence the procedural-generation tag). At first, I looked into doing this by simply creating a sphere which has it's own type of gravity (doesn't have to be too realistic), but research proved that this had many (too many) obstacles to overcome. Making the gravity work on this sphere would have been complicated, but doable, but then I read that the terrain tools wouldn't work properly and that could be a problem. The last issue that I saw for this, which makes me think that this idea is dead is how strenuous this might be for the systems, since I want the planet to be fairly full of interesting things to explore.

This led me to the idea of a modular system of tiles (if I'm using that term correctly), where I could procedurally generate these tiles, and align them in a spherical shape. I could instantiate and destroy the tiles as needed to preserve system resources, and would make the procedural generation aspect of this easier for me as well (at least I think it will). The problem I see with this model is how to make square (or any other shaped tiles) form a sphere.

I am attempting to build this in UE4. If this is impossible, or at least prohibitively difficult, to do in the engine, then I rather find out now before I get too far along in the project. And any help or resources on how I can do this if possible will be greatly appreciated.

# Answer
I haven't touched UE4 in a while but I'm gonna tell you how I'd tackle it. I would create 3D fractional brownian motion (fbm is iterative octaves of the 3D noise) and add it to the equation of a sphere, I would do it in a vertex shader. Here is something similar I wrote in a pixel shader, note that the noise here is 2D which could be troublesome in your case, but the algorithm is similar:

```
float map( vec3 p )
{

    // Equation of a sphere.
    float sphere = length( p + vec3( 0, 150, 0 ) ) - 150.0
    // Fractional Brownian Motion.
    floar f = fbm( p.xz );

    return sphere + f;

}

```

You could even look for texture based noise for speed. Then you would have to run a Marching Cubes implementation to get a mesh or you could even import the mesh from a modeling software and run the fbm to displace the vertexes so that you already have the topology to skip the Marching Cubes. That's if you really need a sphere but you could substitute the sphere equation for a plane and the 3D noise for a 2D one for a 2.5D heightmap, that is much easier to couple with the UE4 terrain system, if I remember correctly it can create terrains from heightmaps.
> 1 votes

---
Tags: procedural-generation, unreal-4, maps, world-design
---


# Question
Title: How to convert a FBX made by blender 2.8 in to a `g3db/g3dj` file?
I've tried to convert a simple cube with libGDX FBX-Converter but the cube is't displaying in my game app.

The FBX file is created by blender 2.8

This is the g3dj file

```
{
    "version": [  0,   1],
    "id": "",
    "meshes": [
        {
            "attributes": ["POSITION", "NORMAL", "TEXCOORD0"],
            "vertices": [
                -1.000000,  1.000000,  1.000000, -1.000000,  0.000000,  0.000000,  0.625000,  0.750000,
                -1.000000, -1.000000, -1.000000, -1.000000,  0.000000,  0.000000,  0.375000,  1.000000,
                -1.000000, -1.000000,  1.000000, -1.000000,  0.000000,  0.000000,  0.625000,  1.000000,
                -1.000000,  1.000000, -1.000000, -1.000000,  0.000000,  0.000000,  0.375000,  0.750000,
                 1.000000,  1.000000,  1.000000,  0.000000,  1.000000,  0.000000,  0.625000,  0.500000,
                -1.000000,  1.000000, -1.000000,  0.000000,  1.000000,  0.000000,  0.375000,  0.750000,
                -1.000000,  1.000000,  1.000000,  0.000000,  1.000000,  0.000000,  0.625000,  0.750000,
                 1.000000,  1.000000, -1.000000,  0.000000,  1.000000,  0.000000,  0.375000,  0.500000,
                 1.000000, -1.000000,  1.000000,  1.000000,  0.000000,  0.000000,  0.625000,  0.250000,
                 1.000000,  1.000000, -1.000000,  1.000000,  0.000000,  0.000000,  0.375000,  0.500000,
                 1.000000,  1.000000,  1.000000,  1.000000,  0.000000,  0.000000,  0.625000,  0.500000,
                 1.000000, -1.000000, -1.000000,  1.000000,  0.000000,  0.000000,  0.375000,  0.250000,
                -1.000000, -1.000000,  1.000000,  0.000000, -1.000000,  0.000000,  0.625000,  0.000000,
                 1.000000, -1.000000, -1.000000,  0.000000, -1.000000,  0.000000,  0.375000,  0.250000,
                 1.000000, -1.000000,  1.000000,  0.000000, -1.000000,  0.000000,  0.625000,  0.250000,
                -1.000000, -1.000000, -1.000000,  0.000000, -1.000000,  0.000000,  0.375000,  0.000000,
                 1.000000, -1.000000, -1.000000,  0.000000,  0.000000, -1.000000,  0.375000,  0.250000,
                -1.000000, -1.000000, -1.000000,  0.000000,  0.000000, -1.000000,  0.125000,  0.250000,
                -1.000000,  1.000000, -1.000000,  0.000000,  0.000000, -1.000000,  0.125000,  0.500000,
                 1.000000,  1.000000, -1.000000,  0.000000,  0.000000, -1.000000,  0.375000,  0.500000,
                -1.000000,  1.000000,  1.000000,  0.000000,  0.000000,  1.000000,  0.875000,  0.500000,
                -1.000000, -1.000000,  1.000000,  0.000000,  0.000000,  1.000000,  0.875000,  0.250000,
                 1.000000,  1.000000,  1.000000,  0.000000,  0.000000,  1.000000,  0.625000,  0.500000,
                 1.000000, -1.000000,  1.000000,  0.000000,  0.000000,  1.000000,  0.625000,  0.250000
            ],
            "parts": [
                {
                    "id": "Cube_part1",
                    "type": "TRIANGLES",
                    "indices": [
                          0,   1,   2,   1,   0,   3,   4,   5,   6,   5,   4,   7,
                          8,   9,  10,   9,   8,  11,  12,  13,  14,  13,  12,  15,
                         16,  17,  18,  16,  18,  19,  20,  21,  22,  22,  21,  23
                    ]
                }
            ]
        }
    ],
    "materials": [
        {
            "id": "green",
            "ambient": [ 0.050876,  0.050876,  0.050876],
            "diffuse": [ 0.018407,  0.800000,  0.000000],
            "emissive": [ 0.018407,  0.800000,  0.000000],
            "opacity":  0.000000,
            "specular": [ 0.018407,  0.800000,  0.000000],
            "shininess":  25.000000
        }
    ],
    "nodes": [
        {
            "id": "Cube",
            "rotation": [-0.707107,  0.000000,  0.000000,  0.707107],
            "scale": [ 10.000000,  10.000000,  10.000000],
            "parts": [
                {
                    "meshpartid": "Cube_part1",
                    "materialid": "green",
                    "uvMapping": [[]]
                }
            ]
        }
    ],
    "animations": []
}

```

This file doesn't display on my game app. On the other hand, if I make an FBX file with blender 2.76 and then convert it to g3dj file it displays successfully.

Any ideas on how to convert an FBX made by blender 2.8 into a `g3db/g3dj` file?

**UPDATE:**

The only difference between the working one vs the not working one is attribute `TEXCOORD0`

heres 2 `g3dj` files, the one made with blender 2.76, and the one made with blender 2.8

**The g3dj file which converted an FBX file made with blender 2.76(the one that works):**

```
{
    "version": [  0,   1],
    "id": "",
    "meshes": [
        {
            "attributes": ["POSITION", "NORMAL"],
            "vertices": [
                -1.000000,  1.000000,  1.000000, -1.000000,  0.000000,  0.000000,
                -1.000000,  1.000000, -1.000000, -1.000000,  0.000000,  0.000000,
                -1.000000, -1.000000,  1.000000, -1.000000,  0.000000,  0.000000,
                -1.000000, -1.000000, -1.000000, -1.000000,  0.000000,  0.000000,
                 1.000000,  1.000000,  1.000000,  0.000000,  1.000000,  0.000000,
                 1.000000,  1.000000, -1.000000,  0.000000,  1.000000,  0.000000,
                -1.000000,  1.000000,  1.000000,  0.000000,  1.000000,  0.000000,
                -1.000000,  1.000000, -1.000000,  0.000000,  1.000000,  0.000000,
                 1.000000, -1.000000,  1.000000,  1.000000,  0.000000,  0.000000,
                 1.000000, -1.000000, -1.000000,  1.000000,  0.000000,  0.000000,
                 1.000000,  1.000000,  1.000000,  1.000000,  0.000000,  0.000000,
                 1.000000,  1.000000, -1.000000,  1.000000,  0.000000,  0.000000,
                -1.000000, -1.000000,  1.000000,  0.000000, -1.000000,  0.000000,
                -1.000000, -1.000000, -1.000000,  0.000000, -1.000000,  0.000000,
                 1.000000, -1.000000,  1.000000,  0.000000, -1.000000,  0.000000,
                 1.000000, -1.000000, -1.000000,  0.000000, -1.000000,  0.000000,
                 1.000000, -1.000000, -1.000000,  0.000000,  0.000000, -1.000000,
                -1.000000, -1.000000, -1.000000,  0.000000,  0.000000, -1.000000,
                 1.000000,  1.000000, -1.000000,  0.000000,  0.000000, -1.000000,
                -1.000000,  1.000000, -1.000000,  0.000000,  0.000000, -1.000000,
                -1.000000,  1.000000,  1.000000,  0.000000,  0.000000,  1.000000,
                 1.000000, -1.000000,  1.000000,  0.000000,  0.000000,  1.000000,
                 1.000000,  1.000000,  1.000000,  0.000000,  0.000000,  1.000000,
                -1.000000, -1.000000,  1.000000,  0.000000,  0.000000,  1.000000
            ],
            "parts": [
                {
                    "id": "Cube.002_part1",
                    "type": "TRIANGLES",
                    "indices": [
                          0,   1,   2,   2,   1,   3,   4,   5,   6,   6,   5,   7,
                          8,   9,  10,  10,   9,  11,  12,  13,  14,  14,  13,  15,
                         16,  17,  18,  17,  19,  18,  20,  21,  22,  21,  20,  23
                    ]
                }
            ]
        }
    ],
    "materials": [
        {
            "id": "Material.005",
            "ambient": [ 0.000000,  0.000000,  0.000000],
            "diffuse": [ 0.800000,  0.800000,  0.800000],
            "emissive": [ 0.800000,  0.800000,  0.800000],
            "opacity":  1.000000,
            "specular": [ 1.000000,  1.000000,  1.000000],
            "shininess":  9.607843
        }
    ],
    "nodes": [
        {
            "id": "Cube",
            "rotation": [-0.707107, -0.000000,  0.000000,  0.707107],
            "scale": [ 1.000000,  1.000000,  0.158538],
            "parts": [
                {
                    "meshpartid": "Cube.002_part1",
                    "materialid": "Material.005"
                }
            ]
        }
    ],
    "animations": []
}

```

**And heres the g3dj file which converted an FBX file made with blender 2.8(the one that DO NOT work):**

```
{
    "version": [  0,   1],
    "id": "",
    "meshes": [
        {
            "attributes": ["POSITION", "NORMAL", "TEXCOORD0"],
            "vertices": [
                -1.000000,  1.000000,  1.000000, -1.000000,  0.000000,  0.000000,  0.625000,  0.750000,
                -1.000000, -1.000000, -1.000000, -1.000000,  0.000000,  0.000000,  0.375000,  1.000000,
                -1.000000, -1.000000,  1.000000, -1.000000,  0.000000,  0.000000,  0.625000,  1.000000,
                -1.000000,  1.000000, -1.000000, -1.000000,  0.000000,  0.000000,  0.375000,  0.750000,
                 1.000000,  1.000000,  1.000000,  0.000000,  1.000000,  0.000000,  0.625000,  0.500000,
                -1.000000,  1.000000, -1.000000,  0.000000,  1.000000,  0.000000,  0.375000,  0.750000,
                -1.000000,  1.000000,  1.000000,  0.000000,  1.000000,  0.000000,  0.625000,  0.750000,
                 1.000000,  1.000000, -1.000000,  0.000000,  1.000000,  0.000000,  0.375000,  0.500000,
                 1.000000, -1.000000,  1.000000,  1.000000,  0.000000,  0.000000,  0.625000,  0.250000,
                 1.000000,  1.000000, -1.000000,  1.000000,  0.000000,  0.000000,  0.375000,  0.500000,
                 1.000000,  1.000000,  1.000000,  1.000000,  0.000000,  0.000000,  0.625000,  0.500000,
                 1.000000, -1.000000, -1.000000,  1.000000,  0.000000,  0.000000,  0.375000,  0.250000,
                -1.000000, -1.000000,  1.000000,  0.000000, -1.000000,  0.000000,  0.625000,  0.000000,
                 1.000000, -1.000000, -1.000000,  0.000000, -1.000000,  0.000000,  0.375000,  0.250000,
                 1.000000, -1.000000,  1.000000,  0.000000, -1.000000,  0.000000,  0.625000,  0.250000,
                -1.000000, -1.000000, -1.000000,  0.000000, -1.000000,  0.000000,  0.375000,  0.000000,
                 1.000000, -1.000000, -1.000000,  0.000000,  0.000000, -1.000000,  0.375000,  0.250000,
                -1.000000, -1.000000, -1.000000,  0.000000,  0.000000, -1.000000,  0.125000,  0.250000,
                -1.000000,  1.000000, -1.000000,  0.000000,  0.000000, -1.000000,  0.125000,  0.500000,
                 1.000000,  1.000000, -1.000000,  0.000000,  0.000000, -1.000000,  0.375000,  0.500000,
                -1.000000,  1.000000,  1.000000,  0.000000,  0.000000,  1.000000,  0.875000,  0.500000,
                -1.000000, -1.000000,  1.000000,  0.000000,  0.000000,  1.000000,  0.875000,  0.250000,
                 1.000000,  1.000000,  1.000000,  0.000000,  0.000000,  1.000000,  0.625000,  0.500000,
                 1.000000, -1.000000,  1.000000,  0.000000,  0.000000,  1.000000,  0.625000,  0.250000
            ],
            "parts": [
                {
                    "id": "Cube.001_part1",
                    "type": "TRIANGLES",
                    "indices": [
                          0,   1,   2,   1,   0,   3,   4,   5,   6,   5,   4,   7,
                          8,   9,  10,   9,   8,  11,  12,  13,  14,  13,  12,  15,
                         16,  17,  18,  16,  18,  19,  20,  21,  22,  22,  21,  23
                    ]
                }
            ]
        }
    ],
    "materials": [
        {
            "id": "Material.002",
            "ambient": [ 0.050876,  0.050876,  0.050876],
            "diffuse": [ 0.800000,  0.800000,  0.800000],
            "emissive": [ 0.800000,  0.800000,  0.800000],
            "opacity":  0.000000,
            "specular": [ 0.800000,  0.800000,  0.800000],
            "shininess":  25.000000
        }
    ],
    "nodes": [
        {
            "id": "Cube",
            "rotation": [-0.707107, -0.000000,  0.000000,  0.707107],
            "scale": [ 1.000000,  1.000000,  0.081716],
            "parts": [
                {
                    "meshpartid": "Cube.001_part1",
                    "materialid": "Material.002",
                    "uvMapping": [[]]
                }
            ]
        }
    ],
    "animations": []
}

```

So is there a way to omit this attribute in blender 2.8? or even better make libgdx take into account this attribute?

# Answer
> 1 votes
Turns out that this is a `materials` problem.

For some reason FBX converter is writing `opacity` to `0.000000` why? I don't know. But for now, a workaround is to change it to `1.000000` in the `g3dj` file under `materials` block

Also, the material color is taken from the `Viewport Display` section `Color` and not from the `Surface` `Color` section of blender.

Note that this is not a `blender 2.8` problem as I believed at first if you change the render engine to cycles in `blender 2.76` FBX converter will write the material with opacity `0.00000` too

This of course is only valid if your using `g3dj` file, if someone has a better solution please do answer, at this point any solution is better than this.

---
Tags: libgdx
---


# Question
Title: How do I detect collisions between a point and a sloped line?
The character in my game constantly falls due to gravity, so i have to detect the collision between the bottom point of the character and the tile slope line on the same x coordinate.

The character must stop just on the slope floor. for that i also need to define where is the slope by storing x, y of both ends of the slope.

In the image bellow, you see a 32x32 tile map, origin of each image is top left.

```
playerPointX = 420;
leftSlopeX = 13*tileSize;
leftSlopeY = 11*tileSize;
rightSlopeX = leftSlopeX+tileSize;
rightSlopeY = leftSlopeY+tileSize;

```

so regarding the awnser i should write this ?

```
float run = playerPointX - leftSlopeX;
float rise = 1 * run;
float collisionHeight = leftSlopeY + rise;

```

and how i can detect the collision against collisionHeight ?

```
if (playerX<collisionHeight) // collision detected

```

or

```
if (playerY>collisionHeight) // collision detected

```

Finally when the collision will be detected should i use y=mx+b for playerY displacement ?

# Answer
> 2 votes
It looks like all you need to do is find how far your character's center is shifted left or right from your line's anchor point, then compute how much your line rises over that interval (or falls, if the product of x offset and slope is negative)

```
float run = character.bottomCenter.x - line.position.x;

float rise = line.slope * run;

float collisionHeight = line.position.y + rise;

```

# Answer
> 0 votes
Well, to answer the letter of your question, a collision between a point and a line would require the point to literally be on the line, and due to floating-point rounding error, you will rarely ever see that in each frame by itself.

To detect a collision that has occurred, you would instead use a technique called sweeping to create a line segment from the point's location in its previous frame, to its coordinate in the current frame. The point of impact would then be trivial, as the intersection between two lines in 2D is simple. Here is an excerpt from Geometric Tools for Computer Graphics by Philip Schnieder and David Eberly (i've added some comments and changed some types for elaboration);

```
//Returns 0 if no intersection
//Returns 1 if there is a unique intersection
//Returns 2 if the lines are "the same" i.e. parallel and/or overlapping
//The variable I is used as output for the point of impact.
//P represents the origin of the line segments
//D is the non-normalized direction vector of the line extending from P
int FindIntersection(Vec2 P0, Vec2 D0, Vec2 P1, Vec2 D1, Vec2 & I, float squareTolerance)
{
  // Use a relative error test to test for parallelism. This effectively
  // is a threshold on the angle between D0 and D1. The threshold
  // parameter ’squareTolerance’ can be defined in this function or be
  // available globally.
  Vec2 E = P1 - P0;
  float kross = D0.x * D1.y - D0.y * D1.x;
  float sqrKross = kross * kross;
  float sqrLen0 = D0.x * D0.x + D0.y * D0.y;
  float sqrLen1 = D1.x * D1.x + D1.y * D1.y;
  if (sqrKross > squareTolerance  * sqrLen0 * sqrLen1) {
    // lines are not parallel
    float s = (E.x * D1.y - E.y * D1.x) / kross;
    I = P0 + s * D0; //I is now the point of impact
    return 1;
  }
  // lines are parallel
  float sqrLenE = E.x * E.x + E.y * E.y;
  kross = E.x * D0.y - E.y * D0.x;
  sqrKross = kross * kross;
  if (sqrKross > squareTolerance * sqrLen0 * sqrLenE) {
    // lines are different
    return 0;
  }
  return 2;
}

```

To answer the spirit of your question I would suggest instead of a point, think of your point a sphere with a very small radius. Now, still following the idea that you want to use a line segment to detect the collision between your point and segment **without** sweep testing, it becomes another trivial geometric problem. Simply find the distance from your point to the line segment, or better yet the *squared* distance, to avoid the square root entirely. Here's another excerpt;

```
float SquaredDistancePointToLineSegment(Vec2 TestPoint, Vec2 SegmentP0, Vec2 SegmentP1)
{
  Vec2 SegmentDirection = SegmentP1 - SegmentP0;

  Vec2 PointMinusP0 = TestPoint - SegmentP0;

  float t = dot(SegmentDirection, PointMinusP0);

  if (t <= 0)
  {
    // P0 is closest to TestPoint
    return dot(PointMinusP0, PointMinusP0);
  }

  float SegmentLengthSquared = dot(SegmentDirection, SegmentDirection);

  if (t >= SegmentLengthSquared)
  {
    // P1 is closest to TestPoint
    Vec2 PointMinusP1 = TestPoint - SegmentP1;
    return dot(PointMinusP1, PointMinusP1);
  }

  // closest Vec2 is interior to segment
  return dot(PointMinusP0, PointMinusP0) - t * t / SegmentLengthSquared;
}

```

Now to see if your small sphere is colliding, simply check if the squared distance is less than the squared radius of your circle.

From the picture you've provided, my gut tells me that a more robust solution would be to think of it as a triangle, rather than a line. Using slopes and such is all well and good, but in my experience, solid polygons tend to be more robust. I highly recommend checking out Randy Gaul's 2D player controller educational github, as he has much to say about this exact question.

If you'd like to see simple triangle point collision detection, I recommend reading Christer Erickson's Realtime Collision Detection as it's a font of knowledge on this subject.

---
Tags: 2d, collision-detection, linear-algebra
---


# Question
Title: Unity, WaitUntil in a self-made message box class
I managed to make a simple message box prefab with a `Text` and a `Button` through `Canvas`, and then instantiate it through the constructor.

```
public class MessageBox
{
    public MessageBox(string msg)
    {
        GameObject obj = (GameObject)MonoBehaviour.Instantiate(Resources.Load(@"MsgBox"));

        obj.GetComponentInChildren<Text>().text = msg;
    }
}

```

So when another script needed it, simply do

```
MessageBox mb = new MessageBox("This is a test message!");

```

This all worked fine, but then I wish to change it to like normal MessageBox where the code was suspended, but not locked, until the user click the OK or Cancel button.

I managed to do it by calling a coroutine **`in the calling script`**.

```
void Start()
{
    StartCoroutine("Do");
}

IEnumerator Do()
{
    MessageBox mb = new MessageBox("This is also a test message!");

    yield return new WaitUntil(() => GlobalVariables.MsgBoxClicked == true);
    //GlobalVariables is a separate class containing some static variables.
    Debug.Log("Done!");
}

```

(You have to set the `MsgBoxClicked` to `false` when the prefab is created and set it to `true` when the button is clicked, of course.)

But that means every time I needed to use the message box, I need to call a coroutine!

And that's super inefficient no matter how you looked at it!

So I tried to move the coroutine into the `MessageBox` class itself.

But now here comes the problem!

The `MessageBox` does NOT inherit from `MonoBehaviour`!

And you can't call a coroutine without it!

I had tried to make the `MessageBox` inherited from `MonoBehaviour`, but the Unity warned me **`This is not allowed`** every time I tried to new it! Even though the game ran smoothly.

I even tried to new the `MonoBehaviour` itself and call its `StartCouroutine`, but of course, the same warning popped up! And this time the game won't even run!

I also tried to use the old `AutoResetEvent`, but it locked the whole thing and crashed my game!

So, could somebody be so kind and teach me how to get around it!?

Much appreciated!

# Answer
Unity doesn’t really support modal dialogs in the way you want, but there are some workaround, like setting the time scale to zero while it’s displayed, and adding a click-blocking later between the message box and everything underneath it.

There are also better ways to wait for the message box to be dismissed than a coroutine, such as a UnityEvent.

That said, if you just want to move your coroutine into the MessageBox class, it should be pretty simple: (warning: untested)

```
public class MessageBox : MonoBehaviour
{
    private System.Action onDismiss;
    public static void ShowMessage(string msg, System.Action onDismiss)
    {
        GameObject obj = (GameObject)Instantiate(Resources.Load("MsgBox"));

        obj.GetComponentInChildren<Text>().text = msg;
        MessageBox msg = obj.AddComponent<MessageBox>(); //or this component could be added to the prefab in the inspector.
        msg.onDismiss = onDismiss;
    }

    void Start()
    {
        StartCoroutine("Do");
    }

    IEnumerator Do()
    {
        yield return new WaitUntil(() => GlobalVariables.MsgBoxClicked);
        //GlobalVariables is a separate class containing some static variables.
        if (onDismiss != null)
            onDismiss();
    }
}

```

And then the code that wants to show the message can simply use

```
MessageBox.ShowMessage("This is a test message!", () => {
    Debug.Log("Done!");
});

```

Basically, MonoBehaviour objects can’t exist on their own. They are components that must be attached to a GameObject, which is what the call to AddComponent is doing.
> 1 votes

---
Tags: unity, coroutines, monobehaviour
---


title: unity update boolean from other script

text:
# Question
Title: unity update boolean from other script
So my problem is that the color of the sprite should only change if the Boolean is true. My theory is that the Boolean isn't being update. So how do I update the Boolean the whole time and see if it is getting changed.

Thanks Guys,

```
 public class controlborder : MonoBehaviour
    {
        private SpriteRenderer m_spriteRenderer;
        public float loopdelay = 2f;
        public static bool startstop;
        public void Start()
        {
            m_spriteRenderer = GetComponent<SpriteRenderer>();
            StartCoroutine(Changecolor(2f));
        }
        public void Update()
        {
        }
        private IEnumerator Changecolor(float loopdelay)
        {
            while (true)
            {
                startstop = control.changecolorborder; <== this bool
                Debug.Log(startstop);

                while (startstop)
                {
                    yield return new WaitForSeconds(1F);
                    int random = Random.Range(1, 4);
                    if (random == 1)
                    {
                        m_spriteRenderer.color = Color.blue;
                    }
                    else if (random == 2)
                    {
                        m_spriteRenderer.color = Color.red;
                    }
                    else if (random == 3)
                    {
                        m_spriteRenderer.color = Color.green;
                    }
                    else
                    {
                        m_spriteRenderer.color = Color.yellow;
                    }

                }
            }
        }
    }

```

# Answer
> 1 votes
I'm not sure about the intent of your code and what 'control' is in this context.

However, I think you are missing a `yield return null;` in the outer `while(true)` loop. Following your current logic, once you set startStop to false, nothing will be able to alter `control.changecolorborder` anymore because your code is stuck in that outer while loop constantly setting startStop to false over and over again...

I'm not sure if this is clear to you, but in case it is not, coroutines are not multi threaded and do not run asynchronously. They are run on the same thread in Unity. With `yield return ...;` you can halt the coroutine so that it can continue executing later (Unity decides how much (frames) later it will continue executing your method depending on what you yielded). Once you yield, your other code (Update, etc.) can run. If you never halt your coroutine (by yield returning something), your other code can't execute as it is still waiting for your coroutine to either finish or yield.

See also: the manual on coroutines.

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


# Question
Title: Will using one class per inventory item create issue on the long term?
I finally managed to plug my menu to my inventory system, display current items, use them etc. But the way I did it... makes me feel dirty.

To cut short, my items are described this way:

```
using System;

public abstract class Item {
    public abstract string Name { get; }
    public abstract string Description { get; }
    public virtual bool IsUsable { get { return false; } }
    public virtual bool IsEquippable { get { return false; } }
    public virtual bool NeedTarget { get { return false; } }
    public virtual void OnUse() { }
}

public class Potion : Item {
    public override string Name { get { return "Potion"; } }
    public override string Description { get { return "Restores 100HP to one character"; } }
    public override bool IsUsable { get { return true; } }
    public override bool NeedTarget { get { return true; } }

    public void OnUse(PlayerCharacter target) {
        Effects.HealTarget(target, 100);
    }

    public override void OnUse() {
        OnUse(GameData.getFirstPc());
    }
}

public class Poison : Item {
    public override string Name { get { return "Poison"; } }
    public override string Description { get { return "Deals 100HP damage to one character"; } }
    public override bool IsUsable { get { return true; } }
    public override bool NeedTarget { get { return true; } }

    public void OnUse(PlayerCharacter target) {
        Effects.DamageTarget(target, 50);
    }

    public override void OnUse() {
        OnUse(GameData.getFirstPc());
    }
}

```

My Inventory is declared like this:

```
public class Inventory {
    private static Dictionary<string, Item> ItemDB = new Dictionary<string, Item>() {
        { "00001", new Potion()},
        { "00002", new Poison()},
        { "00003", new HiPotion()},
        { "00004", new FangOfDestroyer()},
        { "00005", new Elixir()}
    };

    public static Dictionary<string, int> CarriedInventory = new Dictionary<string, int>();
}

```

When I want to add items to CarriedInventory I basically call CarriedInventory\[itemID\] = newAmount

Everything only uses the ID, and when I want to get an item's name I call ItemDB\[itemID\].Name, when I want to use an item I call ItemDB\[itemID\].OnUse() , etc

My reasons for doing this were:

* I can be as specific as I want on item uses as I want, I can have unique item effects without having to worry about extending it to all other items
* I can use the effects in the Effects class for general effects (heal, damage, etc)
* if later on I realize I need a new property for an item, I can just add a virtual property as default to the Item class (e.g. I realize I want an item to not be droppable, I add a public virtual bool IsDroppable with a value of true, and non-droppable items can override this
* I avoid inheritance hell

And... it works, it works, but it feels wrong.

Is it wrong? How wrong?

Is there a better way to do it?

# Answer
> 1 votes
There is nothing wrong with how you decided to design the inventory system. Keep in mind though that different decisions are best for different games.

The only problem I can think with your approach, is that this system does not scale that well. What I mean by that is, if during the development of your game you create 100+ items, it will be very difficult to maintain all of them. However if your game has just a handful of different items, you will not run into this problem.

Here's a few improvements I can think, that might work for some games, but not for others:

* To make your items a little bit more versatile, one thing you can do is, instead of making one class for each item, make one class for each item *type*. To use your example, you can use one class called `Potion`, and use that for all potions, regardless of how much they heal. Inside the Constructor of that class, let it take an argument of how much health it heals. So to create a normal potion you would need to do (for example) `new Potion(50)` to make a potion that heals 50 HP, but to make a `HiPotion` you could use `new Potion(100)`, which heals 100 HP.
* Similar to the note above, instead of using raw numbers (like `new Potion(50)` above) you can use a variable to create "Variations" of an item. In the potion example, you could do something like `new Potion(1)`, to create a "level 1" potion, which heals 50HP, and `new Potion(2)` to create a "level 2" potion, which is now called `HiPotion` instead, and heals more HP.

These improvements can create a range of items without duplicating as much code. Think about it this way, `Potion` and `HiPotion` both do the same thing (I assume on your game at least), just with different values, in that case do they really need to duplicate the code of their behaviour? This logic can also be applied for weapons and armor.

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


# Question
Title: Recommended data structure for storage and fast access of infinite chunk-based heightmap terrain
I'm aiming to create a chunk based heightmap terrain in Unity. I already have a basic multifractal simplex noise set up and working, able to generate heightfields and meshes at runtime... but only individually for the moment.

I'm attempting to work out how best to store and access each chunk. I already have a couple of methods worked out to convert global positions to chunk coordinates and chunk-local barycentric triangle coordinates, so I can interpolate heights. I've used that to build a method to march a camera-space-to-world-space ray across the mesh and iterate through x/z-plane intersections until it finds the height-intersection - for a fast way to look up mouse-position on the terrain without having to attach physics collision meshes for each chunk and use Unity's raycasting. That's all working nicely.

I'm just a bit stumped now on how to implement the main infinite-grid storage that I'll generate chunk meshes from.

This is planned to be in service of a game with an isometric perspective, revealing the world as units explore fog-of-war over time... with the ability to move the camera around the uncovered terrain fairly quickly, so I'm guessing there might be limited scope for unloading previously generated chunks... it'll be an ever-expanding dataset (so I'll presumably have to be looking for ways to keep it light on memory)

I figure I can either:

1. Create a 2-dimensional array of float (or perhaps short - 64k height levels should probably be plenty) for the entire terrain, and dynamically resize the array as each x/z boundary is pushed back. Generate just the terrain mesh in chunks, to keep each mesh chunk under the Unity 64k-vertex limit.
2. Create a grid manager class, which has some kind of dynamic data structure that stores map-chunk objects, and instantiates them/retains references to them as they're demanded, each of which would contain its own (res\*res)-sized heightmap array.
3. Something else?

I'm assuming option 2 will have the most mileage, but what I'm most unsure about is what kind of dynamic data structure to use. I'd guess some kind of key/object pair structure, where the key is built from the chunk coordinates?

Assuming I'll want to access height-values quickly and constantly, across chunk-boundaries, for things like my mouse-ray-intersection method, and for pathfinding code, etc... I presume I'll need a way to access chunks that is nearly as fast as looking up arrays by indices, and O(1) complexity. Or perhaps some way of caching recently-accessed chunks or chunks that the camera is near? Or pointers to them, or something?

As you can probably tell I'm fairly new to the gamedev side of things, but I have a VFX background, and so know my way around 3D geometry math and basic scripting. In terms of designing/structuring/implementing a game, I'm a total novice though, so any pointers to relevant tutorials and such would be much appreciated.

# Answer
You could use the class `Dictionary` to store chunks. A C# Dictionary is an association between keys and values with O(1) performance on retrieving values by key. A Dictionary is also a sparse data-structure, which means that it is not necessary for the whole address-space to be filled.

First, create a struct ChunkAddress which represents the unique identifier of a chunk. In your case, a chunk could be identified by its x and z coordinate in the world grid. The address structure should also have a custom implementation of `GetHashCode`, because that method is used internally by Dictionary to convert keys into hashtable entries. I've stolen the implementation from this stackoverflow post. And when you override GetHashCode, you also have to override `Equals`.

So this struct could look like this:

```
public struct ChunkAddress {
     public int x;
     public int z;

     public ChunkAddress(int x, int z) {
         this.x = x;
         this.z = z;
    }

    public override int GetHashCode() {
        unchecked {
            int hash = 17;
            hash = hash * 23 + x;
            hash = hash * 23 + z;
            return hash;
        }
    }
    public override bool Equals(Object obj) {
        if ((obj == null) || ! this.GetType().Equals(obj.GetType())) {
            return false;
        } else {
            ChunkAddress other = (ChunkAddress) obj;
            return (x == other.x) && (z == other.z);
        }
    }
}

```

Now you can declare a dictionary for your chunks like this:

```
Dictionary<ChunkAddress, Chunk> chunks;

```

You can then try to retrieve a chunk with `chunks.TryGetValue(key, out value)`. The boolean return value tells you if that chunk already exists in the dictionary. If it does, it can be found in the second argument you passed to that method. If it doesn't, you have to create that chunk and store it.

If you need the chunk at a grid location, you would use a method like this (untested!):

```
public Chunk GetOrCreateChunkAtGridLocation(int x, int z) {
    Chunk chunk;
    ChunkAddress address = new ChunkAddress(x, z);
    if (chunks.TryGetValue(address, out chunk) {
          // chunk exists in the dictionary
          // the variable "chunk" now references it
    } else {
          // chunk doesn't exist yet, so we have to create it
         chunk = new Chunk();
         /* initialize the chunk */

         // store chunk in the chunks collection so we can
         // retrieve it from memory the next time we need it
         chunks.Add(address, chunk);
   }
   return chunk;
}

```
> 0 votes

# Answer
You will have a limited area of interest around your player, no matter if the world space is infinite, so you should never need more than that number of chunks in *memory*. (For other matters, see below.)

Let's say you had 5x5 chunks, with the player in the middle. For this `range=5`, the `offset`s from player would be:

`-2 -1 0 +1 +2`

For 2 dimensions this would be a 2D array of 5x5=25 chunks; for 3 dimensions this would be a 3D array of 5x5x5=125 chunks. 0 is always the middle (e.g. \[0,0,0\]) where your player is at. Multiple players with their own (overlapping) areas of interest, is something I'll leave to you.

An array accessed by offset like this, is O(1) read access, and is ideal. Obviously, you cannot index an array by negative numbers, so you will need to convert to array index space back (and forth) by adding (or subtracting) `(range - 1) / 2` to `offset`.

A hashmap is amortised O(1) to read - still great. Make a 2D or 3D hashmap from a normal `long`, `int` or even `string` keyed hashmap by splitting the `long`, `int`, or `string` into multiple parts. For example, a `unsigned long` of 64 bits could be used as 21 bits x 3 (for `x`, `y` and `z`) = 63 bits total.

This is *local* space keying. If you want to retrieve chunks by *world* space, the approach to hashmap use is the same, only you'll probably need to serialise and deserialise to and from disk (or, from a large portion of memory - but ultimately that will run out if you don't limit your world size).

If you want to store what has happened in other, previously visited chunks... disk? LocalStorage? a large but finite section of main memory? - your call. But the coordinates system can work the same, while the area of interest array restricts the consumption of main memory to some fixed bound.

Most such applications have the low fat form of the chunk which sits on disk or on the server, and is decompressed once it reaches cache / registers; and the full fat form which can sit in memory (or possibly cache L3), decompressed and ready for instant use.
> 0 votes

# Answer
There is this awesome repo https://github.com/jacksondunstan/NativeCollections which has multiple collection implementations all of which you can find on his blog (there are links in the repo's README, as well as his blog https://jacksondunstan.com/ where he describes all of them and what they are best for). There are more of them (which are not in the readme) so be sure to check out his blog.

I think you could use some of these for your use cases. I did a simular system once and used a 3d array of structs, which was a simple and a valid solution for the scope of the project. It boils down to the scope and what you will be doing the most to the collection.
> -1 votes

---
Tags: unity, terrain, heightmap
---


# Question
Title: Access a clone of an instantiated object - not all the clones?
I am trying to access the object I instantiate - basically a prefab car instantiates cars (one after one) ..the problem that when try to move one .. they all move together ... what's the best way to separate them (and control them one after one)

the game is about parking .. the first car appear i choose which line to move to (target = empty-object) , then the second car appears and i choose which line also to move (the problem is here : when i hit the left/right-row all the cars go left and right .. i want only the last one to change the line )!! Any Ideas ... Thank You:)

this in Spawn.cs

```
public void SpawnCars()
{
    if (spawnAllowed)
    {
        // choose a random strat point 1/6
        randomSpawnPoint = Random.Range(0, spawnPoints.Length);
        // choose a random car 1/6
        randomSpawnCars = Random.Range(0, Cars.Length);
        // clone randomly a car(1/6) from a random pre_set-points(1/6)
        GameObject obj = Instantiate(Cars[randomSpawnCars], spawnPoints[randomSpawnPoint].position, Quaternion.Euler(-90, 180, 0)) as GameObject;
        // carNumber will count how many cloned car
        carNumber++;
        // destroy the  cloned car after N sec
       // Destroy(obj, 8);
        // every cloned car will take a tag with it
        obj.gameObject.tag = "select" + k;
        k++;
        rcf = obj.GetComponent<RayCastForward>();

    }
}

```

this in CarController.cs changing line problem (it change all the cars line)

```
void ChangeLine()
{
     if (Input.GetKeyDown(KeyCode.RightArrow))
    {
        f.RayDis();
        if (f.v != "R6")
            {
                tf.transform.position = new Vector3(tf.position.x,tf.position.y,tf.position.z - 6.5f);
            }
    }
    else if (Input.GetKeyDown(KeyCode.LeftArrow))
    {
        f.RayDis();
        if (f.v != "R1")
            {
                tf.transform.position = new Vector3(tf.position.x, tf.position.y, tf.position.z + 6.5f);
            }
    }

```

the car will move to target after i click the UpRow key

```
// move the car to (target)
public void MoveCars(string go)
{
        target = GameObject.Find(go);
        directionToTarget = (target.transform.position - transform.position).normalized;
        rb.velocity = new Vector3(directionToTarget.x * moveSpeed, directionToTarget.y * moveSpeed, directionToTarget.z * moveSpeed);
}

```

# Answer
It appears like each of your cars has its own CarController component. So every car is controlled separately.

There are several ways to handle this issue:

* When you change your car into the "parked" state, remove its CarController with `Destroy(GetComponent<CarController>())`;
* Disable the CarController with `GetComponent<CarController>().enabled = false;`. When the property `enabled` of a MonoBehaviour is set to false, then the engine will no longer call its `Update` method. This is preferable to destroying the component if you want to have the option to re-enable control of the car or if that component also carries some data or functionality you still need even if the car is parked.
* But maybe your CarController does more than just input handling and also contains code in its Update method which is supposed to be executed for parked cars? In that case you could add a variable `isControlled` to the CarController. Set it to `false` when the car changes into the parked state. Wrap the input handling in `Update` in a `if (isControlled) {` block.
* Separate the CarController from the Car game object it controls. Create an invisible game object in your scene. Give that object a `CarController` script. But modify that script so it doesn't control its own game object. Give it a property `public GameObject controlledCar` representing the car it is currently controlling. When you spawn a new car, change the `controlledCar` of your `carController`.
> 1 votes

# Answer
I found the solution ..

1/ create boolean var:

```
public bool u;

```

2/put the changeline function in if condition:

```
void Update() {
    if (u)
    {
        ChangeLine();
    }

```

3/ and u will be true if i pressed the Up-Row key (UpRow key will tell the car to move to target)

```
 if (Input.GetKeyDown(KeyCode.UpArrow))
    {   u = false;
        moveCar();
    }

```

Thank for your time guys
> 0 votes

---
Tags: unity, c#, gameobject, control
---


title: reseting timer unity

text:
# Question
Title: reseting timer unity
So I have been trying to reset this timer but for some reason I can't figure out why it isn't resetting.

Thanks,

```
public class controlborder : MonoBehaviour
{
    //varibles
    public static int time; //<== here I create my timer
    public static int random;
    public static bool boolreset = true;
    //varibles
    //get objects
    public SpriteRenderer m_spriteRenderer;
    //get objects

    public void Start()
    {
        m_spriteRenderer = this.GetComponent<SpriteRenderer>();
        StartCoroutine(Changecolortimer(2f));
    }

    IEnumerator Changecolortimer(float loopdaelay)
    {
        while (boolreset)
        {
            yield return new WaitForSeconds(1);
            time++; //<== here is set a interval
            if(time == 3)
            {
                boolreset = false;
                resettime();
            }
        }
    }
    public void changeColor()
    {
        if (random == 1 && time == 1)
        {
            m_spriteRenderer.color = Color.blue;
        }
        else if (random == 2 && time == 2)
        {
            m_spriteRenderer.color = Color.red;
        }
        else if (random == 3 && time == 3)
        {
            m_spriteRenderer.color = Color.green;
        }
        else if(random == 4 && time == 4)
        {
            m_spriteRenderer.color = Color.yellow;
        }
    }

    public void Update()
    {
        random = Random.Range(1, 4);
        changeColor();

    }

    public void resettime()
    {
        time += 0;
        boolreset = true;
        Debug.Log(time);
    }
}

```

# Answer
In your resetTime function you are using the "+=" operator, which adds onto the variable's current value, rather than assigning it directly to the specified value. See this example to understand the difference between += and = operators:

```
int x = 1 //declaring int, initial value is 1
x += 5    // this evaluates to "x = x + 5", so x's value is now 6
x = 999   // this evaluates to "x = 999", setting x's value directly to 999

```

In the resetTime() method you are adding 0 to the current value of time, not setting time to 0. Change that line to use the = operator instead of the += operator and you should get the desired behavior.
> 2 votes

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