# Question
Title: How to render many tiles fast if zoomed out? (Monogame/xna)
I'm currently trying to optimize my tile engine. I used monogame with the spritebatch first, but that doesn’t works well. I have read many articles how I could optimize my rendering code.

I moved away from the normal spritebatch and used the vertexbuffer+indexbuffer stuff. Works very well, but not so good as I hoped. I have chunked my tilemap in 50\*50 large chunks and render each with his own vertexbuffer. Additional I check whether the chunk is in view and only render it then. But things are getting very bad if I zoom out.

Let’s say the map is 500\*500 tiles where a tile is 32\*32px tall. Now I must render too many of the chunks to the same time. How can I fix that performance issue here?

I have attached a sample project if some one is interested in it. https://www.dropbox.com/s/2vbkng7ne6ey43e/TileEngineTestXnaMonoWpf.zip

# Answer
> 1 votes
What you are describing is the main obstacle with tile-based game maps. You've got too many triangles being drawn in one call and having them zoomed doesn't help either.

There are several optimizations that can be done to work with a tile-based world.

**LOD (level of detail).**

A simple way to reduce the performance costs of a tile-based world is to draw less tiles. When zooming out you can switch from drawing your small 32x32 tiles to drawing a 64x64 tile that represents the 32x32x4 area. You can do this at discrete zoom distances multiple times.

This technique is quite effective though it can have a very large memory footprint and can be difficult to make look 'pretty'.

Here is a video of a prototype I made a while back that shows off this technique as well as chunk loading (unfinished).

Implementations of LOD vary greatly but the premise is mostly the same.

**Combining Triangles**

Another way to reduce the number of draw calls is to combine the vertices of any large swaths of the map that have the same texture. Think of a quadtree like structure.

Besides these two techniques, you need to ensure you aren't drawing any tiles that aren't visible, as well as making sure you aren't switching textures (use a spritesheet). Also, make sure you aren't drawing in immediate mode.

# Answer
> 0 votes
I'm not sure if this is ever done, and if not, why not. But; I think it would be possible to create a render target for those things in your viewport that are likely static. So your map, for instance, is not likely to change. Because of this you could draw your entire set of map tiles only once in a while (except when your camera moves.)

This would avoid walking all of those vertices, reapplying the texture in a way that matters, etc. You may have to keep a depth buffer floating around whenever you "settle" on a static background.

One can imagine extending this technique to Buildings (even if destructible) and simply only redrawing under the same conditions as the land or if a building has taken sufficient damage to require an update.

---

Aside from that, a few things you may want to check:

* Are all of your effects necessary at this LOD? Consider some effects that simply clip when the depth buffer is sufficiently distant.
* **Are there any if statements in any of your effects**? Don't do that. IIRC you can use a "clip" function to skip that pixel's calculation.
* Are you performing divides? Any divide that is with a constant can be re-imagined as a multiply (and should be.) For example x/100 is also x * 0.01; but performance between those on both GPU and CPU is dramatically different.
* Are you using *floats for everything?* If not, the GPU is highly optimized for floats and not for ints; contrary to CPU programming. Just like in CPU programming you avoid floats/doubles you should be avoiding ints/longs in GPU programming instead.
* Are you calculating things multiple times that don't need to be. The following segment:

float x = pos.x * lit.x * sin(theta) * (1 - 1/pos.y); float y = pos.y * lit.y * sin(theta) * (1 - 1/pos.y);

Can instead be:

```
float mult = sin(theta) * (1 - 1/pos.y);
float x = pos.x * lit.x * mult;
float y = pos.y * lit.y * mult;

```

That's what I got right now with my coffee :), best of luck!

---
Tags: xna, rendering, monogame, performance, tilemap
---


# Question
Title: Cutout fragment shader pixels arent square
It has been solved, link to the final shader: Shader

The problem (as portrayed by the image below) is that the pixels seem to be, for lack of a better word, cut off. I wish to either display a pixel, or not.

My fragment function, it uses the red value of the vertex colors (displayed by the image blow) on the edge of the mesh which are assigned during mesh generation to determine the pixel cutout "weight" by multiplying it with the texture.

```
fixed4 frag (v2f i) : SV_Target
{
    fixed4 tex = tex2D(_MainTex, i.uv);

    if (i.color.r * tex.r > 0.4f) discard;

    return fixed4(tex.rgb * clamp(i.color.r, 0.3f, 1.0f), 1.0f);
}

```

# Answer
> 2 votes
The reason this happens is that your fragment shader doesn't run just once for each texel in your input texture. It runs once for each fragment in your output buffer (eg. each pixel on the screen).

So when you're drawing big, pixelated art zoomed in, you get multiple shader evaluations for each texel in the source. Each of those evaluations gets its own smoothly interpolated input from the vertex shader, like the vertex colours, to give you smooth gradients. That means the fragments at one side of a texel can get different inputs, and come to a different conclusions about whether to draw or clip, than fragments at the other side of the same texel, leading to the cutoff splitting the texel midway along.

To fix this with textures, we use Nearest / Point filtering mode to snap our texture samples to the center of the nearest texel. For interpolated data, we'll need to emulate that snapping behaviour.

First, we need to measure which way the colour gradient is sloping:

```
float2 gradient = float2(ddx(i.color.r), ddy(i.color.r));

```

The `ddx` and `ddy` functions compute screenspace partial derivatives, measuring how much the quantity inside increases as we move a pixel to the right or a pixel up on the screen. This gives us a gradient vector we can use to estimate the function's value at nearby pixels (assuming it's approximately linear, which holds for this case)

Next, we compute where the fragment we're drawing sits relative to the center of this source texel:

```
// Our current position in texel space (eg from 0,0 to 512, 512)
float2 texelPos = i.uv * _MainTex_TexelSize.zw;

// Rounded to the center of the texel
float2 texelCenter = floor(texelPos) + 0.5f;

// Compute the offset from there to here, and convert back to UV space.
float2 delta = (texelCenter - texelPos) * _MainTex_TexelSize.xy;

```

(You'll need to declare the `float4 _MainTex_TexelSize` uniform at the top of your shader, to tell Unity to populate it with the properties of the currently assigned texture)

We're almost there, but one of our vectors is in screenspace and the other is in UV space. So we do a little conversion:

```
float2x2 uvToScreen;
uvToScreen[0] = ddx(i.uv);
uvToScreen[1] = ddy(i.uv);

float2x2 screenToUV = inverse(uvToScreen);

gradient = mul(screenToUV, gradient);

```

Using an inverse function like this one:

```
float2x2 inverse(float2x2 mat) {
    float determinant = mat[0][0] * mat[1][1] - mat[0][1] * mat[1][0];
    float2x2 result = {mat[1][1], -mat[0][1], -mat[1][0], mat[0][0]};
    return result * 1.0f/determinant;
}

```

(I feel like we should be able to skip this inversion step, and instead promote the UV offset up to screenspace, but my brain's in weekend mode and I can't seem to make the math work right)

(If your geometry is always parallel to the image plane, you can compute this matrix per-vertex or even as a uniform, but to handle all perspective cases I've done it per fragment)

Finally, we can measure what the interpolated colour *should* be at the position corresponding to the center of the current texel:

```
float snapped = i.color.r + dot(gradient, delta);

// discard fragments below the given threshold parameter.
clip(snapped * tex.r - _Threshold);

```

Note that this rounding in the shader can sometimes disagree with the rounding done by nearest/point filtering, depending on the rounding formula used in the hardware, so if you find you have tiny lines of texels that should be clipped peeking through, you can use the same snapped coordinate for your texture sample too, to ensure they stay in agreement.

---
Tags: unity, shaders, nvidia
---


# Question
Title: Trying to make pitch black night - some meshes still dimly lit
I have a directional light as a "sun". At night, I need a pitch black scene, but a mesh I'm using as terrain somehow stays faintly lit when the light intensity is 0.

At night:

* The direction light "sun" is rotated so it's beneath my world.
* The sun light is set to black, intensity to 0
* I tried setting fog and ambient light color in RenderSettings to black
* I tried setting ambient intensity to 0

Notice how the background is lighter than the character. Something is causing that light to remain.

**However**, if I enter playmode with the light object inactive, the coloring works fine.

# Answer
After some more debugging it appears to be the "reflectionIntensity" that has to be set to 0. Not sure what's reflecting, but it fixes my issue.
> 0 votes

---
Tags: unity
---


title: Preempting Behavior Trees

text:
# Question
Title: Preempting Behavior Trees
I'm attempting to get my head around behavior trees, so I'm spiking out some test code. One thing I'm struggling with is how to preempt a currently running node when something of higher priority comes along.

Consider the following simple, fictitious behavior tree for a soldier:

Suppose that some number of ticks have gone by and there was no enemy near by, the soldier was standing on grass, so the *Sit down* node is selected for execution:

Now the *Sit down* action takes time to execute because there is an animation to play, so it returns `Running` as its status. A tick or two goes by, the animation is still running, but the *Enemy near?* condition node triggers. Now we need to preempt the *Sit down* node ASAP so we can execute the *Attack* node. Ideally the soldier wouldn't even finish sitting down - he might instead reverse his animation direction if he only just started to sit. For added realism, if he's past some tipping point in the animation, we might instead to choose to let him finish sitting down and then stand again, or perhaps have him stumble in his haste to react to the threat.

Try as I might, I have not been able to find guidance on how to handle this kind of situation. All the literature and videos I've consumed over the past few days (and it's been a lot) seem to skirt around this issue. The closest thing I've been able to find has been this concept of resetting running nodes, but that doesn't give nodes like *Sit down* a chance to say "hey, I've not finished yet!"

I thought of perhaps defining a `Preempt()` or `Interrupt()` method on my base `Node` class. Different nodes can handle it how they see fit, but in this case we'd attempt to get the soldier back on his feet ASAP and then return `Success`. I think this approach would also require that my base `Node` has the concept of conditions separately to other actions. That way, the engine can check conditions only and, if they pass, preempt any currently executing node before starting the execution of the actions. If this differentiation wasn't established, the engine would need to execute nodes indiscriminately and could therefore trigger a new action before preempting the running one.

For reference, below are my current base classes. Again, this is a spike, so I've attempted to keep things as simple as possible and only add complexity when I need it, and when I understand it, which is what I'm struggling with right now.

```
public enum ExecuteResult
{
    // node needs more time to run on next tick
    Running,

    // node completed successfully
    Succeeded,

    // node failed to complete
    Failed
}

public abstract class Node<TAgent>
{
    public abstract ExecuteResult Execute(TimeSpan elapsed, TAgent agent, Blackboard blackboard);
}

public abstract class DecoratorNode<TAgent> : Node<TAgent>
{
    private readonly Node<TAgent> child;

    protected DecoratorNode(Node<TAgent> child)
    {
        this.child = child;
    }

    protected Node<TAgent> Child
    {
        get { return this.child; }
    }
}

public abstract class CompositeNode<TAgent> : Node<TAgent>
{
    private readonly Node<TAgent>[] children;

    protected CompositeNode(IEnumerable<Node<TAgent>> children)
    {
        this.children = children.ToArray();
    }

    protected Node<TAgent>[] Children
    {
        get { return this.children; }
    }
}

public abstract class ConditionNode<TAgent> : Node<TAgent>
{
    private readonly bool invert;

    protected ConditionNode()
        : this(false)
    {
    }

    protected ConditionNode(bool invert)
    {
        this.invert = invert;
    }

    public sealed override ExecuteResult Execute(TimeSpan elapsed, TAgent agent, Blackboard blackboard)
    {
        var result = this.CheckCondition(agent, blackboard);

        if (this.invert)
        {
            result = !result;
        }

        return result ? ExecuteResult.Succeeded : ExecuteResult.Failed;
    }

    protected abstract bool CheckCondition(TAgent agent, Blackboard blackboard);
}

public abstract class ActionNode<TAgent> : Node<TAgent>
{
}

```

Does anyone have any insight that could steer me in the right direction? Is my thinking along the right lines, or is it as naive as I fear?

# Answer
> 6 votes
I found myself asking same question as you and I had great short conversation in comment section of this blog page where I was provided with another solution of the problem.

First thing is to use concurrent node. Concurrent node is a special type of composite node. It consists of sequence of precondition checks followed by a single action node. It updates all children nodes even if it's action node is in 'running' state. (Unlike sequence node which must start it's update from current running child node.)

Main idea is to create two more return states for action nodes: "cancelling" and "cancelled".

Failure of precondition check in concurrent node is a mechanism which triggers cancelling of it's running action node. If action node does not require long-running cancelling logic then it will return 'cancelled' immediately. Otherwise it switches to 'cancelling' state where you can put all needed logic for correct interruption of the action.

# Answer
> 5 votes
I think your soldier may be decomposited into mind and body (and whatever else). Subsequently, body may be decomposited into legs and hands. Then, every part needs its own behaviour tree, and also public interface — for requests from higher or lower level parts.

So, instead of micro-managing every single action, you just send instant-shot messages like "body, sit down for some time" or "body, run there", and body will manage animations, state transitions, delays and other stuff for you.

Alternatively, body may manage behaviours like this by its own. If it has no orders, it may ask mind "can we sit here?". More interestingly, because of encapsulation, you may easily model features like tiredness or stun.

You may even interchange parts — make elephant with intellect of zombie, add wings to human (he wont even notice), or whatever else.

Without decomposition like this, I bet you are on risk of meeting combinatorial explosion, sooner or later.

Also: http://www.valvesoftware.com/publications/2009/ai\_systems\_of\_l4d\_mike\_booth.pdf

# Answer
> 3 votes
Laying in bed last night, I had something of an epiphany as to how I might go about this without introducing the complexity I was leaning towards in my question. It involves the use of the (poorly named, IMHO) "parallel" composite. Here's what I'm thinking:

Hopefully that's still fairly readable. The important points are:

* the *Sit down*/*Delay*/*Stand up* sequence is a sequence within a parallel sequence (**A**). On every tick, the parallel sequence is also checking the *Enemy near* condition (inverted). If an enemy *is* near, the condition fails and so too does the entire parallel sequence (immediately, even if the child sequence is midway through *Sit down*, *Delay*, or *Stand up*)
* upon failure, the selector **B** above the parallel sequence will jump down into selector **C** to handle the interruption. Importantly, selector **C** would not run if parallel sequence **A** completed successfully
* selector **C** then tries to stand up normally, but can also trigger a stumble animation if the soldier is currently in too awkward a position to simply stand up

I think this will work (am going to try it in my spike soon), despite being a little more messy than I had envisaged. The good thing is that I would eventually be able to encapsulate sub-trees as reusable pieces of logic and refer to them from multiple points. That will alleviate most of my concern there, so I think this is a viable solution.

Of course, I'd still love to hear if anyone has any thoughts on this.

**UPDATE**: although this approach technically works, I've decided it sux. That's because unrelated sub-trees need to "know" about the conditions defined in other portions of the tree so that they can trigger their own demise. Whilst sharing sub-tree references would go some way to alleviating this pain, it's still contrary to what one expects when looking at the behavior tree. Indeed, I made the same mistake twice on a very simple spike.

Therefore, I'm going to go down the other route: explicit support for preempting within the object model, and a special composite that allows a different set of actions to execute when preemption occurs. I'll post a separate answer when I have something working.

# Answer
> 3 votes
Here is the solution I have settled on for now...

* My base `Node` class has an `Interrupt` method which, by default, does nothing
* Conditions are "first class" constructs, in that they are required to return `bool` (thus implying that they are fast to execute and never need more than one update)
* `Node` exposes a collection of conditions separately to its collection of child nodes
* `Node.Execute` executes all conditions first and fails straight away if any condition fails. If conditions succeed (or there are none), it calls `ExecuteCore` so the subclass can do its actual work. There is a parameter that allows skipping of conditions, for reasons you'll see below
* `Node` also allows conditions to be executed in isolation via a `CheckConditions` method. Of course, `Node.Execute` actually just calls `CheckConditions` when it needs to validate conditions
* My `Selector` composite now calls `CheckConditions` for each child it considers for execution. If the conditions fail, it moves straight along to the next child. If they pass, it checks whether there is already an executing child. If so, it calls `Interrupt` and then fails. That's all it can do at this point, in the hopes that the currently running node will respond to the interrupt request, which it can do by...
* I've added an `Interruptible` node, which is kind of a special decorator because it has the regular flow of logic as its decorated child, and then a separate node for interruptions. It executes its regular child to completion or failure as long as it isn't interrupted. If it is interrupted, it immediately switches to executing its interruption handling child node, which could be as complex a sub-tree as required

The end result is something like this, taken from my spike:

The above is the behavior tree for a bee, which collects nectar and returns it to its hive. When it has no nectar and is not near a flower that has some, it wanders:

If this node was not interruptible it would never fail, so the bee would wander perpetually. However, since the parent node is a selector and it has higher priority children, their eligibility for execution is constantly being checked. If their conditions pass, the selector raises an interruption and the sub-tree above immediately switches to the "Interrupted" path, which simply bails ASAP by failing. It could, of course, perform some other actions first, but my spike doesn't really have anything to do other than bail.

To tie this back to my question, though, you could imagine that the "Interrupted" path could attempt to reverse the sitting down animation and, failing that, have the soldier stumble. All this would hold up the transition to the higher priority state, and that's precisely what the goal was.

I *think* I'm happy with this approach - especially the core pieces I outline above - but to be honest, it's raised further questions about the proliferation of specific implementations of conditions and actions, and tying the behavior tree into the animation system. I'm not even sure I can articulate these questions yet, so I'll keep thinking/spiking.

# Answer
> 1 votes
I fixed same issue by inventing "When" decorator. It has a condition and two child behaviors ("then" and "otherwise"). When "When" is executed, it checks condition and depending on its result, runs then/otherwise child. If condition result changes, running child is reset and child corresponding to other branch is started. If child finishes execution, whole "When" finishes execution.

The key point is that unlike initial BT in this question where condition is checked only at the sequence start, my "When" keeps checking condition while it is running. So, the top of the behavior tree is replaced with:

```
When[EnemyNear]
  Then
    AttackSequence
  Otherwise
    When[StandingOnGrass]
      Then
        IdleSequence
      Otherwise
        Hum a tune

```

For more advanced "When" usage, one would also want to introduce "Wait" action that simply does nothing for a specified amount of time or indefinitely (until reset by parent behavior). Also, if you need only one branch of "When", other one can contain either "Success" or "Fail" actions, that respectiveley succeed and fail immediately.

# Answer
> 0 votes
While I'm late, but hope this can help. Mostly because I want to make sure I haven't personally missed something myself as I've been trying to figure this out as well. I've mostly borrowed this idea from `Unreal`, but without making it a `Decorator`, property on a base `Node` or strongly tied with the `Blackboard`, it's more generic.

This will introduce a new node type called `Guard` which is like a combination of a `Decorator`, and `Composite` and has a `condition() -> Result` signature alongside an `update() -> Result`

It has three modes to indicate how cancelation should occur when `Guard` returns `Success` or `Failed`, the actualy canceling depends on the caller. So for a `Selector` calling a `Guard`:

1. Cancel `.self` -\> Only cancel the `Guard` (and its running child) if it is running and the condition was `Failed`
2. Cancel `.lower` -\> Only cancel the lower priority nodes if they are running and the condition was `Success` or `Running`
3. Cancel `.both` -\> Both `.self` and `.lower` depending on the conditions and running nodes. You want to cancel self if its running and would condition to `false` or cancel the running node if they're considered lower priority based on the `Composite` rule (`Selector` in our case) if the condition is `Success`. In other words, it's basically both concepts combined.

Like `Decorator` and unlike `Composite` it only takes a single child.

Although `Guard` only take a single child, you can nest as many `Sequences`, `Selectors` or other types `Nodes` as you want, including other `Guards` or `Decorators`.

`Selector1
 Guard.both[Sequence[EnemyNear?]]
 Sequence1
 MoveToEnemy
 Attack
 Selector2
 Sequence2
 StandingOnGrass?
 Idle
 HumATune`

In the scenario above, whenever `Selector1` updates, it will always run condition checks on the guards associated with its children. In the case above, `Sequence1` is Guarded and needs to be checked before `Selector1` continues with the `running` tasks.

Whenever `Selector2` or `Sequence1` is running as soon as `EnemyNear?` returns `success` during a `Guards` `condition()` check then `Selector1` will issue an interrupt/cancel to the `running` `node` and then continue as usual.

In other words, we can can react to either "idle" or "attack" branch based on a few conditions making the behaviour far more reactive than if we settled on `Parallel`

This also allows you to guard single `Node` that have higher priority against running `Nodes` in the same `Composite`

`Selector1
 Guard.both[Sequence[EnemyNear?]]
 Sequence1
 MoveToEnemy
 Attack
 Selector2
 Guard.both[StandingOnGrass?]
 Idle
 HumATune`

If `HumATune` is a long running `Node`, `Selector2` will always check that one first if it wasn't for the `Guard`. So if the npc got teleported onto a grass patch, next time `Selector2` runs, it will check the `Guard` and cancel `HumATune`in order to run `Idle`

If it gets teleported *out* of the grass patch, it will cancel the running node (`Idle`) and move to `HumATune`

As you see here, the decision making relies on the caller of `Guard` and not the `Guard` itself. The rules of who is considered to be `lower priority` remains with the caller. In both examples, it's the `Selector` who defines what constitutes as a `lower priority`.

If you had a `Composite` called `Random Selector`, then you would get to define the rules within the implementation of that specific `Composite`.

---
Tags: ai, behavior-tree
---


# Question
Title: How can I make tree foliage work with baked lighting?
I have an issue in Unity where my trees are black and it seems to be due to the fact that I'm using baked lighting in my scene. Luckily, it seems that I'm not the only one who's experienced this. I found a post on the unity3d subreddit which goes into more detail about basically the same problem. I'll repost it here for convenience:

> So, I have some custom trees using the "Nature/Tree Soft Occlusion" shaders and they looked great before baking a lightmap. However, now that I have baked the lightmap, the trees have turned black. Or rather, when I tried baking with the trees set to static, they turned invisible, and now that Ive tried without, they're black. Also, they're not casting shadows.
>
> Anyone know how to fix this issue? Perhaps I need to use light probes?
>
> https://i.stack.imgur.com/m6iJP.jpg --\> before and after (fyi the bark is not using the nature/occlusion shader. The shader definitely seems to be the root of the issue, but Im just not sure how to fix it without using a different shader)

Ultimately, the author of this post eventually "solved" his problem by just switching to realtime lighting instead of baked lighting. Unfortunately, this is not an option for me. However, the author did receive some useful comments before giving up.

One of the comments asks if the leaves have properly laid out UVs. The commenter goes on to say that the leaves all need to have their own unique space in the UV grid. I *think* this makes sense because I enabled the `Generate Lightmap UVs` option on my tree model in Unity. But it did nothing. The author apparently also had no luck with that option.

In any case, Maya was suggested (among other software) to check these leaves' UVs. Unfortunately, I've never used Maya and I absolutely can't make heads or tails out of it. I'm just using a borrowed copy from a friend so I've never gone through any tutorials or anything for it. I'm just trying to check this one thing, but I am really at a loss.

EDIT:

According to some comments from DMGregory, he suggests that since trees get spawned and varied dynamically, there's no single mesh to pull apart and check its UVs. His logic seems to make sense, so perhaps Maya is not the solution that I'm looking for. Now, though I'm having trouble with figuring out how to get my tree shaders to work with lightmapping. Details are in the comments.

# Answer
> 0 votes
I went ahead and used mixed lighting instead of baked lighting. The performance is not as high, but it's acceptable for my purposes. I had still had lightmaps enabled on the terrain, but the coloration seemed to be corrected after using mixed lighting on the sun for some reason.

---
Tags: unity, textures, lighting, maya, lightmap
---


# Question
Title: How to set up a key press to start the game
I've tried to create a simple start menu for my game which informs the player to press a key to start the game but the problem is that it works only if the key is pressed all the time...i'm not sure what would be the right way to deal with this. Here is my code:

```
   if (Game.keysPressed[KeyBindings.S]) {

        if (game.livesLeft != 0) {
            game.createEnemies();
            game.update();
            game.draw();
            requestAnimationFrame(game.gameLoop);
        }
        if (game.livesLeft == 0) {
            game.drawLostGame();
        }
    }

```

Basically if the S key is pressed the game works, but when you release the key Game.keysPressed\[KeyBindings.S\] becomes false and the if statement won't be executed anymore, so that's why i need to find a way that by pressing only once the if statement will be executed until the player loses. I've tried with while(true) and similar things but it didn't work. Help would be appreciated! Thanks

# Answer
> 0 votes
You should be setting a bool and then checking that. Something like this should fix it:

```
// in the initialization code
bool gameNotStarted = true;

// all that stuff in between
// [...]

// check if it's time to start the game loop!
if(gameNotStarted)
{
    if (Game.keysPressed[KeyBindings.S] && gameNotStarted) {
        gameNotStarted = false;
    }
}

// specifically not an else statement because it would cause a delay
if(gameNotStarted == false)
{
    if (game.livesLeft != 0) {
        game.createEnemies();
        game.update();
        game.draw();
        requestAnimationFrame(game.gameLoop);
    }
    if (game.livesLeft == 0) {
        game.drawLostGame();
    }
}

```

Your current issue is that each time you want to animate you also check the keyboard; meaning the game will only run while you have the key down. Simply "refactoring" the logic above should fix this issue.

# Answer
> 0 votes
Thanks for answering! In the end i made it work doing something like this:

```
gameLoop() {

    if (game.startGame == 0) {
        game.update();
        game.drawBoardDetails();
        game.drawStartScreen();
        game.startGame = 1;
    }else if (Game.keysPressed[KeyBindings.S]) {
        if (game.livesLeft != 0) {
            game.backgroundAudio();
            game.createEnemies();
            game.update();
            game.draw();
        }
        if (game.livesLeft == 0) {
            game.drawLostGame();
        }
    }else if (Game.keysPressed[KeyBindings.S] == false) {
        Game.keysPressed[KeyBindings.S] = true;
    }
     requestAnimationFrame(game.gameLoop);

}

```

The code is kind of weird but it works fine:))

---
Tags: input, game-loop
---


# Question
Title: In very simple 3d racing games, how are collisions handled?
**I was wondering how collisions in some simple 3d car racing games are done (especially in games like Outrun 2/Motoracer).**

In classic car racing games with complex environment (open world), I guess this is done with a basic box (for the car) to plane collision (for track, buildings an other stuff). The whole thing would be optimized using some bounding boxes (this is the way collision is done in many games).

In a game like Outrun 2/Motoracer, the gameplay is so simple that developers maybe dont need that and everything could have been simplified a lot. For those who never play it, here is what is so specific :

* The car/bike is always glued on the road.
* The road is always same size and have a very simple shape.
* The only possibilities is to follow that road, its not possible to leave the road, or to get in collision with something else (except other cars/bikes but we don't care).
* When you collide with the road, very basic arcade collision is done (the car is simply pushed away from it)

**Here is how i think collision (could) have been done :**

The whole track could be considered as giant a 3d bezier curve. From that curve, the road polygons could be generated (using front, left and up vectors generated from curve). Other elements (like houses, trees, ...) could be also placed and aligned using this method.

Then, to handle the collisions (and draw car) :

1) Find closest position on 3d curve from current car 3d position. In other words, transform 3d car position to bezier curve position. Every 3d position on the road could be considered as a displacement along 3d curve (`t`) + lateral displacement (`d`). Check image below if it is not clear (this is a 2d example but this apply to 3d easily).

> when t = 0 car is at beginning of track section, when t = 1 car is at the end. when d = -1 or 1 car is at border of track, when d = 0 car is in the middle of the road

2) align the car to the road using `t` and `d` (very simple : for any `t` and `d` values i can get a 3d position + up/front/left vectors). the car is now glued on the road

3) check lateral displacement `d` of car. if value is too big `(d > 1)` or to low `(d < -1)` car is away of track. just clip it to put car in correct place.

This also make 3d culling very simple, just draw the track from current car `t` position to `t + some_big_enough_value_to_avoid_visible_clipping`.

**Or maybe i'm completly wrong :** it would have been lot faster and simpler to just check collision of the car (a bounding box) and a very simplified set of polygons that represent the track (without the buildings and such). The 3d world (and the resulting colision model) would have simply been generated before, using some 3rd party tool (no more 3d curve when running the game, just a bunch of polygons).

# Answer
> 16 votes
I have worked on a few commercial games similar to those you describe.

In each of those games, we actually had polygons creating an invisible "wall" along the sides of the track, and did traditional collision testing against those walls. This meant that we could have some additional collidable hazards at the side of the road, inside of the invisible walls, and also let us vary the road width faster than you normally can with a spline approach.

But with that said, we also did what you list in the **how I think collision would work** section in order to guard against collision tunnelling/glitches, and this system was also heavily used for racing AI logic. We also used it for determining which cars were in the lead, so that we could display a "1st/2nd/3rd/etc" indicator on the HUD. Sometimes this data was also used for respawning a car after a major crash.

One piece you missed in **how I think collision would work** is that when you're working with splines like this, you'll normally give the splines *ribs*. Ribs are bits of data expressing how far the track extends sideways in each direction from the spline. So for a spline that's 100 meters long, you might have 50 ribs, giving the track width every two meters along its length. This allows your track to change widths along its extent. In the games I've worked on, these ribs have also distinguished between "track surface" and "drivable area". So you'd have one set of road widths telling how far from the middle of the spline you have nice tarmac, and then another width saying how far the sand/grass/whatever goes outside of that. That let us have players able to drive a reasonable distance off the track, but still have AI know where the real road surface was.

Many games I've worked on have also stored other data in the ribs; one game baked track lighting information into the ribs, for easily calculating whether or not an area was in shadow (which was then used for car rendering, deciding whether or not to draw a lens flare, and other effects). Another baked in information about which cinematic camera placements could see that part of the spline, so we didn't have to do line-of-sight calculations during replays. Still another included information about how many lanes were on the spline, which direction they went, and the horizontal displacement where each lane was located. This allowed us to include traffic cars which could correctly drive within road lanes. Ribs are fantastic for storing any sort of varying data you might need about your road surface.

Ribs are typically stored in an array that's associated with the spline. For speed reasons, a normal implementation will have evenly spaced ribs, so once you know an object's distance along the spline, you can calculate the nearest rib index in the array by dividing the distance along the spline by the distance between ribs. Otherwise you're stuck doing binary searches through your rib array to find the correct road width data.

Your culling description gives a good basic description of how the spline approach can be used, but it's actually a bit more complicated than you suggest -- if you use splines for culling in this way, long hairpin turns often won't draw the opposite side of the turn, since when measured by the distance along the track, the opposite side of the turn can be very far away, even if it's only a few meters away when measured as the crow flies. Additionally, the distances at which world geometry can be seen is typically different than that at which track mesh can be seen, so those don't really fit into this system either. My experience is that in most cases, it's better not to rely on track-following logic for determining whether a model should be drawn; it's much more reliable and causes fewer glitches to use standard camera frustum testing for that.

# Answer
> 0 votes
In my OpenGL racer, I originally started by using two circles to define the borders of the track, but it seemed like too much of a hassle. I just use glReadPixel to read the pixel color. If the players car is over a green (grass colored) pixel, then the movement is further limited. There is very little effect on performance.

---
Tags: 3d, collision-detection, car
---


# Question
Title: Homing missile not following the target and not facing the direction of movement
I have been trying this for two days with no success. I cant figure out where I'm missing the point. All the missiles are moving towards the position of the target but not following it. The position remains fixed and all the newly created missiles come to this point instead of following the target.

Here is the code

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

public class HomingMissile : MonoBehaviour
{
    public Transform target;
    private Rigidbody rb;
    public float rotationSpeed;
    public float speed;

    Quaternion rotateToTarget;
    Vector3 direction;

    private void Start()
    {
        //target = GameObject.FindGameObjectWithTag("Target");
        rb = GetComponent<Rigidbody>();
    }

    private void Update()
{
    //direction = (target.transform.position - transform.position).normalized;
    //float angle = Mathf.Atan2(direction.z, direction.x) * Mathf.Rad2Deg;
    //rotateToTarget = Quaternion.Slerp(transform.rotation, rotateToTarget, Time.deltaTime * rotationSpeed);
    //rb.velocity = new Vector3(direction.x * speed, direction.y * speed, direction.z * speed);

    Vector3 direction = (target.transform.position - transform.position).normalized;
    float angle = Mathf.Atan2(direction.z, direction.x) * Mathf.Rad2Deg;
    Quaternion rotateToTarget = Quaternion.Euler(0, angle, 0);
    transform.rotation = Quaternion.Slerp(transform.rotation, rotateToTarget, Time.deltaTime * rotationSpeed);
    rb.velocity = direction * speed;
}

}

```

I selected the target(transform) using the inspector. I'm using Unity and C# obviously you know that.

What Im trying to achieve is that the missile should follow the position of the target in real time. And i can add the destroy code for the missile myself. **Note :** Please don't tag this as a duplicate. It is not. The game is 2D where Y is always constant. Vertical axis is X and Horizontal axis is X. The objects are 3D. That's why I can't use rigidbody2D.

# Answer
You seem to have a `rotateToTarget` field which isn't doing anything, and you are calculating `angle` and doing nothing with it. Also note that `Mathf.Atan2` accepts arguments in the order (y,x). I'm not sure if x,z is correct or not in your case. You might try swapping them around. Finally, a PSA: You can multiply a vector by a scalar and get a scaled vector. For example, your assignment to `rb.velocity` can be made much simpler.

Maybe something like this?

```
Vector3 direction = (target.transform.position - transform.position).normalized;
float angle = Mathf.Atan2(direction.z, direction.x) * Mathf.Rad2Deg;
Quaternion rotateToTarget = Quaternion.Euler(0, angle, 0);
transform.rotation = Quaternion.Slerp(transform.rotation, rotateToTarget, Time.deltaTime * rotationSpeed);
rb.velocity = direction * speed;

```

Oh, and lastly, I would recommend looking into a different way of animating your rotation. Using `Quaternion.Slerp` is not ideal for this purpose. See this StackOverflow answer explaining why and offering an alternative.
> 2 votes

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


title: Issue with Jumping

text:
# Question
Title: Issue with Jumping
In my game, you have to press (or more accurately release) space bar to jump. However, at seemingly random instances the player wouldn't jump. So it is working fine most of the times but then out of nowhere, the cube doesn't jump even when input is given. Please help!

```
    public float horizontalSpeed = 0.5f;
    Rigidbody rb;
    public float JumpHeight = 10f;
    private bool onGround;
    public float forwardSpeed;
    public float rotSpeed;

    private float increaseJumpBy = 1f;
    private bool increaseJumpHeight;
    private bool jumped = false;

    public SimpleHealthBar healthBar;

    private float Horizontal;
    private float Forward;
    Vector3 forwardMovement;
    Quaternion verRotation;
    Vector3 horizontalmovement;

    public float maxJump;

    // Use this for initialization
    void Start()
    {
        rb = GetComponent<Rigidbody>();
        onGround = true;
        Forward = Time.deltaTime * forwardSpeed;
        forwardMovement = new Vector3(0f, 0f, Forward);
        verRotation = Quaternion.Euler(rotSpeed * Time.deltaTime, 0f, 0f);
    }

    private void FixedUpdate()
    {
        rb.MovePosition(transform.position + forwardMovement);

        Jump();
    }
    // Update is called once per frame
    void Update()
    {
        healthBar.UpdateBar(JumpHeight, maxJump);
    }

    void Jump()
    {
      //Debug.Log("Jumpheight" + JumpHeight);

        if(onGround)
        {

            if (Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.UpArrow))
            {
                if (JumpHeight < maxJump)
                {
                    increaseJumpHeight = true;
                }
            }

            if(JumpHeight>= maxJump)
            {
                JumpHeight = maxJump;
            }

            if (increaseJumpHeight)
            {
                JumpHeight += increaseJumpBy;
            }

            if (Input.GetKeyUp(KeyCode.Space) || Input.GetKeyUp(KeyCode.UpArrow))
            {
                rb.velocity = new Vector3(0f, JumpHeight, 0f);
                onGround = false;
                increaseJumpHeight = false;
                jumped = true;
            }

            if (jumped)
            {
                JumpHeight = 0;
                jumped = false;
            }
        }

        if (!onGround)
        {
            Horizontal = Input.GetAxis("Horizontal");
            horizontalmovement = new Vector3(Horizontal * horizontalSpeed * Time.deltaTime, 0f, 0f);
            rb.MovePosition(transform.position + horizontalmovement + forwardMovement);
            Quaternion horRotation = Quaternion.Euler(0f, 0f, Horizontal * horizontalSpeed * Time.deltaTime);

            rb.MoveRotation(rb.rotation * verRotation /*horRotation*/);
        }
    }
    void OnCollisionEnter(Collision collision)
    {
        onGround = true;
    }
    void OnCollisionExit(Collision col)
    {
        onGround = false;
    }

```

Edit: Removing the bool `jumped` and adding `JumpHeight = 0` to `if(!onGround)` seems to solve the problem

# Answer
> 0 votes
Removing the bool `jumped` and adding `JumpHeight = 0` to `if(!onGround)` seems to solve the problem

# Answer
> 2 votes
Your code for capturing input using `Input.GetKeyDown` should be called from `Update`, not `FixedUpdate`.

It's possible for input events to be missed if it happens between two `FixedUpdate` calls. `FixedUpdate` does not necessarily fire every frame. For example, 2 `Update` calls might fire consecutively before a `FixedUpdate` fires.

(Note that you should still use `FixedUpdate` when dealing with RigidBody, as you have done already.)

---

(For more information, see this discussion on Unity Answers: "Is Input detection ok to do in fixedupdate?" or other similar questions here like this one: Unity Input.GetMouseButtonDown(0) is not working.)

---
Tags: unity, c#, 3d
---


# Question
Title: Problems with Unity3D Animator controller states
I have an object (a simple card) equipped with the Rigidbody, Collider and Animator components. In particular, Animator performs two simple clips: **Cover** and **Uncover** that rotates the card 180 degrees. The first starting from 0 degrees to 180, the second from 180 to 0.

So the clips should cover or uncover the card. The problem is that the card returns to its original state.

For example, the original state of the card is the "uncovered state" so when I click on it to cover it covers as expected. The I register the state "covered" programmatically. However, immediately after the animation ends, it returns to its original state (uncovered). The card now has an internal (C# variable) state as "covered", but I see it to still be uncovered. When I click it again, will be fired the correct animation clip: "uncover".

What should I do to leave it covered at the first click?

I have uploaded here a short clip that shows the behavior of the card, also below find some screenshots that refer to the various views of the IDE that may have useful information. The video clip is uploaded to Dropbox for the while.

The video of the behavior: Dropbox link

The code of the Flip script:

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

public class Flip : MonoBehaviour {

    private Animator anim;
    private enum cs_e {covered, uncovered};
    private cs_e coveringState;

    // Use this for initialization
    void Start () {
        anim = this.GetComponent<Animator>();
        coveringState = cs_e.uncovered;
    }

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

    }

    private void OnMouseUp()
    {
        Debug.Log("Mouse up");

        if (coveringState == cs_e.uncovered)
        {
            anim.Play("Cover");
            coveringState = cs_e.covered;
        } else {
            anim.Play("Uncover");
            coveringState = cs_e.uncovered;
        }

    }

    private void OnMouseDown()
    {
        Debug.Log("Mouse down");
    }

    private void MouseDrag()
    {
        Debug.Log("Mouse drag");
    }
}

```

Some screenshots:

# Answer
Both Cover and Uncover transition into the same Idle state.

So you're saying, "no matter what this card does, it has only one resting state"

But that's not true! It's supposed to have two resting states: one where it's persistently covered, and one where it's persistently uncovered.

Instead your state diagram should look like a loop:

```
 Covered  ------->  Uncovering
    ^                  |
    |                  v
 Covering <-------  Uncovered

```

The transitions from Covered to Uncovering, or from Uncovered to Covering, should be conditional on your covered bool variable, so you can trigger the transition to the opposite side of the loop by setting this variable to the new state you want.
> 2 votes

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


# Question
Title: Update dependent values of Serializable C# classes on Inspector
I have some data types' properties that depend on the input given into other attributes, but I haven't found in the Unity's API an elegant way to update them automagically on the Inspector.

As an example, let's say I have a struct that has a divider value. Since I want to save division computations, I also have on the class a multiplicative inverse value that depends on the divider's, so I'd rather multiply instead of dividing.

Example Code Snippet:

```
[Serializable]
public struct SomeNumbers
{
    [SerializeField] private float divider;
    private float multiplicativeInverse;

    /// When the divider is set, the multiplicative inverse is also set.
    public float Divider
    {
        get { return divider; }
        set
        {
            divider = value;
            multiplicativeInverse = (1f / divider);
        }
    }

    public float MultiplicativeInverse
    {
        get { return multiplicativeInverse; }
        private set { multiplicativeInverse = value; }
    }

    /// Constructor.
    public SomeNumbers(float divider) : this()
    {
        Divider = divider;
    }
}

public class ExampleScript : MonoBehaviour
{
    public float value;
    public SomeNumbers numbers;

    void Update()
    {
        float result = (value * numbers.MultiplicativeInverse); /// Instead of (value / numbers.divider)...
        Debug.Log("Result: " + result.ToString());
    }
}

```

What I'd like, is that each time I change the divider's field, the value under the hood (this case the multiplicative inverse) also gets changed, as if I used the Divider's setter. Since the idea is to have an independent data type, the approach of using OnValidate on a class that contains this struct would not be applicable, since that would be a hard case.

I could also set the Divider's setter on each class at Start/Awake do that for me, but that would be prone to be forgotten. I know about Property Drawers , but I am not sure if that would be the right approach.

I hope the question was clear enough, if not make me know so I correct it. Thanks in advance.

# Answer
You can use a MonoBehaviour or ScriptableObject's OnValidate() method. This gets called in the Editor when a script instance gets (re)loaded or when Inspector properties are changed.

It won't automatically be called on structs nested inside your type, but you can relay it down yourself. Eg...

```
[System.Serializable]
public struct SomeNumbers {

    [SerializeField]
    private float divisor;

    public float Divisor {
         get { return divisor; }
         set {
              divisor = value;
              OnValidate();
          }

    public float multiplicativeInverse { get; private set;}

    public void OnValidate() {
           multiplicativeInverse = 1f/divisor;
    }
}

public class MyBehaviour : MonoBehaviour {
     public SomeNumbers myNumbers;

     void OnValidate() {
          myNumbers.OnValidate();
     }
}

```
> 3 votes

# Answer
In my opinion I these variables should be treated separately. Use your properties methods as just interactor to that one variable alone. Putting logic in them is a bit smelly I think. The setter for the Divider but should only set its self. I would be tempted to use the boolean as a toggle between divide and multiplication and the multiplication value as the value you operate with.

(Do you even need the value if you have a value that can do negative to divide? Could you have a negative value and just do x * value? My brain isn't thinking maths atm so apologies for this jabber.

If this isn't possible then use the value as only positive and your factor and the bool as your operation type. This would eliminate your need for the toggle with value change. If this is something that is needed else where then this should be an interactor function which you call as it is interacting between the two variables. Using the inspector should edit properties seperately. If you have a variable that is effected by the other like time that then works out mph at a speed this should go in a function rather than being effected on a property change.

Sorry if this is a mess, hope helps in some way.
> 2 votes

---
Tags: unity, serialization, editors
---


# Question
Title: How can I make the y extent height also to be random when instantiate new objects?
With the script I instantiate random objects above the terrain. But the random was only on x and z. Now I want the height of the objects to be random as well.

The terrain position is: X = -250, Y = 0, Z = -250.

So I changed the line:

```
var y = Extents.y;

```

To:

```
var y = Random.Range(-Extents.y, Extents.y);

```

But now half of the objects above the terrain and half below the terrain, and I want them all to be above the terrain; thus the random height should be above the terrain.

My full code for reference:

```
using System;
using UnityEngine;
using Random = UnityEngine.Random;

[ExecuteInEditMode]
public class SphereBuilder : MonoBehaviour
{
    // for tracking properties change
    private Vector3 _extents;
    private int _sphereCount;
    private float _sphereSize;

    /// <summary>
    ///     How far to place spheres randomly.
    /// </summary>
    public Vector3 Extents;

    /// <summary>
    ///     How many spheres wanted.
    /// </summary>
    public int SphereCount;

    public float SphereSize;

    private GameObject parent;

    private void Start()
    {
        parent = GameObject.Find("Target Builder");
    }

    private void OnValidate()
    {
        // prevent wrong values to be entered
        Extents = new Vector3(Mathf.Max(0.0f, Extents.x), Mathf.Max(0.0f, Extents.y), Mathf.Max(0.0f, Extents.z));
        SphereCount = Mathf.Max(0, SphereCount);
        SphereSize = Mathf.Max(0.0f, SphereSize);
    }

    private void Reset()
    {
        Extents = new Vector3(250.0f, 20.0f, 250.0f);
        SphereCount = 100;
        SphereSize = 20.0f;
    }

    private void Update()
    {
        UpdateSpheres();
    }

    private void UpdateSpheres()
    {
        if (Extents == _extents && SphereCount == _sphereCount && Mathf.Approximately(SphereSize, _sphereSize))
            return;

        // cleanup
        var spheres = GameObject.FindGameObjectsWithTag("Target");
        foreach (var t in spheres)
        {
            if (Application.isEditor)
            {
                DestroyImmediate(t);
            }
            else
            {
                Destroy(t);
            }
        }

        var withTag = GameObject.FindWithTag("Terrain");
        if (withTag == null)
            throw new InvalidOperationException("Terrain not found");

        for (var i = 0; i < SphereCount; i++)
        {
            var o = GameObject.CreatePrimitive(PrimitiveType.Sphere);
            o.tag = "Target";
            o.transform.localScale = new Vector3(SphereSize, SphereSize, SphereSize);
            o.transform.parent = parent.transform;

            // get random position
            var x = Random.Range(-Extents.x, Extents.x);
            //var y = Extents.y; // sphere altitude relative to terrain below
            var y = Random.Range(-Extents.y, Extents.y);
            var z = Random.Range(-Extents.z, Extents.z);

            // now send a ray down terrain to adjust Y according terrain below
            var height = 10000.0f; // should be higher than highest terrain altitude
            var origin = new Vector3(x, height, z);
            var ray = new Ray(origin, Vector3.down);
            RaycastHit hit;
            var maxDistance = 20000.0f;
            var nameToLayer = LayerMask.NameToLayer("Terrain");
            var layerMask = 1 << nameToLayer;
            if (Physics.Raycast(ray, out hit, maxDistance, layerMask))
            {
                var distance = hit.distance;
                y = height - distance + y; // adjust
            }
            else
            {
                Debug.LogWarning("Terrain not hit, using default height !");
            }

            // place !
            o.transform.position = new Vector3(x, y, z);
        }

        _extents = Extents;
        _sphereCount = SphereCount;
        _sphereSize = SphereSize;
    }
}

```

# Answer
If terrain is at *y = 0*, you can make sure that the random `y` value you need is never smaller than zero by writing it like this:

```
var y = Random.Range(0, 2*Extents.y);

```

Although the range of values will be as wide as the previous ones, if a primitive gets a `y` value of *0* it will be split into two halves by the plane:

That's because the primitive origin is its geometric center. So, if we "push" the primitive upwards enough to let it out of being stuck in the plane, it will be just standing onto it:

If you're using spheres as primitives, and you know their radius is *r*, then you can improve the code like this:

```
var y = Random.Range(r, 2*Extents.y);

```

That means the minimum value will be the radius *r* of the sphere, making the sphere standing on the floor. I guess your radius value is stored by the variable `SphereSize`, so:

```
var y = Random.Range(SphereSize, 2*Extents.y);

```
> 0 votes

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


# Question
Title: How can I change displayed information as a physical control knob is slid along a track
I'm making an installation for exhibition or demonstration purpose.

I want to have a physical handle the viewer can slide along a track. As they do so, the information displayed on the screen should change, to correspond to the segment of the track the handle is currently within. Something like what's shown in this YouTube video:

https://www.youtube.com/watch?v=DOElf77g5yI&feature=youtu.be

How can I achieve this?

# Answer
> 1 votes
Experimental games/game installations with custom controllers often implement them using a gadget called a Makey Makey. (I have no affiliation with the makers of this product)

This is a small circuit board you can plug into a computer by USB. It emulates a keyboard, simulating keypresses when activated in various ways.

By connecting wires to the circuit board, you can fire off these keypresses when an object is touched or a circuit is completed.

To build the kind of track controller you show using this, you'd build a double rail out of a conductive material. The bottom rail would be all one piece, while the top rail would be split into (electrically insulated) segments corresponding to each zone where you want to show different content. Connect each of these rail segments to a different input on the Makey Makey.

Your handle/knob would itself act as a conductor, bridging the two rails in the section it's currently occupying, completing the circuit so the Makey Makey can detect which segment it's in and send a corresponding key press signal.

On the software side, any piece of software that can react to keyboard presses can be used to react to these signals (which casts a wide net! That's why they do it this way, to be compatible with whatever software you're comfortable using) — it could be a slideshow presentation or a webpage, or a very simple game built on an engine or made from scratch.

---
Tags: controllers, hardware, user-interface
---


title: libGDX 3D rendering

text:
# Question
Title: libGDX 3D rendering
I'm currently working on a FPS 3D game using libGDX. I aim to have maze-like levels (like the original Doom and Duke Nukem 3D) so I'm making a level editor with a top-down view and lets you stretch lines (which represent walls) and create sectors. I read that libGDX Models aren't efficient if you plan to have lots of them (I believe that a level could have hundreds of lines). My question: is there an alternative to that? I checked Decals but unfortunately they are not affected by an Environment light. Does anybody have any idea how to improve performance to handle these amount of walls? Should I use BSP-Trees in order to render the walls? Thanks

# Answer
> 2 votes
You may look into https://github.com/libgdx/libgdx/wiki/ModelBuilder%2C-MeshBuilder-and-MeshPartBuilder .

You can construct your level walls using a single model with more than one mesh parts.

Here is some sample code:

```
ModelBuilder worldBuilder = new ModelBuilder();
MeshPartBuilder meshBuilder;
Vector3 corner00 = new Vector3(),
    corner10 = new Vector3(),
    corner11 = new Vector3(),
    corner01 = new Vector3(),
    normal = new Vector3();
modelBuilder.begin();

meshBuilder = worldBuilder.part("room1", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material());
meshBuilder.rect(corner00.set(-10, -10, 0), //room 1, wall 1
                 corner10.set( 10, -10, 0),
                 corner11.set( 10,  10, 0),
                 corner01.set(-10,  10, 0), normal.set(0, 0, 1));
meshBuilder.rect(corner00.set(-10, -10, 10), //room 1, wall 2
                 corner10.set( 10, -10, 10),
                 corner11.set( 10,  10, 10),
                 corner01.set(-10,  10, 10), normal.set(0, 0, -1));

Node node = modelBuilder.node();
node.translation.set(100,0,0); // next room far away
meshBuilder = worldBuilder.part("room2", GL20.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material());
meshBuilder.rect(corner00.set(-10, -10, 0), //room 2, wall 1
                 corner10.set( 10, -10, 0),
                 corner11.set( 10,  10, 0),
                 corner01.set(-10,  10, 0), normal.set(0, 0, 1));
meshBuilder.rect(corner00.set(-10, -10, 10), //room 2, wall 2
                 corner10.set( 10, -10, 10),
                 corner11.set( 10,  10, 10),
                 corner01.set(-10,  10, 10), normal.set(0, 0, -1));

Model worldModel = worldBuilder.end();

```

This way you can use meshBuilder in room localCoordinates, and use the nodes to control room positioning.

You can also disable node by node later on, if you want to do BSP optimization and only draw adjacent rooms.

---
Tags: java, libgdx, 3d, maze, binary-space-partitioning
---


title: Pixel Shader stage did not run

text:
# Question
Title: Pixel Shader stage did not run
I can't figure out why the pixel shader won't run. I'm using the Blinn-Phong per-pixel shader from here. Only change I've made is that I pass an aditional color per vertex which gets multiplied by the light-color in the pixel shader.

So far the Graphics Analyzer shows me a valid IA-result and the same (okay looking) result in the VS-stage. I disabled depth-stencil for testing and though everything looks rather fine I always see "*Stage did not run. No output.*" when I inspect the captured frame.

This is my **Projection**-matrix:

```
_projection = Matrix.PerspectiveFovLH((float) Math.PI / 4.0f, viewports[0].Width / viewports[0].Height,
            0.1f, 100f);

```

Values are *Width*: 1346, *Height*: 800

My **View** is calculated like this:

```
_rotation = Quaternion.RotationYawPitchRoll(Yaw, Pitch, Roll);
Vector3.Transform(ref _target, ref _rotation, out _target);

Vector3 up = Vector3.UnitY;
Vector3.Transform(ref up, ref _rotation, out up);

_view = Matrix.LookAtLH(Position, _target, up);

```

Whereas *Position*: X:50, Y:50, Z:-300, *Target*: X:50, Y:50, Z:0 and *Yaw, Pitch, Roll* are all 0.

**World**-Matrix is currently *Matrix.Identity*.

The **quad** I try to render spans itself from X:0, Y:0 to X:100, Y:100 with *4 vertices* and *6 indices*.

I first thought that *SV\_POSITION* must be a normalized value since it's obviously a SV-coordinate and someone posted in another thread that this solved his problem - but then the VS-stage does not show anything at all and PS still won't run.

It's been quite some years since I last worked with DirectX so I'm not sure anymore why this happens.

# Answer
Your input w values are zeros.

The mathematical principles which projection matrices are based on rely on the input vector w element to be 1.0. The GPU later uses the resulting w element of each position vector to perform the **perspective divide**.

In your case, your projection cannot work (because you input w = 0) and the perspective divide is a divide-by-zero.
> 1 votes

---
Tags: shaders, directx, sharpdx
---


title: how to switch cameras with one button?

text:
# Question
Title: how to switch cameras with one button?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class cameraswitch : MonoBehaviour {
 public Camera cam1;
 public Camera cam2;

void Start () {
    cam1.enabled = true;
    cam2.enabled = false;
    Button Button = gameObject.GetComponent<Button>();
    Button.onClick.AddListener(baz);
}

void baz () {
    cam1.enabled = false;
    cam2.enabled = true;
}
}

```

this is my code . how to switch between the cameras with one button . and Thank You.

# Answer
> 2 votes
If I didn't understand you wrong, inside `baz` function you should do this:

```
cam1.enabled = !cam1.enabled;
cam2.enabled = !cam2.enabled;

```

This way you reverse the previous state of the cameras.

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


# Question
Title: Isometric Map with different Z-axis values
I want to create a isometric tile map editor just like the one shown in the images ( pictures are from the game Zoo Tycoon ). I know how to render the tiles when there is only one Z value ( zero ), but I have no clue how I could archieve something like in the pictures where you can raise certain tiles in 1/2 unit steps, either creating a sharp edge/cliff or a smooth transition.

Can anyone give me some good reference materials or help me out here? Thanks in advance :)

Oh yea and you can also rotate the view by 90 in any direction like this:

**EDIT :**

I am using SFML with C++ for this project. There I am creating an array of vertices, 4 of which represent an quad/tile in the map. In SFML each vertex has two main properties, a position in space and a position in the texture mapped to it. I adjust the first one based on the simple projection formula. The textures are represented in a simple tileset. I simply calculate the corresponding 4 edges of a tile in the texture based on a level data array that contains the number of the tile in the texture, starting from 0.

Here's a very very simple tileset that I made myself

Here's how this looks so far:

Oh yea and this is how far I come with rendering different z values. The 4 tiles on the top right are raised 1 unit. But as you can see the faces of the blocks are incomplete. I don't know how I draw them yet.

**UPDATE :** I managed to display sharp edges correctly now, even though it's really unoptimised (I am drawing every front-facing face of the blocks, even the ones that are covered by others. Any tips on how I can prevent this?)

# Answer
> 2 votes
Sharp edges are easy, you just subtract height times step height from the y coordinate and you're done.

Smooth edges on the other hand are a bit harder. For each tile you have to check the sorrounding 8 tiles and draw the correct step type (256 possibilities with 6 different cases) For instance, having only 1 raised corner tile around creates a tile with only 1 raised corner, 1 raised neighbouring tile makes the current one have a whole edge raised up and having two neighbouring raised tiles on two opposite edged creates a bridge or a saddle type structure.

The easiest solution to this would be to draw a polygon between the 4 corners of the tile and raise these corners separately.

---
Tags: game-mechanics, tilemap, isometric, map-editor
---


# Question
Title: Why when drawing a circle using linerenderer the circle is not complete?
```
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

[RequireComponent(typeof(LineRenderer))]
public class DrawCircle : MonoBehaviour
{
    [Range(0, 50)]
    public int segments = 50;
    [Range(0, 50)]
    public float xradius = 5;
    [Range(0, 50)]
    public float yradius = 5;
    LineRenderer line;

    void Start()
    {
        line = gameObject.GetComponent<LineRenderer>();

        line.positionCount = (segments + 1);
        line.useWorldSpace = false;

    }

    private void Update()
    {
        CreatePoints();
    }

    void CreatePoints()
    {
        float x;
        float y;
        float z;

        float angle = 20f;

        for (int i = 0; i < (segments + 1); i++)
        {
            x = Mathf.Sin(Mathf.Deg2Rad * angle) * xradius;
            z = Mathf.Cos(Mathf.Deg2Rad * angle) * yradius;

            line.SetPosition(i, new Vector3(x, 0, z));

            angle += (360f / segments);
        }
    }
}

```

In the screenshot in the left of the circle there is a gap the circle is not perfect completed.

# Answer
Were I to guess there are two things that jump out at me:

```
float angle = 20f;

```

Notice how this is a different length segment than the rest of the circle, as defined here?:

```
angle += (360f / segments);

```

So your first segment is 20 length and your following segments are 360/50; which is 7.2. That could be enough to make it look a bit funky.

---

Second thing, which compounds the first, is that you're talking to everything in degrees, converting to radians, then adjusting by degrees again. This introduces a lot of possibility for rounding error.

I'd make the following changes:

```
public int segments = 50;
void CreatePoints()
{
    float x;
    float z;

    float change = 2 * Math.Pi / segments;
    float angle = change;

    for (int i = 0; i < (segments + 1); i++)
    {
        x = Mathf.Sin(angle) * xradius;
        z = Mathf.Cos(angle) * yradius;

        line.SetPosition(i, new Vector3(x, 0, z));

        angle += change;
    }
}

```

This is not only going to reduce the possible rounding errors and move a consistent amount each time it loops, but it also gets rid of (in this case) 50 extra divide operations you didn't need, 100 multiplies you didn't need, and you're talking in radians, which is just good practice.

---

An aside for the above: I highly recommend getting used to the Unit Circle and memorizing common values.

---

Update: In the comments it was mentioned that LineSegment.loop needs to be called at the end of the function to connect the beginning to the end.

The above code will still solve the "circle isn't quite circular" problem that would have occurred (I think) and be more efficient than the original code.
> 2 votes

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


title: Shrink a convex polygon

text:
# Question
Title: Shrink a convex polygon
Shrinking a concave polygon is quite hard, to do well. But I expect shrinking a convex polygon would be easy.

The naive approach of moving each vertex a certain distance to the centre gives me poor results though: Notice how for long edges, the displacement is much less than the other shapes.

```
static void shrink_poly( int numcoord, jcv_point* coords )
{
        jcv_point c = {0,0};
        for ( int i=0; i<numcoord; ++i )
        {
                c.x += coords[i].x;
                c.y += coords[i].y;
        }
        c.x = c.x / numcoord;
        c.y = c.y / numcoord;

        const float bordersz = 0.008f;
        for ( int i=0; i<numcoord; ++i )
        {
                float dx = coords[i].x - c.x;
                float dy = coords[i].y - c.y;
                float l = sqrtf( dx*dx+dy*dy );
                float dirx = dx / l;
                float diry = dy / l;
                coords[i].x = c.x + (l-bordersz) * dirx;
                coords[i].y = c.y + (l-bordersz) * diry;
        }
}

```

So for my second approach, I move the edges instead of the vertices, to get even spacing. However, doing this causes the shapes to degenerate: non neighbouring edges start to intersect. I would have to identify these and then collapse the superfluous edge to a new vertex at the intersection point. It also creates concave sections in the polygons, as seen below.

```
static void shrink_poly( int numcoord, jcv_point* coords )
{
        const float bordersz = 0.008f;
        float shiftx[ numcoord ];
        float shifty[ numcoord ];

        for ( int e=0; e<numcoord; e++ )
        {
                const int i=e;
                const int j = (i+1)%numcoord;
                jcv_point& v0 = coords[ i ];
                jcv_point& v1 = coords[ j ];
                float dx = v1.x - v0.x;
                float dy = v1.y - v0.y;
                float nx = -dy;
                float ny =  dx;
                float l = sqrtf( nx*nx + ny*ny );
                nx = nx / l;
                ny = ny / l;
                shiftx[e] = bordersz*nx;
                shifty[e] = bordersz*ny;
        }

        for ( int v=0; v<numcoord; v++ )
        {
                const int e0 = v;
                const int e1 = (v+numcoord-1) % numcoord;
                assert( e0 >= 0  && e0 < numcoord );
                assert( e1 >= 0  && e1 < numcoord );
                coords[ v ].x += shiftx[e0];
                coords[ v ].y += shifty[e0];
                coords[ v ].x += shiftx[e1];
                coords[ v ].y += shifty[e1];
        }
}

```

Is there a simple and effective way for shrinking convex polygons?

# Answer
The easiest solution is to just deal with the lines separately. Define a winding order, let's say polygons go anti-clockwise. Loop through every vertex and subtract it from the next one. Normalize the resulting vector. This should result in unit length vectors pointing in an anti-clockwise direction around the polygon. Now rotate them anti clockwise 90 degrees (a vector can be rotated anti-clockwise by taking the (x, y) coordinates and replacing them with (-y, x)). Take the first point from the line segment you got the vector from and add the result vector to it. You can multiply the vector by a constant amount to get different shrinking amount (higher constants make it shrink faster). Then take this point and the vector and convert them to a line equation using the

```
n.x * x+n.y * y - n.x * P. x - n.y * P. y = 0

```

where n is the vector, P is the point and (x, y) is a variable for every point on the line.

Now you shrunk every line and converted them to a line equation. The next step is to take every 2 neighbouring equations and solving for the point where both of them equal 0. That gives you a vertex. Take every vertex and construct the polygon from it. This results in a constant, uniform shrinkage.
> 1 votes

# Answer
A solution to do this will be:

* enclose the polygon in a circle.
* for each vertex of the polygon, calculate normalized vector:

vi = ( vertex - center of circle ) / radius of circle
* if you change the radius of the circle to be radius', shrinking it, just recalculate vertices:

vi' = center + radius' * vi
> -1 votes

---
Tags: 2d, mathematics, geometry, convex
---


# Question
Title: Create a method and call it from another class
Hi guys I'm having a problem of creating a custom method here's my code

```
public class Board
{
   public Board()
   {}
    public void makeMethod(string history)
    {
    intTmp_Ori = arrPart[0];
        intTmp = 10 * (intTmp_Ori / 100) + 0;

        string tmpPoint = "";
        for (i = 0; i < arrPart.Length; i++)
        {
            if (i == 0)
            {
                if ((int)(arrPart[i] / 100) != TIE)
                {
                    intTmp_F = (int)(intTmp_Ori / 100);
                }
                else
                {
                    intTmp2++;
                    intTmp_F = (int)(intTmp_Ori / 100);
                    bFirstTie = true;
                }
                bNextMove = false;
            }
            else
            {
                if (bFirstTie)
                {
                    if ((int)(arrPart[i] / 100) == TIE)
                    {
                        if (intTmp2 < 6) intTmp2++;
                        bFirstTie = true;
                    }
                    else
                    {
                        intTmp_Ori = (int)(arrPart[i]);
                        intTmp = 10 * (int)(intTmp_Ori / 100) + intTmp2;
                        intTmp_F = (int)(intTmp_Ori / 100);
                        bFirstTie = false;
                    }
                    bNextMove = false;
                }
    }
}

public class StringBuilder
{
    public StringBuilder()
    {}

    public void _StringBuilder(string history, string[] arrPartStr, int[] arrPart, int temp)
    {
        arrPartStr = history.Split(',');

        arrPart = new int[arrPartStr.Length];

        for (int c = 0; c < arrPart.Length; c++)
        {
            int temps = temp;

            if (arrPartStr[c][0] == 'P') temp = 100;
            else if (arrPartStr[c][0] == 'B') temp = 200;
            else temp = 300;
            if (arrPartStr[c][1] == 'P') temp += 10;
            if (arrPartStr[c][2] == 'P') temp += 1;

            arrPart[c] = temp;
        }
    }
}

```

Now what I am going to ask is how can I create that \_StringBuilder Method and call it to the Board class

# Answer
Before you can call a method on your class `StringBuilder`, you first need an instance of it.

The most straight-forward way to do so would be to create one with the `new` keyword and assign it to a variable:

```
StringBuilder builder = new StringBuilder();

```

You can then call methods on that variable:

```
builder._StringBuilder( /* arguments */);

```

By the way, there already is a `StringBuilder` class in the standard library. Depending on your project organization and your imports, the compiler might get confused about which one you mean. When you encounter problems which could be explained by this, try a different name for your class.
> 2 votes

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


title: Does abstraction influence performance?

text:
# Question
Title: Does abstraction influence performance?
Say I have a `GameObject` class that is being extended by all of the objects in the game that are moving around. (This class provides basic stuff like a sprite, draw method, update method with application of move vector and so on...) I also have a class `Asteroid` that like I said extends `GameObject`

Then there are two versions of the game:

**Version 1:** Somewhere in the game there is a Collection that holds all of the `Asteroid`-objects. The update Method is something like this:

```
for(Asteroid a : asteroids)
    a.update(...)

```

Draw method goes equivalent.

**Version 2:** I decided to put all of my `GameObject`s in a single collection, so that all moving stuff is being handled in one single loop like this:

```
for(GameObject o : gameObjects)
    o.update(...)

```

Again, draw method goes equivalent.

The problem I am facing with version 2 is that the game loop basically takes twice as long. (The update method as well as the draw method.) I am astonished at the draw method, since in either version there is the exact same amount of object being drawn. So my question is: **Does this abstraction in version 2 affect the game's performance in any way?** (I can imagine that version 2 requires the JVM to alway cast the `GameObject` implicitly to it's specific type which it does not have to do when the type is already given like in version one, but I am not sure about that.) (I am using Java with LibGDX if it matters)

# Answer
> 5 votes
It looks like you don't really need to ask "Does abstraction influence performance?" - because you did one better: you tested and measured it! "The problem I am facing with version 2 is that the game loop basically takes twice as long. (The update method as well as the draw method)"

So we know something is causing slowness. The question is where exactly it creeps in and why.

1. Indirection

When you have a collection of all one concrete/final type, any method calls like `asteroid.update()` can point directly to the compiled code for that method - or even get automatically inlined in some cases.

When the collection may contain multiple types each with their own different update method, there's an extra step of indirection required: we need to use the type information to look at the appropriate vtable, then use that to point to the appropriate update method code. So there's at least one extra step in every `update()` call.

This is normally a reasonably small hiccup for the flexibility it gives, and you might pay it either way if the `Asteroid` type isn't final, since you might have `IronAsteroid` and `Iceteroid` subtypes with their own update methods. But it sets us up for...
2. Misprediction

Modern CPUs have deep pipelines, so often they don't know the result of some operation until quite a few cycles after they started working on it. If everything that depended on that operation had to wait for the result, they'd slow to a crawl. So instead they have sophisticated features to guess what the result will be and execute chains of instructions on that assumption, then invalidate/roll back only if they guessed wrong.

They're surprisingly good at guessing right, which gives them a tremendous speed-up compared to naive execution. But code patterns that confuse their predictions can throw all that out the window and force them to keep re-doing work due to a wrong guess.

If you're always calling the same method in a loop, those jumps are easy to predict correctly, and the prediction machinery can learn which way that method's branches tend to go, so you rarely guess wrong.

If you're calling multiple different methods in a random mish-mash with no discernible pattern, the predictor is more likely to guess wrong and have to re-do work.
3. Cache Thrashing

If you're always using the same chunk of instructions in `asteroid.update()` over and over, they stay in the processor's innermost cache levels and are very quick to access repeatedly.

If you switch between lots of different `update()` methods, the code for each one needs to get pulled into cache, which might kick out part or all of a different `update()` method, which then needs to be re-fetched from slower cache or main RAM the next cycle.

The same thing can happen with your data. You probably have a loading/generation step somewhere in which you spawn all your asteroids for the level/chunk at once. Those are likely to end up close-together in memory, and iterating over them in order will tend to make good use of the cache. In a collection of mixed types though, which were probably spawned in different times, the memory accesses can jump around almost randomly, so your CPU has to spend more time waiting for data to get pulled in from main RAM.

(Learn more about this under the names of "locality of reference" or "code & data locality")
4. Draw Calls & State Changes

This one's more speculative, since I don't know the details of your draw method. But if it involves setting up any render state like making sure the asteroid's texture and shader are bound, then this can have an impact. Rendering a lot of the same object back-to-back is usually more efficient for the graphics pipeline, making full use of its silicon.

When you draw one asteroid, then a rocket, then a planet, then another asteroid, each with their own shader or texture, the GPU can often draw only one at a time, waiting for the full operation to complete before swapping its rendering state to start on the next one. This leaves a lot of performance on the table and wastes time switching states back and forth.

None of this is to say that object oriented programming abstractions are always awful or slow and that you shouldn't use them. Very often, the flexibility and clarity they offer can make them worthwhile for many developers' working styles, and performance can often be very good. The best thing you can do is exactly what you're doing: write code that makes sense to you, and profile it so you understand its real cost, and can make informed decisions about where to structure things differently.

---
Tags: java, libgdx, performance, inheritance
---


# Question
Title: libgdx strange collision detection behaviour
I am currently developing a small Spaceshooter Clone. The project can be found on github

I am having problems with my very simple collision detection (or better said some behaviour that I can't explain myself.)

I do have lasers and asteroids. (currently all represented by Rectangles) To check for collision I'm using `asteroid.overlaps(laser)`

Basic handling of all my elements is as follows:

* Move all my asteroids to the left
* Check if an asteroid "left the screen" and if so destroy it.
* Move all my lasers to the right
* Check if a laser "left the screen" and if so destroy it.
* If the laser has "not left the screen" I check collision with all asteroids.

asteroids is a Libgdx-Array; lasers is a Libgdx-Array; ship is a Libgdx Rectangle

```
    Iterator<Asteroid> asteroidsIterator = asteroids.iterator();
    while (asteroidsIterator.hasNext()) {
        Asteroid asteroid = asteroidsIterator.next();
        asteroid.x -= 200 * Gdx.graphics.getDeltaTime();
        if (asteroid.x < 0) {
            asteroidsIterator.remove();
        } else if (asteroid.overlaps(ship)) {
            //quitGame();
        }
    }

    Iterator<Rectangle> lasersIterator = lasers.iterator();
    asteroidsIterator = asteroids.iterator(); //<-- it seems that this does not get a fresh iterator
    while (lasersIterator.hasNext()) {
        Rectangle laser = lasersIterator.next();
        laser.x += 600 * Gdx.graphics.getDeltaTime();
        if (laser.x > 800) {
            lasersIterator.remove();
            Gdx.app.log("SC", "Laser exited screen.");
        } else {
            while (asteroidsIterator.hasNext()) {
                Asteroid asteroid = asteroidsIterator.next();
                if (asteroid.overlaps(laser)) {
                    Gdx.app.log("SC", "COLLISION");
                    asteroidsIterator.remove();
                    lasersIterator.remove();
                }
            }
        }
    }

```

When I do single fire everything is ok.

The strange behaviour is:

When I do full-automatic fire then some asteroids are not hit. Only newly created asteroids after begining firing are destroyed and in addition to that they should be very much to the right of the screen.

**EDIT:** After further investigation it seems that the second call to `asteroids.iterator()` does not create a fresh instance. Is there a way to get a fresh/reset Iterator?

# Answer
> 0 votes
I found the problem. The issue was that I did not get a fresh iterator of asteroids for every single laser.

```
Iterator<Rectangle> lasersIterator = lasers.iterator();
    asteroidsIterator = asteroids.iterator(); //<-- this should be done for EVERY laser
    while (lasersIterator.hasNext()) {
        Rectangle laser = lasersIterator.next();
        laser.x += 600 * Gdx.graphics.getDeltaTime();
        if (laser.x > 800) {
            lasersIterator.remove();
            Gdx.app.log("SC", "Laser exited screen.");
        } else {
            while (asteroidsIterator.hasNext()) {
                Asteroid asteroid = asteroidsIterator.next();
                if (asteroid.overlaps(laser)) {
                    Gdx.app.log("SC", "COLLISION");
                    asteroidsIterator.remove();
                    lasersIterator.remove();
                }
            }
        }
    }

```

**SOLUTION**

```
Iterator<Rectangle> lasersIterator = lasers.iterator();
    while (lasersIterator.hasNext()) {
        Rectangle laser = lasersIterator.next();
        laser.x += 600 * Gdx.graphics.getDeltaTime();
        if (laser.x > 800) {
            lasersIterator.remove();
            Gdx.app.log("SC", "Laser exited screen.");
        } else {
            asteroidsIterator = asteroids.iterator();
            while (asteroidsIterator.hasNext()) {
                Asteroid asteroid = asteroidsIterator.next();
                if (asteroid.overlaps(laser)) {
                    Gdx.app.log("SC", "COLLISION");
                    asteroidsIterator.remove();
                    lasersIterator.remove();
                }
            }
        }
    }

```

**of even better**

```
for (Iterator<Rectangle> lasersIterator = lasers.iterator(); lasersIterator.hasNext(); ) {
            Rectangle laser = lasersIterator.next();
            laser.x += debugMode ? 1 : 600 * delta;
            if (laser.x > 800) {
                lasersIterator.remove();
            }
            for (Iterator<Asteroid> asteroidsIterator = asteroids.iterator(); asteroidsIterator.hasNext(); ) {
                Asteroid asteroid = asteroidsIterator.next();
                if (laser.overlaps(asteroid)) {
                    asteroidsIterator.remove();
                    lasersIterator.remove();
                }
            }
        }

```

# Answer
> 0 votes
As you noted, `Array#iterator()` does not create a new iterator when it is called but returns a cached iterator to prevent garbage collection. From the documentation:

> Returns an iterator for the items in the array. Remove is supported. Note that the same iterator instance is returned each time this method is called.

The way to reset the iterator is by calling `ArrayIterator#reset()` which should reset the iterator to the original state.

---
Tags: java, libgdx, collision-detection
---


# Question
Title: How to convert 3D coordinates to 2D Isometric Coordinates?
I wanted to make an isometric game which has a bouncing ball.

I assume that there is a way I can "show" a jumping motion in isometric, since it has been done before, but I was unable to find the maths/formulae which will help me depict this (Z-axis)motion.

If you know how i could do this please share.

Thank you :D

PS: If this sounded a bit confusing to you, just ask me in the comments.

# Answer
You can represent the transformation between 3D world coordinates to 2D screen coordinates as a projection matrix:

$$\begin{bmatrix} x\\ y\\ z \end{bmatrix} = \begin{bmatrix} X\_x & Y\_x & Z\_x & T\_x \\ X\_y & Y\_y & Z\_y & T\_y \\ X\_z & Y\_z, & Z\_z & T\_z \\ \end{bmatrix} \cdot \begin{bmatrix} X \\ Y \\ Z \\ 1 \end{bmatrix} $$

Here \[x, y, z\] is the screen-space projected position of the world-space point \[X Y Z\], where x & y are the horizontal & vertical pixel positions, and z is the depth (which you can use for sorting, etc). \[Tx Ty Tz\] is the on-screen position of the world origin (0, 0, 0).

You can think of splitting this matrix into its three columns as separate vectors:

* \\$(X\_x, X\_y, X\_z)\\$ is the screenspace projection of the X+ unit vector in worldspace (1, 0, 0)
* \\$(Y\_x, Y\_y, Y\_z)\\$ is the screenspace projection of the Y+ unit vector in worldspace (0, 1, 0)
* \\$(Z\_x, Z\_y, Z\_z)\\$ is the screenspace projection of the Z+ unit vector in worldspace (0, 0, 1)

For a true isometric projection, where Z is up, your vectors might look like this:

* \\$(X\_x, X\_y, X\_z) = \frac {\text {size}} 2 \cdot (\sqrt 3, -1,\frac {-1} {\sqrt 2}) \\$
* \\$(Y\_x, Y\_y, Y\_z) = \frac {\text {size}} 2 \cdot (-\sqrt 3, -1, \frac {-1} {\sqrt 2}) \\$
* \\$(Z\_x, Z\_y, Z\_z) = \frac {\text {size}} 2 \cdot (0, 2, \frac {-1} {\sqrt 2} ) \\$

Where `size` is the on-screen length of your worldspace unit vector (eg. the length of a tile's diagonal)

For a 2:1 dimetric projection (commonly used in games to get neat integer tile sizes, without the irrational numbers in a true isometric projection), you might use something like this instead:

* \\$(X\_x, X\_y, X\_z) = \text {size} \cdot (1, \frac {-1} 2,\frac {-1} {2 \sqrt 2}) \\$
* \\$(Y\_x, Y\_y, Y\_z) = \text {size} \cdot (-1, \frac {-1} 2, \frac {-1} {2 \sqrt 2}) \\$
* \\$(Z\_x, Z\_y, Z\_z) = \text {size} \cdot (0, 1, \frac {-1} {2 \sqrt 2} ) \\$

Where `size` is half the on-screen horizontal width of the tile. Here I left the z-ordering the same as the isometric case, since it's simple and "close enough" ;)
> 7 votes

# Answer
I would like to thank @DMGregory for a detailed explanation.

Initially I did not understand the matrices a lot so after a google search I found the simplified version of the matrices.

Suppose your 2D coordinates are x' and y', and your 3D coordinates are x , y and z.

To convert 3D coordinated to a 2D isometric projection you use the following formulae :

x' = (x-z)/ sqrt(2)

y' = (x + 2y + z) / sqrt(6)
> 2 votes

# Answer
The first thing about game development is not to over thing the thing you are thing to code.

If you want to "show" a jumping motion in an isometric game then break it down in simple parts.

**Getting to Destination**

I don't know what language or engine you are programming in but I would move your ball from point A to point B. This might be a simple:
`'transform = new Vector2(transform.x + 1, transform.y + 1);'`

**The 'Jumping'**

When you are moving to your point, just scale the ball up. That would make the illusion that the ball is jumping. When you are at your end point you would need to revert the scaling back to normal.

`var scale = gameobject.localScale;
gameobject.localScale = new Vector2(gameobject.localScale.x + 1, gameobject.localScale.y + 1);
gameobject.localScale = scale;`
> -1 votes

---
Tags: mathematics, isometric
---