# Question
Title: Should I store a value for every damage type even if zero, when using the Decorator pattern?
My game characters take damage by the method `TakeDamage(Damage amounts)`, and the `Damage` struct has every type of damage (`fireDamage`, `iceDamage`, `bluntDamage`, etc.). For now every `Weapon` has a lot of info in the `Damage` struct that isn't used, e.g. the common `Hammer` just has `bluntDamage`; and the others (`fireDamage`, `edgeDamage`, etc.) are all zero.

Is this the correct way, or should I use the Decorator Pattern for every kind of damage instead? Or is there another way?

# Answer
> 7 votes
As a general rule, one should never be a slave to any pattern. Be flexible. As for the particular example you give, it's a rather well known case, so I can help a bit with the pros and cons. I can say outright that it *has* been done both ways.

* **Who is going to read your code?** This should be your number one concern. As Gudio von Rossum put it, "Code is read more often than it is written." The decorator pattern is not the most complicated design pattern out there, but it is a design pattern. It provides a great deal of flexibility, so any developer working on the code is going to have to be thinking of this flexibility while they work on it. The brute force approach is not as flexible, so it's easier to wrap your brain around it.
* **Understand your costs.** How big of a deal is it that every weapon has a few extra bytes of data on it? Most of the time, it's not so bad. How big of a deal is it to add a new damage type? If you build your class structure well, it may be easy. If you do it poorly, you may find that you have to wade through the code to find all the loops that use the damage types and add to them. Also know that the typical decorator pattern requires heap allocations. For a game, that may be very affordable, but if you have a strategy engine that has to generate millions of these weapons every second to make decisions, that could hurt.
* How many types of damage do you have? Are there 8 types? 50 types? Can the user create new types? The more types you have to deal with, the more "waste" there is in the brute force solution.
* How many permutations are there for different damage types? Can you have an ice/fire/poisoned/blunt/sharp-thing that does all those types of damage? If you know that none of your weapons are going to do more than 4 types of damage, you can create an array of 4 "slots," each of which holds a damage type and a damage amount. You could also use a `std::vector` if you wanted an unbounded number of types.
    + Why use this over Decorator? Pros and cons. This approach provides flexibility, but with some restriction. Decorator opens the door wide for any modification of any Weapon behavior, while this approach sets some ground rules for what sorts of patterns are permitted. Look at your code, think of your readers, and find the best balance.
* Know that, if you use Decorator, you will need to develop a damage API that is robust enough to handle any arbitrary behavior a decorator may wish to use. This API may not be as readable as a simple one which scans through a table and sums up damage.

# Answer
> 3 votes
There is never just one correct way in programming. Any solution which gives you correct results is a "correct" solution. But not every "correct" solution is also a "good" solution. However, which solutions are good and which are bad usually depends on your unique requirements and personal preferences.

Some possible solutions:

* When you have a large amount of damage types but all damage sources are just going to have one kind of damage, you only need two fields in your damage structure: `value` and `type`.
* When you have some damage sources which do mixed damage but very few which use all the available damage types, you could use an array of damage-structures.
* You could also go the object-oriented way. Make `Damage` an interface with a public method `applyTo(victim)`. You can then have multiple classes which implement that interface in different ways. For example, the applyTo method of class `SimpleDamage` could have one value and one type, the class `PoisonEffectDamage` could not affect the victims's hit points but would instead put a poison effect on it, the class `CompositeDamage` could be an aggregate of multiple `Damage` objects which are applied one after another while `MultiformDamage` could have only one value but multiple types and uses the worst (or best? or average? or sum?) of the resistances of the victim.

---
Tags: architecture, design-patterns
---


# Question
Title: Unable to rollout release to alpha in Google Play Console
I have uploaded my APK, and filled in data in every field which was required... but using Googles new MAnage releases tab, I am unable to press the final button to roll it out to alpha. Its not telling me I need to do anything else, but the button is inactive.

See image:

# Answer
You are required to supply information in the sections marked with a grey checkmark (now a grey triangle with exclamation mark), in all required fields (marked with a blue asterisk). This includes, but isn't restricted to:

Pricing and Distribution:

* setting app availability to *all countries* (don't worry about this, read on),
* configuring presence of ads and being targeted *primarily* at children,
* confirming Android Content Guidelines compliance,
* acknowledging the app being subject to US export laws,
* configuring testing (you can have a closed alpha, hence countries doesn't matter at this stage)

Store listing:

* uploading feature graphics and even screenshots, yeah...

Once that's done, you'll get *two* "Ready to publish" labels, at the top of the page, the right one being a link to the App Releases management section where you can complete your rollout.

Yes, this is even more horrible UX than Google Play's previous light grey 'Why can't I publish?' help link on the top of the page. Make the best of it before the next iteration.=)
> 10 votes

---
Tags: android, google-play, publishing, alpha
---


title: Is TIN a 2D or 3D mesh?

text:
# Question
Title: Is TIN a 2D or 3D mesh?
I have a TIN (Triangle Irregular Network) that was created in CAD software packages from something called DTM (essentially each point represents the height of the ground for that specific point).

The result looks like a 'blanket' of triangle, so not closed in any way. I think that's a non-boundary manifold triangle mesh but not sure. More unclear is if it is a 2D mesh (like a polygon is a 2D surface in a 3D Cartesian space even if not all vertexes are the same z). Can someone please explain what kind of geometry is a TIN?

Example (the blue triangles are the TIN):

# Answer
> 1 votes
TINs can be either. From the Wikipedia entry:

> Although usually associated with three-dimensional data (x, y, and z) and topography, TINs are also useful for the description and analysis of general horizontal (x and y) distributions and relationships.

A mesh does not need to be closed to be considered 3D, it simply needs to be described in 3 dimensions. In fact I'd say a majority of games have their terrain or large meshes "open" because the player will never see the bottom of a building or terrain, yet we don't consider those games to have 2D terrain.

The pictured mesh is most likely 3D, as it's one of the common uses cases depicting topography.

---
Tags: mesh
---


# Question
Title: about register reserved word or sementic in HLSL
I'm studying HLSL cookbook. In that sample code, author used a lot of register sementic.

like this

```
cbuffer cbPointLightDomain : register( b0 )
{
    float4x4 LightProjection : packoffset( c0 );
}

cbuffer cbPointLightPixel : register( b1 )
{
    float3 PointLightPos : packoffset( c0 );
    float PointLightRangeRcp : packoffset( c0.w );
    float3 PointColor : packoffset( c1 );
    float2 LightPerspectiveValues : packoffset( c2 );
}

```

what is benefit of this?

actually I erased every register keywords and ran program.

the result is completely fine.

# Answer
`register` exists to let you manually explicitly specify which register to use for a particular shader variable, in the event that you need to for some particular purpose or because you like to be explicit and not rely on how the compiler will pick registers (which may change over time).

It is optional, which is why you can remove it and everything still works.
> 1 votes

---
Tags: directx11, hlsl
---


# Question
Title: One big spritesheet vs many smaller spritesheets?
I have my 2D character animations which are stored in spritesheets. I have individual sprite sheet for every animation. For example, if my character have animations for idle, run and jump, I have 3 different spritesheets.

Is it good way for managing 2D animations or it's better to store all animations in one big spritesheet? I noticed that many old games animations are stored in one big spritesheet - is it the best way?

# Answer
There is no "best" way. There is the way that is most appropriate for your program, in terms of code complexity, managing your data sets, performance, etc, and many of these are questions that only you can answer. If what you're currently doing runs well enough on your target platform(s), it'll do.

Having said that, you should consider the reason why sprite sheets exist in the first place. Their purpose is to address performance issues associated with large amounts of texture changes; by packing many sprites into a single texture, instead of using a separate texture for each sprite, we get to reduce the number of texture changes and (hopefully) increase performance.

From there it should be obvious that using many small sprite sheets is a step back from this towards having a separate texture for each sprite. However you need to balance that with the restriction of your hardware's maximum texture size and with the possibility of large amounts of unused space in a single large sprite sheet.
> 4 votes

---
Tags: 2d, animation, sprites, spritesheet
---


# Question
Title: Why should I always consider creating and using object pools instead of instantiating the new object on the fly?
I have read about this pattern several times (from a best-practices perspective):

> **Memory Allocation**: Instead of instantiating the new object on the fly, always consider creating and using object pools. It will help to less memory fragmentation and make the garbage collector work less.

However, I don’t know what it actually means. How can I implement it?

For example, I can instantiate a `GameObject` using the `Instantiate` method of Unity?

```
Instantiate(prefab, new Vector3(2.0F, 0, 0), Quaternion.identity);

```

Is this use discouraged? What else can it mean?

# Answer
> 40 votes
If you're planning to instantiate many instances of the same prefab, you should definitely think about using object pooling. Calling Unity's Instantiate function is one of the most taxing method calls you could make.

Object pooling is when you instantiate prefabs before they are used. They are deactivated immediately upon instantiation and reactivated only when they are needed. While this does increase memory usage, it avoids the CPU overhead of instantiating during gameplay.

For example, I'm currently working on a bullet hell game that requires hundreds of bullets to be spawned at runtime. I initially tried to make the game without object pooling but that ended up being a disaster ( less than 2 fps). Now, I pool 500 bullets before the game starts and the game runs astonishingly fast (200 fps).

There are situations where object pooling cannot be used. For instance, if you have a game where player input dictates what prefab is spawned, then you may have no choice but to use the normal Instantiate call. Object pooling is only possible when you know ahead of time what objects will be needed.

Sebastian Lague's YouTube tutorial is a great resource for learning about object pooling: https://youtu.be/LhqP3EghQ-Q

---
Tags: unity, c#, design-patterns, memory-efficiency
---


title: Determine which button was pressed

text:
# Question
Title: Determine which button was pressed
I have 4 buttons, which on clicking,all of them does the same thing (each displays a different string read from an array to the button's text field). I want to have a single OnClick function to keep my code clean, instead of having 4 different functions for 4 different buttons. But I need to determine which button was pressed, How to do that inside OnClick Function?

# Answer
> 0 votes
You can use EventSystem.currentSelectedGameObject defined in the `UnityEngine.EventSystems` namespace :

```
 public void OnClick()
 {
     Debug.Log( UnityEngine.EventSystems.EventSystem.current.currentSelectedGameObject.name ) ;
 }

```

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


title: Unity low level network API

text:
# Question
Title: Unity low level network API
I was trying out Unity Network LLAPI, I am following the this tutorial. I wrote everything the same, my `server` starts well and good with no errors.

When my `client` tries to add host

`int hostId = NetworkTransport.AddHost(topology, port);`

like this, it crashes with this error

`Cannot open socket on ip {*} and port {12000}; check please your network, most probably port has been already occupied
UnityEngine.Networking.NetworkTransport:AddHost(HostTopology, Int32, String)
Client:Connect() (at path/to/game/files/Client.cs:35)
UnityEngine.EventSystems.EventSystem:Update()`

Now if I change port on `client` side it says `Wrong IP or Port`.

I tried looking but didn't find much. Don't know what is wrong. Also I'm on `Linux`

# Answer
> 1 votes
The reason of the error is that you didn't stop **previous host** and trying the adding new. With the same credential you are trying to add same server. So first stop host then, add host.

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


# Question
Title: How do I fix objects "popping" or jittering in physics engine?
I've got a simple physics engine that solves collisions by simply correcting the position of overlapping bodies (just circles for now) directly, as opposed to just changing the velocity or applying an impulse. Velocity is only changed after impacts are already resolved, or during the integration part.

I've had the problem that in heaps of objects the top objects apply too much pressure (this exists implicitly, there's no pressure modelling in the algorithm) on the objects at the bottom of the heap, which results in them getting pushed through floors, etc.

I wanted to fix this by sorting the objects by their y-coordinate, so the collisions are resolved bottom-up. But now, the engine shows weird popping behavior for objects which should actually be at rest (see gif)

Without just giving you the source code - what could this be?

# Answer
One solution I have found when using position correcting is to have a few iterations and vary the strength with each iteration.

```
doPhysics();

int num_iterations = 5;
for(int iteration=0; iteration<num_iterations; ++iteration)
{
    float strength = float(iteration+1)/num_iterations;
    correctPositions(strength);
}

```

So the first iteration has a strength of 1/num\_iterations and the last has a strength of 1. This makes my simulations smoother and more stable than simply using the same number of iterations with a fixed strength.
> 6 votes

# Answer
Your problem lies in the fact that you have no "resting" state for your bodies. Any physics system has an amount of energy, be that kinetic, thermal, and so on. In reality, solid object deform slightly, and tranform some kinetic energy into heat, though it is hardly measurable. It's also worth noting that in reality there is no such thing as a completely solid object. Even dense materials, like diamond, have space in between the atoms, giving the atomic structure room to flex, and absorb kinetic energy.

To make this relevant, resting bodies are in a state where the only forces in effect is the "normal force", which is to say, the force that prevents bodies from floating through each other. The magnitude of that normal force, is proportional to the density of the objects, and how far they have penetrated each other.

Physics engines call this value "slop".

Here's the trick: Calculate the slop, and correct the position of the bodies, and apply the normal force, based on the relative velocity of the two bodies. during the update of the bodies themselves, calculate the kinetic energy of each body. If it is below a minimum value, then put the body to sleep, until a force of sufficient magnitude is applied to it. (usually twice the minimum value).
> 5 votes

# Answer
Why not add a "sticky" surface to them and have them stick to a resting position gradually and when another object hits it it transfers some energy into it causing it to move but the sticky surface will cause it to lose some of this energy and stop in a resting position. the gif looks like it has no friction to it.
> 0 votes

---
Tags: physics, physics-engine
---


title: Understanding Unity 5 Car controller

text:
# Question
Title: Understanding Unity 5 Car controller
As with all Unity versions Unity 5 comes with a set of Standard Assets. This new set of Standard Assets comes with a Car Controller. Either by attaching a Car user controller script or a Car A.I. script the Car is ready to be used within a game. I am using that said Car controller to create my own car in a game. What I am trying to do is increase the cars acceleration and top speed. I did not find any documentation on the mechanics behind the car controller (and since I do not know much about cars) I did not find a way on how to do this. I am reading the script and understand the flow of code but do not understand which variables affect what in the script.

Now for Top speed the car controller exposes a public variable responsible for that precise task. But what about acceleration?

# Answer
> 1 votes
In order to increase the car's acceleration, you need to increase the torque variable. There are two torque variables in Unity's official car controller, one for the forward movement and one for the reverse.

Keep in mind that the torque variable also controls how gears change (f.e. more torque = earlier gear changes) and too low of a torque can make certain speeds pretty hard to attain.

# Answer
> -1 votes
I've found it. You need to change the reverse torque ;) and wheel colliders forward friction.

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


# Question
Title: How to move objects with different y positions by a certain number of units
As seen in the image below, I have game objects with different y positions. I would like to select and change their y position by say, 2 units downwards while maintaining the gap. Please note I want this to be done through the inspector. I tried adding 2 units, but this just put all four objects on the same line. How can I achieve this?

# Answer
> 5 votes
Group the game objects under a common parent, and then try adding 2 units to y of the parent game object.

# Answer
> 2 votes
An other solution would be to rely on the snap settings :

1. Hold `CTRL` (`Command` on Mac)
2. Click on the gameobjects in the hierarchy (or the scene view)
3. Keep `CTRL` (`Command` on Mac) pressed and move the green axis vertically
4. The objects should snap on the grid and move 1 unit at a time

You can change the Snap settings in the `Edit > Snap Settings...` menu.

<sub>(source: unity3d.com)</sub>

---
Tags: unity
---


# Question
Title: In Unreal4, Can I use switch case in C++ with FString?
I'm making XML parsing code with FXmlNode. I want to iterate through GetChildrenNodes(), and use switch-case with FString which is return value of FXmlNode::GetTag(). Is there someway to do that? Or should I use

```
 if (Tag == TEXT("XX") .. else if (Tag == TEXT("YY"));

```

Thanks.

# Answer
In C++, you can't switch on strings, only integers (and the values you compare to must be constant).

But it is possible to *indirectly* switch on strings by choosing a stable mapping from string to integer (such as a hash function), applying that to the constants as well as the string to switch on, and using that. Because the expression in a `case` statement must be a compile-time constant, you're likely going to want to write that hash or mapping yourself and not rely on anything Unreal provides, as it may not be sufficient for this purpose.

FNV1a is a simple, decent hash function, and can be implemented as a `constexpr` function in C++. This will let you write:

```
constexpr std::uint32_t fnv1a(const char* s) { ... };

...

switch(fnv1a(someString)) {
  case fnv1a("Foo"): ... break;
  case fnv1a("Bar"): ... break;
  default: ... break;
}

```

If you don't have a modern C++ compiler, you will be forced to manually hash the strings yourself and write the resulting constant values in the `case` statements, which is exceedingly cumbersome.

Frankly, I'd argue that if the comparison code in question isn't a performance bottleneck, you're better off not overcomplicating things and just doing `if`/`else` chains. If it *is* a performance bottleneck, it might be worth revisiting whether or not you can replace the strings in a broader, algorithmic sense as it will likely be a bigger performance win.

As always, your mileage may vary, and you'll want to engage the services of a profiler to ensure you're actually gaining something by adding this extra layer of indirection.
> 2 votes

---
Tags: unreal-4, unreal, xml
---


title: Top down 2D game: hole tiles

text:
# Question
Title: Top down 2D game: hole tiles
I'm making a top down 2D game in Unity, here's my doubt: how can I add "hole" tiles to it, so the player could fall (something like Zelda: Link to the past, or the water tiles in Enter The Gungeon)?

The solution I thought is to put tags on each tile (ground, hole, trap, etc), put the player on Z = -5 and use the 3D Physics.Raycast to check in which tile the player is. But that doesn't seem optimized, I would need to spam colliders in every tile and use the Raycast at each frame. Can you guys give me better alternatives?

Thanks a lot! :)

# Answer
I don't know what tool you are working with but as if you work in unity like me, you can make a trigger for those holes and certainly player has a collider. so in collision stay of hole or player just write a code that checks the tag of other. if the distance was less than a threshold write the code for falling.
> 1 votes

# Answer
Think of the hole tiles as "teleporters" which teleport the player-character to a different map (the one representing the layer below it).

You will likely already have an implementation for these to implement doors and other gateways between maps. The only difference between a door of a building leading to an indoor map and a hole leading to the dungeon map of the floor below is the animation you play when the player-character steps into them.

Using 3d physics just for this gimmick is likely not worth the hassle.
> 1 votes

# Answer
If your grid consists of tiles of 1 unit width and length, you should implement a function that is called from Update() and which constantly checks whether you find yourself one another tile than the previous one. You round every time the X and Y coordinates values, so that you would know on which tile you are at a specific moment. If your function detects that you arrived on another tile, check whether the new location is hole. You should have a List() of your holes location and you iterate through it. Or the better thing would be to actually to label the hole-tiles and instead of running through a whole list, you simply make a check on that new tile.
> 0 votes

---
Tags: unity, 2d, tiles, tilemap, tilesets
---


# Question
Title: Tile-based board game collision mechanism algorithm
I am looking to see ideas for an algorithm which will handle collisions for some battle-ship tile-based board game.

# A little about the game

The game is pretty simple. Basically there is a board, which usually sized `20x36` tiles. One tile is a position that a ship can be at, unless the tile is a rock tile.

Many ships are in the game, and all players have 35 seconds to select 4 moves that their ship will perform. After these 35 seconds, all ships will perform the selected moves parallel, by doing the first selected move, then going to the second, third and fourth, and then 35 seconds again to select new moves.

A ship can either move Forward, Left or Right.

Now these are the collision rules for the game:

1. All ships that are moving (regardless of direction) attempt to "claim" the space that started directly in front of them. That space has five possibilites: a. That space is empty and unclaimed. Then move the ship into that space. b. That space contains a stationary ship. Then execute a "bump" (see below). c. That space contains a ship that is moving, and claiming the first ship's space. Then stop movement entirely (with a collision). d. That space is empty but claimed by a ship of the same or larger class. Then stop movement entirely (with a collision). e. That space is empty but claimed by a ship of smaller class. Then move the ship into that space (with a collision).
2. All ships that are turning but have not "stopped entirely" then attempt to claim their destination space. Now that space also has five possibilities:

**2.a.** That space is empty and unclaimed. Then move the ship into that space.

**2.b.** That space contains a stationary ship OR a ship that moved there in step 1. Then stop movement entirely (with a collision).

**2.c**. That space contains a ship that is moving, and claiming the first ship's space. Then stop movement entirely (with a collision).

**2.d**. That space is empty but claimed by a ship of the same or larger class. Then stop movement entirely (with a collision).

**2.e.** That space is empty but claimed by a ship of smaller class. Then move the ship into that space (with a collision). Note: At the end, all ships have their orientation changed if they tried to turn... even if they had "stopped entirely." Note that (2b) does not depend on the ship's class. This allows a small ship to move forward into a tile even if a larger ship is attempting to turn into that tile. If two ships both try to move into the same tile for any other reason, the larger ship succeeds.

**Example**

So let's say you select the forward move on your ship, and there is another ship on the target tile you are aiming to (forward). So what do you need to make sure?

You need to check if that target tile is unclaimed. If it's not unclaimed, you can check if its a rock or another ship. If it is a rock, cancel movement. If it's another ship, and it does not move, push it by 1 tile and stay in the same location. If that ship does move, you have to ask it if that ship has successfully moved, but for it to return a success message, that other ship has to check if it can move, and that can have a lot of cases with a lot of callbacks and might end up not efficient.

So my question is, how can this be done, in the proper way?

Read more here about the collision mechanism rules

# Answer
`I just feel like the algorithm I described will just create me a big spaghetti and it will take me a long road to complete`

Not really. Appreciate that there is a difference between compile time code written to achieve a task, and the instructions / paths taken in silicon when that code is executed. The former's quite condensed and simple to read; whereas its runtime flow may be considerably more complex to follow, especially over multiple ticks. We don't usually look at the latter unless we are debugging, and at that point it is easy enough to follow our compile time code simultaneously to see how it drives the latter process.

---

`If we go through the algorithm I described, this means I have to loop through all players atleast N times, where N is the amount of ships I have in the game.`

But that's stock-standard collision detection / resolution in games like this. It behooves you to forego multiple phases / conditions of "did someone move here before me during this turn". See code below.

Still, there are many different ways to achieve collision detection and resolution. If you are working in a floating point space, then a trivial implementation will often go for the `O(n^2)` ("big-oh n squared") solution that you mention here. However, because you are working on tiles, there is a much simpler, finite space solution that I provide below. All you need to do for each ship is look at the proposed tile it wants to move to. You don't have to compare each ship to each of the other `n-1` ships.

---

You delve into certain rules that make it difficult to write up an exact solution, which is to be expected: Even pro game devs hit a wall when *their own specs go too far into the realm of speculation*. That's when you need to stop thinking, pick up your keyboard, and start writing code in order to determine further requirements... until you do so, all you have is a fragile house of cards. It's like trying to explore the next room in a house when you don't even know where all the doors leading outward from the current one, are! Exploring game designs is a highly iterative process and requires you to constantly push, in code, to the leading edge of your ideas in order to explore further without wasting time.

---

Loose, rough, incomplete, untested C# code follows as a guide. (Please do not ask me to repeatedly come back and change this, as already it has taken a fair effort to draft this for you; and any areas I've left out are either trivial to implement, up to your interpretation, or were in conflict with other matters in your mini-spec. I am however happy to answer general questions in the comments, below.)

---

```
public class Tile
{
    Ship ship;
    Rock rock;
}

public enum Occupation
{
    None,
    Ship,
    Rock
}

public class Ship
{
    //assume 8 ship-facing directions (N, NE, E, SE, S, SW, W, NW in that order to represent a clockwise rotation)
    const int turnDegreesMax = 8;

    static const Vector2 offsetByHeading[] = new int[]
    {
        new Vector2(){0,-1}, //N
        new Vector2(){+1,-1}, //NE
        new Vector2(){+1,0}, //E
        new Vector2(){+1,+1}, //SE
        new Vector2(){0,+1}, //S
        new Vector2(){-1,+1}, //SW
        new Vector2(){-1,0}, //W
        new Vector2(){-1,-1}, //NW
    };

    public int sizeClass; //you could also prefer an enum here, to have named classes.
    public Move[] moves = new Move[4];
    public int moveStatus;
    public int heading;
    //suggest you use a integer, not float vector class, to avoid casting and other confusions
    public Vector2 position;

    public Vector2 ProposeMove()
    {
        //TODO - you need to check whether you will be outside of map bounds here,
        //i.e. (0-100) in x or y! and do not add delta if so.

        return position += offsetByHeading[heading]; //should return a new Vector2
    }

    public void MoveTo(Vector2 position)
    {
        //TODO - you need to check whether you will be outside of map bounds here,
        //i.e. (0-100) in x or y! and do not add delta if so.

        position += delta;
    }

    public void Turn(int delta)
    {
        heading += delta;

        //remember to ensure heading is still within range
        if (heading > turnDegreesMax-1)
            heading %= turnDegreesMax-1;
        else if (heading < 0)
            heading += turnDegreesMax-1;
    }
}

public class Move
{
    //for simple 8-directional gameplay, make range 0 to 7 representing each direction; else use float degrees / radians here.
    //range -1 to +1 inclusive: -1 is left turn, 0 is remain facing ahead (see heading), +1 is right turn; else use float here.
    public int turnDirection;
    //are we moving forward this move round? and if so, where are we moving relative to heading?
    public int linearDirection; //0 = no direction, 1= left, 2 = forward, 3 = right

    //NOTE: only ONE of these should be set non-zero at a time, as in one round,
    //you cannot be turning and moving into a new tile AND turning (for simplicity).
}

public class Game
{
    Tile[,] tiles = new Tile[100,100]; //or whatever size
    //you will have pre-populated this in initialisation and other places,
    //e.g. where a shop or shipyard constructs a new ship for use.
    List<Ship> ships = new List<Ship>();

    //call once all players have queued their moves and hit "Go".
    void EnactRounds()
    {
        //for each move out of 4 (do 1st phase moves for all ships, then 2nd phase moves for all, etc.):
        //NOTE: Unless we make explicit changes like shuffling the list or ordering by initiative,
        //we proceed in an order defined by the order in which ships were inserted into this list.
        //If you don't, certain ships will _always_ take move precedence over others.
        for (int i = 0; i < 4)
        {
            foreach (Ship ship in ships)
            {
                Move move = ship.moves[i];
                if (move.linearDirection != 0) //attempt linear move along current heading
                {
                    //note: I don't deal with linearDirection's value here, I just need to know its non-zero to move forward:
                    //implementing left / right "strafe" movement is left to you as it is not central to collisions.
                    Vector2 proposedPosition = ship.ProposeMove();
                    Occupation occupation = IsTileOccupied(proposedPosition);
                    switch (occupation)
                    {
                        case Occupation.none:
                            //this updates the Tiles map, so that in the next foreach loop iteration calling this method,
                            //we will have the updated map ready for the next ship - remember: ship list order matters!
                            ship.MoveTo(proposedPosition);
                            tiles[proposedPosition.x, proposedPosition.y].ship = ship;
                            break;

                        case Occupation.ship:
                            Ship shipOther = tiles[proposedPosition.x, proposedPosition.y].ship;
                            if (ship.sizeClass > shipOther.sizeClass)
                            {
                                //note we do not use shipOther.Bump(ship), because this will need access to higher level
                                //(map) data structures that the player's Ship instance / class may not have access to.
                                BumpInto(ship, shipOther);
                            }
                            else
                            {
                                //do whatever UI + sound FX to show player cannot go there.
                                BounceOff(ship, shipOther);
                            }
                            break;
                        case Occupation.rock:
                            Rock rock = tiles[proposedPosition.x, proposedPosition.y].rock;
                            BounceOff(ship, rock);
                            break;
                        default: break;
                    }
                }
                else
                {
                    if (move.turnDirection != 0) //ship is busy turning in it's current Tile / position
                    {
                        ship.Turn(move.direction);
                    }
                    else //no order was issued
                    {
                        //Ship waits through this round.
                    }
                }
            }
        }

        //...do other stuff...
    }

    Occupation IsTileOccupied(Vector2 position)
    {
        //you can rather generalise Ship and Rock to a supertype Entity and then just check the type, here (or in Tile).
        if (tiles[position.x, position.y].ship != null) return Occupation.Ship;
        if (tiles[position.x, position.y].rock != null) return Occupation.Rock;
        //...etc.
        return Occupation.None;
    }
}

```

Obviously, I cannot write your game for you. This cannot be anywhere near exact, but it can provide a path to a solution. Try this out, and if it gets you on track to the solutions you desire, great.
> 2 votes

# Answer
The algorithm will be a bunch of if-statements. But the data structure I think is more interesting. Since you did not provide a programming language, I will assume C++ in the following example:

```
typedef enum {
    EMPTY,
    SMALL_SHIP_1,
    SMALL_SHIP_2,
    BIG_SHIP_1,
    ...(etc)
} _tile_t;

```

This will define a type for a ship (basically an integer, since it may not be necessary to create a class for each type of ship if they share a lot of similarities. Then creating a container for the ships:

```
_tile_t game_board[20*36];

```

This will give you an implementation which is fairly easy to extend. Considering collision-detection for a ship in index i of the game board, check for `game_board[i-1]` for left (remember to account for the width of the game map), and `game_board[i-WIDTH]` for above (remember to account for the height of the game map).
> 0 votes

---
Tags: collision-detection, algorithm, tiles
---


# Question
Title: Handling of persistent key presses in an ECS
I'm currently in the planning phase of a game. The whole thing should be based on the entity-component-system (ECS) pattern. All logic is concentrated inside of the systems, i.e. that the components hold data only. Communication across the systems is performed using asynchronous events.

Using this design, I'm unable to find a clean solution for the simple example task of moving player: While the input system generates key press events, I'm looking for a way to query the key state, since the player will most likely want to move the player for more than one frame.

There are two possible ways I can think of solving this problem:

* Retrigger the key press event every frame
* Pass the corresponding systems a reference to the input system

Neither possibility sounds "correct", since they both require the abuse of the design.

Is there a better approach for solving this issue?

# Answer
> 0 votes
I would opt to tackle input using a hybrid approach.

1. Cache the current input state in the input system, allowing it to be queried.
2. Raise appropriate delta input events as necessary.

Lets take an example, pressing both left and mouse buttons imply move forward.

If this use case was designed specifically using only (2), you not only would have to write the handler to detect the mouse button press and release, but maintain state management to track both buttons since its possible one is pressed or released in different frames from the other.

If we used a query approach, the system no longer needs to be bothered with maintaining state for these buttons as the input system does this automatically and exposes a way that a given system could simply poll

```
if ( input.IsMouseButtonsPressed( Mouse::LEFT || Mouse::RIGHT ) ) {
  // do logic
}

```

This becomes even more powerful when you have more than one occurrance of the same state check, likely in different systems, allowing it to be centralized and for that state to be managed by what I feel is the most appropriate owner, the input system.

In systems design, I like to take this one step farther and layer another abstraction here on top of what I have described the input system doing. This system is called an action or intent system that generally uses both methods to maintain an additional state map meant to abstract an action with a particular keybinding, allowing those bindings to be customized.

Now rather than your movement system looking for key-press `W` or up-arrow key for moving forward, it might ask the action system if an action is toggled:

```
if ( actionSystem.IsActionActive( Action::MOVE_FORWARD ) ) {
  // move forward
}

```

There will often be a mix of both of these in certain systems as sometimes certain bindings are not mutable and therefore those will be used directly, e.g. the left/right mouse button example above.

---
Tags: entity-system, events, keyboard
---


title: Accounting for drift between ticks

text:
# Question
Title: Accounting for drift between ticks
What are some solid techniques to account for the gap between processing time and frame update ticks? In other words, the game/render loop looks like this:

Some important points:

1. Tick timings are determined by the web api (roughly 16ms consistently)
2. Workers could either be triggered at the start of each tick (first checking if the previous one finished) or run continuously in their own loop. I think running continuously is better if we can account for the gap, so as to not waste time being idle which could lead to skipped frames.
3. Either way - the size of the gap will vary between updates. It's not constant

*note* this article is a good reference: https://gafferongames.com/post/fix\_your\_timestep/ ... I haven't really tried applying it yet and I'm not sure if it fits the web constraints exactly.

# Answer
> 1 votes
I'm not sure if this is much of an answer, but...

Roughly speaking, if you are finished the work and want to render it, then that happens on a set schedule. Your graphics (WebGL) calls buffer things to be done; on next vsync (typically, in a browser environment), those commands should all have reached the GPU so they can be effected.

You really want to ensure that gap is always reasonably sized, because if you are still buffering commands when the next vsync comes around, your display may show odd results (depends very much on your implementation specifics). Other than that, you don't have to worry about the gap *as such* since your buffered commands that have been sent to the GPU will simply be put into practice at the next scheduled vsync.

If you want to be very sure you are not still making commands across the system bus when the threshold (~16.7ms @ 60fps) is reached, just make sure your ticks always take way less than 16.7 milliseconds (depending how close you want to cut it). You could have a cut-off at say 15ms in. If you're doing this on e.g. `RequestAnimationFrame`, then you have that much time to get all your work done, and a 1.7ms safety buffer (but you need to test to be sure of what works for you). If the job doesn't look complete by that point, just don't schedule draw calls for it till next frame (or later frames, even). You should only be doing draw calls for data that is in a ready state.

TL;DR Ensure your processing and resultant draw calls complete well before the render period does, and you will be fine. Profiling your code is the best way to determine if that is the case.

---
Tags: javascript, browser-based-games, frame-rate, timer, timestep
---


# Question
Title: Bullet hits the object not in the center of the screen
When player shoot, the bullet fly to the center of the screen. But if player stay too close to some object, then bullet hits it not in the center, because it flies from the gun on the right side of the screen. How can I fix this?

```
 public Rigidbody projectile;
 public int speed = 50;
 public Transform startBulletPosition;

 void Update()
 {
     if (Input.GetButtonDown("Fire1"))
     {
         Rigidbody clone;
         clone = Instantiate(projectile, startBulletPosition.position, transform.rotation) as Rigidbody;
         var centre = new Vector3(0.5f, 0.5f, 0f);
         var ray = Camera.main.ViewportPointToRay(centre);
         clone.velocity = ray.direction * speed;
     }
 }

```

**Edit 1**

# Answer
Right now your camera center and your bullet trajectory will never meet. You're using what is essentially `transform.forward` from the camera and using the gun as the starting point, your bullet will always be offset from the center by the same distance as the gun is from the camera.

Regardless, you should probably do it a bit differently, because always aiming at the center of the screen isn't going to work as you want it to.

Instead, cast a ray from the center of the camera, that ray will hit an object in the scene (or reach some maximum distance). Now get the vector between your gun and the hit point (or maximum distance point). Then either direct your bullet along that vector. You can also rotate the player's gun to align with the firing direction.

This essentially changes the aim of the gun based on the distance of the object it's firing at.
> 3 votes

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


# Question
Title: Collision stickyness problem on multiple inputs
I've been trying for a couple of days to solve an issue I'm having with top-down 2D collisions, whenever I collide with tiles that have adjacent collidable tiles my player sticks to the wall, If I collide right or left I can't move up or down, the same for the Y axis, I can't move left or right when colliding from the top or bottom. Here's a picture to represent my issue a bit better:

The gray boxes represent the collision area.

Here is my code:

```
            Rectangle tileRect = new Rectangle((int)tile.Position.X, (int)tile.Position.Y, tile.SourceRect.Width, tile.SourceRect.Height);
            Vector2 temporaryPlayerPosition = player.Sprite.Position - player.Velocity;
            if (player.CollisionBox.Intersects(tileRect))
            {
                if ((player.CollisionBox.Right >= tileRect.Left && player.CollisionBox.Right < tileRect.Right) ||
                    (player.CollisionBox.Left <= tileRect.Right && player.CollisionBox.Right > tileRect.Left))
                {
                    player.CollisionBox.X = (int)temporaryPlayerPosition.X;
                    player.Sprite.Position.X = temporaryPlayerPosition.X;
                }
                if ((player.CollisionBox.Bottom >= tileRect.Top && player.CollisionBox.Bottom < tileRect.Bottom) ||
                    (player.CollisionBox.Top <= tileRect.Bottom && player.CollisionBox.Top > tileRect.Top))
                {
                    player.CollisionBox.Y = (int)temporaryPlayerPosition.Y;
                    player.Sprite.Position.Y = temporaryPlayerPosition.Y;
                }
            }

```

If anyone could point me to the right direction I would be grateful!! Thanks again!

**EDIT!!!**

I changed my whole collision code so it does a forward check before handling the displacemente of the sprite, I still have the stickyness issue though. This is the new code:

```
Rectangle forwardCollision = new Rectangle((int)(player.CurrentPos.X + (player.Velocity.X*4)), (int)(player.CurrentPos.Y + (player.Velocity.Y*4)), player.Sprite.SourceRect.Width, player.Sprite.SourceRect.Height);
player.CanRunX = player.CanRunY = true;
foreach (TmxTile tile in tileList)
{
    tile.Update(gameTime);
    Rectangle tileRect = new Rectangle((int)tile.Position.X, (int)tile.Position.Y, tile.SourceRect.Width, tile.SourceRect.Height);
    if (forwardCollision.Intersects(tileRect) && SolidTileIds.Contains(tile.Id))
    {
        if (player.Velocity.X != 0)
            player.CanRunX = false;
        if (player.Velocity.Y != 0)
            player.CanRunY = false;
    }
}
foreach(DebugRectangle rectangle in rectangleList)
{
    rectangle.Update(gameTime);
}

if (player.CanRunX)
    player.Sprite.Position.X += player.Velocity.X;
else
    player.Sprite.Position.X -= player.Velocity.X;
if (player.CanRunY)
    player.Sprite.Position.Y += player.Velocity.Y;
else
    player.Sprite.Position.Y -= player.Velocity.Y;

player.CurrentPos = player.Sprite.Position;
player.CollisionBox.X = (int)player.Sprite.Position.X;
player.CollisionBox.Y = (int)player.Sprite.Position.Y;
player.DebugRectangle.Position.X = forwardCollision.X;
player.DebugRectangle.Position.Y = forwardCollision.Y;

```

# Answer
You might think of it like a filter. You'll simply remove movement in any direction that is currently blocked. For example:

```
Vector2 deltaMovement = player.Velocity;

if(blockedRight && deltaMovement.x > 0)
    deltaMovement.x = 0; //Don't move XPlus

if(blockedLeft && deltaMovement.x < 0)
    deltaMovement.x = 0; //Don't move XMinus

if(blockedUp && deltaMovement.y > 0)
    deltaMovement.y = 0; //Don't move YPlus

if(blockedDown && deltaMovement.y < 0)
    deltaMovement.y = 0; //Don't move YMinus

MovePlayer(deltaMovement);

```

This simply looks for collisions in each orthogonal and zeros out any velocity in that direction if there is a collision there. Clearly you'll need to implement the `blocked*` properties yourself.
> 0 votes

# Answer
You had the right idea, but in adding Velocity to your temp player movement early on it made it hard to undo so your if statements got clunky.

For the following we're assuming positive values of X velocity = going right and positive values of Y velocity = going up *down*.

Lets clean this up and adjust the logic a bit shall we:

```
// Store some helpful variables to make our code easy to read
Rectangle tileRect = new Rectangle((int) tile.Position.X, (int) tile.Position.Y, tile.SourceRect.Width, tile.SourceRect.Height);
Rectangle colBox = player.CollisionBox;

// Lets not worry about velocity yet, just store temp position for next frame
Vector2 nextPosition = player.Sprite.Position;

// Only need to affect the position values if colliding
if (colBox.Intersects(tileRect)) {

    // Some variables to make our condition more readable.
    var collidingOnLeft = colBox.Left <= tileRect.Right;
    var collidingOnRight = colBox.Right >= tileRect.Left;
    var collidingOnBottom = colBox.Bottom <= tileRect.Top;
    var collidingOnTop = colBox.Top >= tileRect.Bottom;

    // We're colliding on the left, so lets make sure
    // we can't go any further left by limiting the
    // X Velocity to a positive value.
    if (collidingOnLeft) {
        nextPosition.X += Math.Max(0, player.Velocity.X)
    }

    // Same idea here but with negative values
    if (collidingOnRight) {
        nextPosition.X += Math.Min(0, player.Velocity.X)
    }

    // Now we're limiting in the Y direction but same principle
    if (collidingOnBottom) {
        nextPosition.Y += Math.Min(0, player.Velocity.Y)
    }

    if (collidingOnTop) {
        nextPosition.Y += Math.Max(0, player.Velocity.Y)
    }
} else {
    // No collision so just add the velocity
    nextPosition.X += player.Velocity.X;
    nextPosition.Y += player.Velocity.Y;
}

// We're done - set the values
player.CollisionBox.X = (int) nextPosition.X;
player.CollisionBox.Y = (int) nextPosition.Y;
player.Sprite.Position.X = nextPosition.X;
player.Sprite.Position.Y = nextPosition.Y;

```

Hopefully this points you in the right direction.
> 0 votes

---
Tags: c#, xna, collision-detection, monogame, collision-resolution
---


# Question
Title: Why does my Character Jump only Half as High?
I am trying to implement simple Newtonian physics for my game. However, my character only jumps half of the height I would expect him to.

---

Physics says that the take-off velocity (impulse) `v` for an object to reach a height `h` is

Thus, to achieve a height of `2.0` meters, an impulse of `6.264` (per unit of mass) would be required. I used this as a benchmark to test the correctness of my physics code.

---

However, aforementioned impulse only raises my object `0.97` meters into the air before it falls down again.

I've tried Euler integration, Euler (midpoint) integration and Runge-Kutta 4 integration, all resulting in a jump height `0.97`. My delta time is fixed to `1 / 120`.

```
// Calculate the movement of the game object in this physics frame
Vector3 translation;
{
  Vector3 acceleration = this.queuedForces / this.Mass;

  // Convert impulses
  Vector3 impulses = this.queuedImpulses / this.Mass;
  acceleration += impulses / delta; // turn impulse into force over 1 delta tick

  // Apply half of the force scaled by time
  this.Velocity += acceleration * delta / 2.0f;

  // Apply impulses directly to velocity
  //this.Velocity += this.queuedImpulses / this.Mass;

  // Integrate into position
  translation = this.Velocity * delta;

  // Apply second of the force scaled by time
  this.Velocity += acceleration * delta / 2.0f;

  // Finally, queued movements (root motion, etc.) go directly into translation
  translation += this.queuedMovement;
}

```

Gravity is a force, applied each tick as `this.forces += Vector3(0, -9.81, 0) * this.Mass)`. The jump is an impulse added once as `this.impulses += Vector3(0, 6.264, 0)`.

**Where does my mistake lie?**

Adding the impulse directly to `this.Velocity` instead of converting it to a force *quadruples* the jump height, which equally puzzles me.

# Answer
**F=MA**. Or, Force = Mass * Acceleration.

It appears you're dividing out the mass from your queued forces and impulses to deal with just acceleration, but you're not putting the mass back in when you calculate the force to be applied to the object. And I suspect the mass of your character is equal to 2?

```
this.Velocity += acceleration * delta / 2.0f;

```

should be

```
this.Velocity += (acceleration * mass) * delta / 2.0f;

```

You can also just not divide out the mass and just sum up forces instead of accelerations.

---

I wrote a quick test method to see this in action:

```
    static void Test()
    {
        float delta = 1f/120f;
        float height = .001f;
        float impulse = 6.264f;
        float gravity = -9.81f;
        float mass = 2f;
        float velocity = 0;

        float peakHeight = 0;
        while (height > 0)
        {
            float acceleration = gravity/mass;
            float impulses = impulse/mass;
            impulse = 0;
            acceleration += impulses/delta;
            velocity += (acceleration*mass)*delta/2f;

            height += velocity*delta;

            if (height > peakHeight)
                peakHeight = height;

            velocity += (acceleration*mass)*delta/2f;
        }

        Console.WriteLine("PeakHeight: " + peakHeight);
    }

```

Which outputs:

> PeakHeight: 1.974736
> 1 votes

---
Tags: c#, physics, mathematics, platformer, jumping
---


title: Only subtract velocity on one axis

text:
# Question
Title: Only subtract velocity on one axis
I'm really slow in uptaking this! I have a GameObject with a Rigidbody. Now I add via AddForce a velocity to the y-axis. But after that, I want to lerp it to zero. But how? My problem is, that I use the velocity also for steering my GameObject

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

[RequireComponent(typeof(Rigidbody))]
public class PlayerController : MonoBehaviour {

[Header("Movement")]
[SerializeField] private float speed;
[SerializeField] private float steeringPower;
[SerializeField] private float jumpHeigt;

[Header("Physics")]
[SerializeField] private float gravity;

private Rigidbody rigid;

void Start () {
    rigid = GetComponent<Rigidbody> ();
}

void Update () {
    if (Input.GetKeyDown(KeyCode.UpArrow)) {
        rigid.AddForce (Vector3.up * jumpHeigt);
    } else if (Input.GetKeyDown(KeyCode.DownArrow)) {
        rigid.AddForce (Vector3.down * jumpHeigt);
    }
}

void FixedUpdate () {
    rigid.velocity = new Vector3 (Input.GetAxisRaw ("Horizontal") * steeringPower, rigid.velocity.y, speed);

    //lerp rigid.velocity.y to zero here
}
}

```

# Answer
I'd suggest you don't do a Lerp, since that's really best for changing from one value to another over a certain amount of time. It doesn't deal with external changes simply, you'd have to manage that manually.

You essentially want gravity, or some constant force pulling down.

```
void FixedUpdate () {
    float yValue = rigid.velocity.y - (gravity * Time.fixedDeltaTime);

    rigid.velocity = new Vector3 (
                 Input.GetAxisRaw ("Horizontal") * steeringPower,
                 yValue,
                 speed);
}

```
> 1 votes

# Answer
If I understand correctly your question :

You basically want your player to **move** on the x and be able to **jump**(up/down) on the y, while costantly **sliding** along z.

Since you want to lerp y velocity to 0, and you can actually jump down, I guess you don't need gravity. Make sure to turn off gravity on your rigidbody. You might want to add some **drag** to it aswell, to avoid other rigidbodies to push your player too much.

Hope this can help you.

*(Note: I changed the jump input block a little bit while i was testing the code, just change it back if you don't want that)*

```
[RequireComponent(typeof(Rigidbody))]
public class PlayerController : MonoBehaviour
{

[Header("Movement")]
[SerializeField]
private float speed;
[SerializeField]
private float steeringPower;
[SerializeField]
private float jumpHeigth;
[SerializeField]
private float jumpSpeed;

[Header("Physics")]
[SerializeField]
private float gravity;

private Rigidbody rigid;

void Start()
{
    rigid = GetComponent<Rigidbody>();
}

float jumpForce;

void Update()
{
    // Added this to make sure the player completed the current jump.
    // Remove it if you don't need it.
    if (Mathf.Abs(jumpForce)<1f)
    {
        if (Input.GetKeyDown(KeyCode.UpArrow))
        {
            jumpForce = jumpHeigth;
        }
        else if (Input.GetKeyDown(KeyCode.DownArrow))
        {
            jumpForce = -jumpHeigth;
        }
    }

}

void FixedUpdate()
{

    Vector3 offset = new Vector3(Input.GetAxis("Horizontal") * steeringPower, jumpForce, speed) * Time.fixedDeltaTime;

    // Move the player by the offset value
    rigid.position += offset;

    // Gradually lerp jump force to 0 ...
    // (this one is not accurate, it will not cover the whole jump distance)
    // jumpForce *= .95f;

    // ...or move it contantly towards 0
    jumpForce = Mathf.MoveTowards(jumpForce, 0f, jumpSpeed * Time.fixedDeltaTime);

}
}

```
> 0 votes

---
Tags: unity, c#, physics, rigidbody
---


title: Unity: Interrupting Animations

text:
# Question
Title: Unity: Interrupting Animations
When I interrupt an Animator Controller during an Animation and reopen it the Armature gets stuck (more or less) at the point where the previous Animation was interrupted. How can I safely and instantly quit an animation without destroying it?

Please watch the Video to fully comprehend the problem: https://youtu.be/O9X5SBATHRw

Screenshot of Problem:

Screenshot of Animator Controller:

Part of the Weapon Switch Script:

```
disableWeaponModel(weaponNameList[activeWeapon]); //Disable active Weapon Model

if (holsteredWeapon == -1) //If player carries only 1 weapon
    holsteredWeapon = activeWeapon; //Active Weapon is holstered
else //Player already carries 2 weapons
    actionDropGun(); //Active Weapon is thrown (New LOD generated)

activeWeapon = getWeaponIDfromLOD(targetName); //Active Weapon is set to Target LOD

setWeaponVars(activeWeapon); //Set all variables to the active Weapon
setWeaponModel(weaponNameList[activeWeapon]); //Set Weapon Model to the active Weapon
setAnimator(weaponNameList[activeWeapon]); //Set Animations to the active Weapon

```

setAnimator(string name) Function from above (last code line):

```
void setAnimator(string name)
{
    //Add new guns here
    if (name == "MP5A3")
        currentWeaponAnimation = MP5A3_Animation;
    else if (name == "Rpk-74")
        currentWeaponAnimation = Rpk74_Animation;
    else if (name == "Skorpion")
        currentWeaponAnimation = Skorpion_Animation;
}

```

Variables from setAnimator(string name):

# Answer
> 1 votes
Turning on **Optimize Game Objects** on the Rig tab of your model fixed this for me (Generic/Humanoid animations only). The only problem is that it won't work for you, if you actually need the model bones as gameobjects.

---
Tags: unity, animation
---


title: RPC Movement in UE4

text:
# Question
Title: RPC Movement in UE4
Having some issues with grapple hook movement over the network. I tried a few different methods with the RPC's, but as of now, when the client presses grapple, they simply shake in place.

Here is my current blueprint setup for the grapple.

and here is the RPC setup.

What am I doing wrong?

Thanks!

# Answer
> 1 votes
Unreal uses the Client-Server model, so when making a multiplayer game, the server is king - it should be the only place that you try to perform game actions.

The GameMode is key. GameMode is where you define the rules of the game - match time limit, spawn rules, and so on. It is also the place that determines player actions - who shot who, how much damage is done, player respawns. Only the server runs the GameMode, clients cannot see it.

So if clients cannot see the GameMode, how does shooting work? The answer is in Replication - specifically, replicating the Player Character. If a blueprint is replicated, it is sent to the server every update cycle. It is important to note that, the bigger the blueprint that is being replicated, the more network traffic you generate. Any variables that your blueprint needs to use must also be replicated, otherwise your server-side logic will fail.

Let's say your player needs to shoot. For this behavior, the Player Character blueprint should contain (at least) three custom events and one Input event. The Input event is called when the player tries to shoot, and executes one of the custom events; I usually name my events with \_Server, \_Client, \_Multicast suffixes so I don't get confused.

So in the shooting case, the Input event calls a custom event called PlayerShoot\_Server - this is in the Player Character blueprint. This custom event is marked as "Run On Server", and contains all the validation logic: does player have enough ammo, is the weapon valid, is player doing something that would prevent firing. If these checks pass, a linetrace is done (for instant hit weapons) from the gun barrel, to see if anything was hit. If anything *was* hit, the custom event calls a couple of things: 1. PlayerShoot\_Client is called that updates the firing player's ammo counts, and 2. PlayerHit\_Client is run on the damaged client to remove health as appropriate.

PlayerShoot\_Client is marked as "Run On Owning Client", and handles anything specific to the firing player - hit marker sounds, UI updates, inventory updates, and so on.

But what about weapon firing sounds, impact particles, firing particles and the like? Another custom event called PlayerShoot\_Multicast, marked as "Multicast", is broadcast to all clients in the game. This event should play all the visual and sound effects; each client would check their sound attenuations and line-of-sight to determine if the effects are actually seen and heard.

This is actually a very simple system (although the answer length might make it seem otherwise). The important parts are: 1. Server is king, it should decide everything about the game 2. Run on Owning Client is for updating the player who did the action 3. Multicast is for telling everyone else about the player's action

---
Tags: physics, networking, multiplayer, unreal-4
---


# Question
Title: Why does my disable z-depth test shader do not work?
I wrote the following shader which purpose is to force draw a mesh over the rest, regardless z-depth :

```
Shader "Custom/AlwaysOnTop"
{
    SubShader
    {
        Tags { "Queue"="Overlay" "RenderType"="Overlay" }
        ZTest Always

        CGPROGRAM
        #pragma surface surf Lambert

        struct Input
        {
            float4 color : COLOR;
        };

        void surf (Input IN, inout SurfaceOutput o)
        {
            o.Albedo = 1;
        }
        ENDCG
    }
    Fallback "Diffuse"
}

```

It works great, however transparent objects still get draw over it. Setting the queue as Overlay should have solved the problem.

* White = AlwaysOnTop shader
* Green = Transparent diffuse
* Blue = Diffuse

The left face of the white cube should be white, no tinted in green.

# Answer
> 1 votes
If you want something overlaying everything the easiest way is to create a second camera with identical settings and position to the first except for:

* A higher depth. (it's the camera render order, to render after the first camera.)
* Clear flags set to depth only, this will render everything on top.
* Culling mask set only to the object layer you want to render.
* Remove the same layer from the 1st camera's culling mask.
* Remove the audio listeners, UI rendering, and other extra components from the 2nd camera.

see: https://docs.unity3d.com/Manual/Layers.html

Easiest way to move them together is to make the 2nd camera a child of the 1st. If you change the camera's FOV or other effects you'll need to add a small script to copy the values over.

This is a method that works with Unity 4 as well (and more likely to work with future versions too).

# Answer
> 0 votes
Your material may have too low `Render Queue` value. Sometimes the material overrides the value it gets from the shader. Try setting it for example to 5000 or so, and see which values work for you. Too low value will render transparent objects after your overlayed object.

---
Tags: unity, shaders, depth
---


# Question
Title: Objects appear invisible to camera during animation
Depending on the camera angle and the distance of the animated Objects to the camera they flicked in and out of view.

Since I have no idea what could be causing this and didn't manage to limit the problem other than moving the camera please state what valuable information I should supply.

The Model is parented to a camera which is parented to a character controller. The Animation is undisrupted during scene view. If I move the camera further away from the model, or look in a different direction the models remain visible throughout the entire animation.

I have recordet the incident: https://youtu.be/b66N80\_Fg\_g

As you can see the right hand, the magazine and at one point even the weapon disappears from view.

# Answer
When meshes disappear randomly from certain perspectives (or as in your case during animation), the issue might be caused by view frustum culling.

View frustum culling is a CPU optimization, where all objects outside of the volume captured by the camera are discarded and won't be rendered. To determine whether an object is located inside or outside the camera's frustum, all bounding volumes are tested against the camera's frustum volume.

If you face a situation where you expect an object to be rendered but it gets culled, check the near and far clipping planes of your camera and also the bounding volume of your meshes. For imported meshes the bounding volume might not be set up properly and you need to call `mesh.RecalculateBounds ()` or set the bounding volume of the mesh manually using the `mesh.bounds` property.

If you have an animated mesh, you should set the bounds in a way that they represent the maximum bounding volume so that you can be sure that culling is performed correctly in any animation frame.
> 3 votes

# Answer
I have recently met Objects where mesh.RecalculateBounds () doesn't work anymore. Another solution: Resize the Bound Extents to something ridiculously high and the Object will always appear in the camera view.
> 0 votes

---
Tags: unity
---


# Question
Title: How to use delta time when your speed needs to be always the same?
I am using Bezier curve, and that curve positions the entity when the step reaches 1, so anthing between 0 and 1 is his travelling distance.

So in my game, according to the speed I set, I want the entity move `0.01f` steps towards the target, this means, the entity will reach the target position after 100 steps.

But if I will use delta time, this will change from time to time.

How can I use delta time correctly in this case?

I'm using libGDX.

# Answer
> 1 votes
The delta time is a measurement of time since the last frame and is best used when you want to change things based on time(and smooth across all platforms). So if you wanted your entity to move from the start of the curve to the end of the curve over 15 seconds you would increase the position by (deltaTime / 15) This makes the movement of the entity smooth even on platforms that are unable to keep the 60 fps frame rate.

If you used a static step value like 0.01f then on platforms that get 10 fps you will have an entity that takes 10 seconds to complete the curve. Whereas a platform that gets 60fps will have the entity in less than 2 seconds.

So, if you game requires the unit to compete the curve over the same amount of time you would use the deltaTime as a step value and if your game doesn't require the same performance across platforms you would just use a single static value like 0.01f.

Another option is to use a mixture of the two to limit the max step time so slower platforms aren't playing in slow motion. e.g.

```
if(deltaTime > 0.05f){ // frame took longer than expected
   stepTime = 0.03f; // limit stepTime to 0.03f
}else{
    stepTime = deltaTime; // deltaTime is within acceptable range
}

```

---
Tags: movement, timestep
---


# Question
Title: Two BitmapFonts from one .ttf font using AssetManager
I'm trying to start using AssetManager in my game. Previously I used to generate two BitmapFonts (bigger and smaller) from my .ttf file and it worked well. Here's how it looked in the code:

```
FreeTypeFontGenerator generatorRoboto = new FreeTypeFontGenerator(Gdx.files.internal("fonts/Roboto-Regular.ttf"));
FreeTypeFontGenerator.FreeTypeFontParameter params = new FreeTypeFontGenerator.FreeTypeFontParameter();
params.size = 80;
BitmapFont robotoFont = generatorRoboto.generateFont(params);
robotoFont.getData().setScale(0.5f);
robotoFont.getRegion().getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
params.size = 40;
BitmapFont smallerFont = generatorRoboto.generateFont(params);
smallerFont.getData().setScale(0.6f);
smallerFont.getRegion().getTexture().setFilter(Texture.TextureFilter.Linear,
Texture.TextureFilter.Linear);

```

Then I add it to skin and use it.

```
skin.add("roboto-regular-font", robotoFont, BitmapFont.class);
skin.add("roboto-smaller-font", smallerFont, BitmapFont.class);

```

It works well, but now I'm trying to use it with AssetManager (according to documentation):

```
FreeTypeFontLoaderParameter robotoFontLP = new FreeTypeFontLoaderParameter();
robotoFontLP.fontFileName = "fonts/Roboto-Regular.ttf";
robotoFontLP.fontParameters.size = 80;
manager.load("fonts/Roboto-Regular.ttf", BitmapFont.class, robotoFontLP);
manager.finishLoading();

BitmapFont robotoFontBig = manager.get("fonts/Roboto-Regular.ttf", BitmapFont.class);
robotoFontBig.getRegion().getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
robotoFontBig.getData().setScale(0.5f);
BitmapFont robotoFontSmall = manager.get("fonts/Roboto-Regular.ttf", BitmapFont.class);
robotoFontSmall.getRegion().getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
robotoFontSmall.getData().setScale(0.15f);

skin.add("roboto-regular-font", robotoFontBig, BitmapFont.class);
skin.add("roboto-smaller-font", robotoFontSmall, BitmapFont.class);

```

But it doesn't work, LibGDX treat them as the same font. What am I doing wrong?

# Answer
I believe this could be an issue with the AssetManager as it uses an objectMap which maps loaded objects to the string used to load them. In this case you're loading the font and the assetManager is storing it in it's objectMap under the key "fonts/Roboto-Regular.ttf", then when you load your font again with second set of parameters the previous font is overwritten.

I found this workaround from this page.

> One solution would be to pass an id as the name, and also have parameters that get passed to the TTF loader that actually contains the filename.

This example shows how to use the parameter file to define font file name leaving the name in the load method to be used purely as a key. Adapted from the libgdx ttf test found here

```
    FreeTypeFontLoaderParameter robotoFontBigParam = new FreeTypeFontLoaderParameter();
    size1Params.fontFileName = "fonts/Roboto-Regular.ttf";
    size1Params.fontParameters.size = 40;
    manager.load("size40.ttf", BitmapFont.class, robotoFontBigParam );

    FreeTypeFontLoaderParameter robotoFontSmallParam= new FreeTypeFontLoaderParameter();
    size2Params.fontFileName = "fonts/Roboto-Regular.ttf";
    size2Params.fontParameters.size = 12;
    manager.load("size12.ttf", BitmapFont.class, robotoFontSmallParam);

```
> 4 votes

---
Tags: java, libgdx, fonts, asset-management
---


# Question
Title: Moving spotlight (or object) between 2 coordinates (image included)
Given the origin position and direction for a spotlight.
How can I smoothly move a spotlight between two 3D coordinates?
Please use the picture below so I can easily comprehend this. I would like to move the direction of the spotlight from point A to B, for example.
**All values/vectors are in 3D.**

EDIT: How should I properly do this, if given only current **position** and **unit direction** of spotlight?

# Answer
> 1 votes
Your spotlight direction should be of unit length, therefore, you can perform interpolation.

Method A - Linear:

Take the unit direction of spotlight to point A, then the direction of the light to point B. Then decide how quickly you want to rotate the light. Let's say over 5 seconds. unit(DirB - DirA)/5 = your rotPerS.

Then: lightDir+=rotPerS * deltaTime, or lightDir-=rotDir * deltaTime to rotate back.

Method B - Spherical:

Compute the axis you wish to rotate the direction of the light on. Get the dot product of DirA and DirB. This is the cosine of the angle between them, on that axis. To compute the axis, perform a cross product of DirA and DirB.

Decide on your rotation speed again. You now have the rotation angle per second, and the axis upon which you must rotate, and how long it will take to rotate.

Then you can use a quaternion to rotate the direction of the light based on angle/axis, by multiplying the direction vector by the quaternion.

Like so:

axis = cross(dirA,DirB);

angle = dot(DirA,DirB);

anglePerSec = angle/Duration; (radians)

rotateQ = Quaternion(anglePerSec * deltaTime,axis);

lightDir = rotateQ * lightDir;

# Answer
> 1 votes
If you use Unity 3D Create an empty object and make it move from A to B any way you want, you can use a "lerp" for this:

```
float smooth = 0
void Update () {
         smooth += (Time.deltatime) * speed;
         transform.position = Vector3.Lerp (A.position, B.position, smooth);
     }

```

The "smooth" values they serve range from 0 to 1, less than zero takes it as zero, greater than 1 takes it as 1.

Then make the "spotlight" look at your moving object.

```
public class ExampleClass: MonoBehaviour
{
     public Transform target;

     void Update ()
     {
         // Rotate the spotlight every frame so it keeps looking at the target
         transform.LookAt (target);
     }
}

```

---
Tags: 3d
---


# Question
Title: 2D collision > rectangles can glitch into each other
I have implemented a simple rectangle based collsion detection where you can "slide" around the edges on diagonal movement. Works fine but the thing is, it is somehow possible that e.g. the player (rectangle) glitches into the one of a collision object. It seems, that it appears only when the player "slides" around the corners. I suspect that if the player walks around the corners that the movement direction (Vector2) cuts off the corner and at some point glitches into the collision rectangle.

I hope I've explained the problem somehow understandable?

The code looks like this:

The UpdateCall recieves the playerMovement from the keyboard input

```
public void UpdatePlayer(GameTime gameTime, Vector2 playerMovement)
{
    //...
    playerMovement = CalculatePlayerMovement(Vector2.Normalize(playerMovement) * movementspeed);
    if (playerMovement.Length() != 0)
        MoveBy(playerMovement);
    //...
}

```

The CalculatePlayerMovement-Method checks world bounds, collision objects and so on. Depending on what side the collsion happens, the x- or y-movement will be zeroed.

```
private Vector2 CalculatePlayerMovement(Vector2 movement)
{
    Rectangle destRect = new Rectangle(BoundingBox.X + (int)movement.X, BoundingBox.Y + (int)movement.Y, Width, Height);
    Vector2 returnValue = movement;
    //...
    foreach (Rectangle r in TileMap.collisionObjects)
    {
         if (destRect.Intersects(r))
         {
             string collsionSide = GetCollisionSide(destRect, r);
             if (collsionSide == "top" || collsionSide == "bottom")
                 returnValue.Y = 0;
             if (collsionSide == "left" || collsionSide == "right")
                 returnValue.X = 0;
         }
     }
    //...
}

```

Finally the check itself. I took this part from HERE since I was not sure what the best way would be.

```
private string GetCollisionSide(Rectangle destRect, Rectangle r)
{
    float w = (destRect.Width + r.Width) / 2;
    float h = (destRect.Height + r.Height) / 2;
    float dx = destRect.Center.X - r.Center.X;
    float dy = destRect.Center.Y - r.Center.Y;

    if (Math.Abs(dx) <= w && Math.Abs(dy) <= h)
    {
        float wy = w * dy;
        float hx = h * dx;

        if (wy > hx)
        {
           if (wy > -hx)
                return "top";
            else
                return "right";
        }
        else if (wy < hx)
        {
            if (wy > -hx)
                return "left";
            else
                return "bottom";
        }
    }
    return "";
}

```

I am not sure where the problem is, but it is probably something I don't see myself.

# Answer
I believe you should consider these 2 cases separately:

1 - The objects are colliding and are moving towards each other.

2 - The objects are colliding and are moving away from each other.

In the second case, you should not restrict the movement. You can still apply a position correction, in order to eliminate the overlapping. But you should allow velocity.
> 1 votes

---
Tags: collision-detection
---


title: How can i make my game GUI look nicer?

text:
# Question
Title: How can i make my game GUI look nicer?
Im currently developing my first little android game. Its a casual game, which people can play when they are waiting for the bus or something like that.

All the other games in the playstores are looking very simple and still beautifull or addicting. So how can i improve my UI ? Are there any guidelines ?

The gallery contains several images of my GUI. Some are the same, but with other colors. Thats because i have an ingame shop, where the user can unlock new color themes.

Open Imgur Gallery

# Answer
I think it already looks real nice! If you want it to look more complex (though I don't see a reason why) you could add borders to the geometric shapes that are darker in colour, eg a a darker border around the circles. You can play with the thickness of said border, you can make things stand out as foreground objects by making it thick and real dark, and you can make things stand out as background objects by making the border thin and slightly lighter. They kind of do that in "Bindin of Isaac"

But yet again I already think it looks nice!

Not gonna upvote your question though because it's very subjective, we don't deal with those kind of open questions here on SE
> 1 votes

# Answer
To Agree with Derpinator, I also think it looks quite nice already. But to improve your flat-like interface further, you could try experimenting more with different colour gradients to provide some more flair to your designs. Also maybe experiment with different background colours as well. Currently you are using both black and dark grey in your designs, which are somewhat boring colours to look at, maybe other colours will look more lively in that regard.

Keep up the good work!
> 0 votes

---
Tags: graphics, gui
---


# Question
Title: Unity - occlude a transparent part of a generated mesh with a non transparent part
I am making a procedurally generated voxel world made of blocks. Some of the blocks have non cubic shapes (ramps), and some of the blocks are transparent (water).

All the blocks are part of the same mesh. The mesh is made out of 2 sub-meshes, both using unity's standard shader, one with the opaque rendering mode, while the other uses the transparent mode.

I want to allow for the water block to render at the same location as a ramp block, with the water correctly appearing above the ground.

Here is an image of a ramp block next to a water block:

When I combine them however, I get the following effect:

I have set the transparent Shader to write to the Z-Buffer using:

```
meshRenderer.materials[1].SetInt("_ZWrite", 1);

```

(Otherwise only the water block is visible)

Here is my code for rendering the mesh:

```
filter.mesh.Clear();
filter.mesh.vertices = meshData.vertices.ToArray();

filter.mesh.subMeshCount = 2;
filter.mesh.SetTriangles(meshData.triangles.ToArray(), 0);
filter.mesh.SetTriangles(meshData.transparentTriangles.ToArray(), 1);

filter.mesh.uv = meshData.uv.ToArray();
filter.mesh.RecalculateNormals();

```

meshData.triangles contains the triangles of the opaque blocks, and meshData.transparentTriangles contains the triangles of the transparent blocks.

I have tried to slightly offset the water block, to avoid having 2 triangles at the exact same position, and that almost gives me the effect I want, except for some reason the opaque block becomes transparent, even though it's triangles are rendered by the opaque shader:

https:// i.stack.imgur.com/zlSKl .png

(The link is weird since it does not allow me to post a 3rd image link as I dont have enough reputation, please just remove the spaces)

Any help with solving the issue would be greatly appreciated.

Thank you.

# Answer
I solved it by placing the water block at the same position as the ramp block, but scaling the water block to be 99.9% of it's original size, which solved the z-fighting issue.

Here is how it looks:
> 0 votes

---
Tags: unity, shaders, 3d-meshes, mesh, transparency
---


# Question
Title: Describing the spherical cap intersection between a spherical shell and a solid ball
I have:

* an infinitely thin sphere shell with center `O1` and radius `R1`, and
* a solid ball with center `O2` and radius `R2`

Now i need a way to describe their intersection.

For example, for 2 spheres (shells), the intersection is a circle, and I can find the equation (the mathematical description) of that circle.

For the sphere and ball i know the intersection is a spherical cap, but I don't know if it is possible to find its analytical or algebraic expression.

I can determine the base (outer circle) of the spherical segment, using the sphere-sphere intersection math described here .

But how would I extend that to the full dish/bowl shape of the spherical cap?

# Answer
> 0 votes
If the distance between the center of the 2 hyperspheres is less than 2 times the radius of them, then they intersect.

So, if the points are defined like this: `(x1, y1, z1, w1)`, `(x2, y2, z2, w2)` then the intersection check is

```
√((x1 - x2)² + (y1 - y2)² + (z1 - z2)² + (w1 - w2)²) < 2 * radius

```

# Answer
> 0 votes
This follows pretty directly from the sphere-sphere formulas in my earlier answer, so I won't repeat the full breakdown here.

Once you've verified that the sphere and ball surfaces do intersect, you can use those formulas to find the radius of the circular intersection `r_i` and the signed proportion of the distance to the intersection plane `h`:

Next we can form a vector pointing to the center of the sphere cap, call it `peak`:

```
peak = normalize(c2 - c1)

```

The cap has an angular extent `phi_max`, measured in radians from the peak of the cap to the outer rim. We can find it using the 2-argument arctangent function:

```
phi_max = atan2(r_i, hd)

```

Now if we augment `peak` with two more mutually perpendicular unit vectors `u` and `v` to form a 3D basis (or equivalently, a transformation matrix) we can express any point in the spherical cap like so:

```
0 <= theta < 2pi
0 <= phi <= phi_max

point = c_1 + r_1 * (
           peak * cos(phi)
         + u * sin(phi) * cos(theta)
         + v * sin(phi) * sin(theta)
       )

```

If the sphere is fully contained in the ball, then you can pick any arbitrary basis vectors and choose `phi_max = pi` to express the entire surface using this same parametrization.

---

Extending this to 4-dimensional space is hard to picture, but the math follows a similar pattern with a fourth orthonormal basis vector w:

```
0 <= theta <= 2pi
0 <= beta <= pi
0 <= phi <= phi_max

point = c+1+ r_1 * (
        peak * cos(phi)
      + u * sin(phi) * sin(beta) * cos(theta)
      + v * sin(phi) * sin(beta) * sin(theta)
      + w * sin(phi) * cos(beta)
     )

```

You can confirm that for any value of `point`, `(point - c_1)^2 = r_1^2` and `(point - c_2)^2 <= r_2^2`

In the same way that in the 3D case, the spherical cap can be thought of as a series of nested circles, varying in radius from a point at the peak of the cap to the outer rim; in 3D we can think of the hyperspherical cap as a series of nested spheres.

---
Tags: geometry, sphere
---


title: Unity3D - Button Slicing Problem

text:
# Question
Title: Unity3D - Button Slicing Problem
I'm having trouble getting my button to appear correctly, as you can see in the image below, the right and top sides are stretched out and not displaying properly. I cannot figure out if this is a problem with the image itself or something wrong in the way I'm setting up the button.

Here are the settings in the inspector window:

Here is the original image:

UPDATE: So everything looked fine when I just opened up Unity, so I tried to figure out what I did last time for it to make this switch. It happens when I build and export the scene to my Android device.

# Answer
Your button is set up correctly and the image is fine it works in a test project of mine and scales properly with all resolutions.

Check the canvas scaler and make sure you are set to scale with screen size. if for some reason that does not work drop it into a panel and scale the panel to custom anchor you min and max and it should scale no problem in every resolution.
> 2 votes

# Answer
Tweaking the "Pixels Per Unit" ratio from 100 down to 1, for the asset in question, solved this for me.

Until I did this, all I got was a square / rect without seeing the 8 boundaries of the 9-sliced image... i.e. all I got was the central fill, no 9-slicing as such.
> 0 votes

---
Tags: unity
---


# Question
Title: "Plugins colliding with each other" when building Unity scene for WebGL
I have a simple scene that looks like this:

It's using the free DefKit plugin to make the bunny a soft-body.

This works fine in Unity, I can play the scene and it's great.

However I can't build for WebGL. I'm getting the following error:

```
Plugin 'DefKit.dll' is used from several locations:
 Assets/AssetStore/DefKit/Plugins/x86/DefKit.dll would be copied to <PluginPath>/DefKit.dll
 Assets/AssetStore/DefKit/Plugins/x86_64/DefKit.dll would be copied to <PluginPath>/DefKit.dll
Plugin 'UTet.dll' is used from several locations:
 Assets/AssetStore/DefKit/Plugins/x86_64/UTet.dll would be copied to <PluginPath>/UTet.dll
 Assets/AssetStore/DefKit/Plugins/x86/UTet.dll would be copied to <PluginPath>/UTet.dll
Please fix plugin settings and try again.

UnityEditor.Modules.DefaultPluginImporterExtension:CheckFileCollisions(String)
UnityEditorInternal.PluginsHelper:CheckFileCollisions(BuildTarget) (at C:/buildslave/unity/build/Editor/Mono/Plugins/PluginsHelper.cs:25)
UnityEditor.HostView:OnGUI()

```

and then it says

```
Plugins colliding with each other.

```

I'm really not sure how to go about fixing this. Any recommendations would be highly appreciated.

---

**update**

after deleting the /x86 folder as advised in an answer, I get this error when building:

```
FileNotFoundException: Could not find file "E:\platform_fighter\platform-fighter\Temp\StagingArea\Data\Native\build.asm.js".
System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean anonymous, FileOptions options) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.IO/FileStream.cs:305)
System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share)
(wrapper remoting-invoke-with-check) System.IO.FileStream:.ctor (string,System.IO.FileMode,System.IO.FileAccess,System.IO.FileShare)
System.IO.File.OpenRead (System.String path) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.IO/File.cs:363)
System.IO.StreamReader..ctor (System.String path, System.Text.Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.IO/StreamReader.cs:167)
System.IO.StreamReader..ctor (System.String path, System.Text.Encoding encoding)
(wrapper remoting-invoke-with-check) System.IO.StreamReader:.ctor (string,System.Text.Encoding)
System.IO.File.ReadAllText (System.String path, System.Text.Encoding encoding) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.IO/File.cs:587)
System.IO.File.ReadAllText (System.String path) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.IO/File.cs:582)
UnityEditor.WebGL.CodeAnalysisUtils.ReplaceDuplicates (System.String builtCodePath, Int32 interations) (at /Users/builduser/buildslave/unity/build/PlatformDependent/WebGL/Extensions/Unity.WebGL.extensions/CodeAnalysisUtils.cs:145)
UnityEditor.WebGL.WebGlBuildPostprocessor.PostProcess (BuildPostProcessArgs args) (at /Users/builduser/buildslave/unity/build/PlatformDependent/WebGL/Extensions/Unity.WebGL.extensions/BuildPostprocessor.cs:589)
UnityEditor.PostprocessBuildPlayer.Postprocess (BuildTarget target, System.String installPath, System.String companyName, System.String productName, Int32 width, Int32 height, System.String downloadWebplayerUrl, System.String manualDownloadWebplayerUrl, BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.BuildReporting.BuildReport report) (at C:/buildslave/unity/build/Editor/Mono/BuildPipeline/PostprocessBuildPlayer.cs:186)
UnityEditor.HostView:OnGUI()

```

---

**update 2**

another error!

```
Exception: E:\Unity5.0.0\Unity\Editor\Data\il2cpp/build/il2cpp.exe did not run properly!
UnityEditorInternal.Runner.RunManagedProgram (System.String exe, System.String args, System.String workingDirectory, UnityEditor.Scripting.Compilers.CompilerOutputParserBase parser, System.Action`1 setupStartInfo) (at C:/buildslave/unity/build/Editor/Mono/BuildPipeline/BuildUtils.cs:98)
UnityEditorInternal.IL2CPPBuilder.RunIl2CppWithArguments (System.Collections.Generic.List`1 arguments, System.Action`1 setupStartInfo, System.String workingDirectory) (at C:/buildslave/unity/build/Editor/Mono/BuildPipeline/Il2Cpp/IL2CPPUtils.cs:281)
UnityEditorInternal.IL2CPPBuilder.ConvertPlayerDlltoCpp (ICollection`1 userAssemblies, System.String outputDirectory, System.String workingDirectory) (at C:/buildslave/unity/build/Editor/Mono/BuildPipeline/Il2Cpp/IL2CPPUtils.cs:272)
UnityEditorInternal.IL2CPPBuilder.Run () (at C:/buildslave/unity/build/Editor/Mono/BuildPipeline/Il2Cpp/IL2CPPUtils.cs:126)
UnityEditorInternal.IL2CPPUtils.RunIl2Cpp (System.String stagingAreaData, IIl2CppPlatformProvider platformProvider, System.Action`1 modifyOutputBeforeCompile, UnityEditor.RuntimeClassRegistry runtimeClassRegistry, Boolean developmentBuild) (at C:/buildslave/unity/build/Editor/Mono/BuildPipeline/Il2Cpp/IL2CPPUtils.cs:39)
UnityEditor.WebGL.WebGlBuildPostprocessor.PostProcess (BuildPostProcessArgs args) (at /Users/builduser/buildslave/unity/build/PlatformDependent/WebGL/Extensions/Unity.WebGL.extensions/BuildPostprocessor.cs:560)
UnityEditor.PostprocessBuildPlayer.Postprocess (BuildTarget target, System.String installPath, System.String companyName, System.String productName, Int32 width, Int32 height, System.String downloadWebplayerUrl, System.String manualDownloadWebplayerUrl, BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.BuildReporting.BuildReport report) (at C:/buildslave/unity/build/Editor/Mono/BuildPipeline/PostprocessBuildPlayer.cs:186)
UnityEditor.HostView:OnGUI()

```

# Answer
For a quick fix, delete the x86 directories.

* `Assets/AssetStore/DefKit/Plugins/x86/`
* `Assets/AssetStore/DefKit/Plugins/x86/`

The problem is that WebGL is trying to copy the same dll (but different versions) into one location. It doesn't know which one to use. In this case x86 is likely for legacy support when building to other targets, you can remove it.
> 2 votes

---
Tags: unity, soft-body-dynamics
---


# Question
Title: Cannot implicitly convert type object[] to UnityEngine.GameObject[]
So, I cannot implicitly convert type object\[\] to UnityEngine.GameObject\[\]. But why? As far I know, are all types a inheritanced types of object. So, for my logic, I could put a GameObject array in a object array. That's why, this should work:

```
spawnedObjects = FindObjectOfType<Tools> ().AddObjectToArray (spawnedObjects, go);

```

//

```
public object[] AddObjectToArray(object[] _array, object _toAdd){
    if (_array.GetType() == _toAdd.GetType()) {
        object[] a = new object[_array.Length + 1];
        a = _array;
        a [a.Length] = _toAdd;
        return a;
    } else {
        Debug.LogWarning ("The object that should be added to the array have to be the same type as the arrays type. Initially array was retuned!");
        return _array;
    }
}

```

But yeah, it won't do

# Answer
> 2 votes
> I cannot implicitly convert type object\[\] to UnityEngine.GameObject\[\]. But why?

Because allowing it subverts the type system. Assume want you want is allowed, and then consider this:

```
object[] a = ...;
GameObject[] b = a;

```

Arrays are reference types, so `a` and `b` refer to the same actual array. Now consider if you did:

```
a[1] = new object();

```

This is legal, because `a` is `object[]`. But now `b[1]` is not a `GameObject`, it's a plain `object`. You have broken the type system.

Consequently, you are not permitted to make this implicit cast. It looks like you are *attempting* to prevent this occurrence at runtime in your code, but the compiler doesn't care. The compiler will try, and succeed, in stopping this at compile-time.

---

Why don't you just use `List<GameObject>`? It will let you append new `GameObject`s to the list more efficiently than you're doing by recreating the entire array (and with fewer bugs). For example:

```
List<GameObject> spawnedObjects;

...

spawnedObjects.Add(go);

```

---
Tags: objects, inheritance
---


# Question
Title: Pros and cons of loading DirectX DLLs directly?
I have been looking at the source code of various commercial games, and I have noticed that a lot of them load video card/input DLLs directly using LoadLibrary().

I wanted to mod one, but also make my own engine, so I was wondering what would be the benefits of loading DirectX 11 DLLs directly, as opposed to link the program with .libs?

# Answer
> 3 votes
If the DLLs are loaded using a .lib your game will fail to launch if the DLLs are missing.

Loading DLLs using `LoadLibrary` lets you display a friendlier message on failure and allows you implement a fallback system to a previous version of DirectX if the latest is unavailable.

---
Tags: c++, directx, dll
---


# Question
Title: When/where should a game state transition take place?
I'm in the process of redesigning some of my state management code (there are several features I've grown to dislike in practice..) which was based on this tutorial and others. The issue I'm having right now has to do with state transitions.

Where and when should state transitions occur? Should they be executed immediately, or should they be delayed to the end of the current frame, after the current state has finished its work for that frame?

Let's say my states can implement `handleEvents`, `update`, `render`, `pause` and `resume` methods, among others that are not relevant for this question.

My thoughts so far are the following:

* If the transition is done at the end of the frame, then when I pause the game I might see an update during that same frame I clicked to pause. The Pause State will only appear after the current state has executed the rest of the frame (events, update and render). Perhaps that extra update should not have been done.
* If the transition is done immediately I have to be careful to not to delete the current state while it is still executing its method, let's assume the `handleEvents` method. But even so, if I were to pause a game in the `handleEvents` function, then the game would immediately pause and the game state `update` function would not be executed that frame.

The second options is more appealing to me, because as a player I would probably notice that extra bit of movement after pressing to pause the game. What if the player died during that frame? The delayed state change would be unwarranted. But then, the game state itself should probably disable updates if a game pause was requested.

On the other hand it might make more sense to delay state transitions to after the current state has fully executed its functions for the current frame. Maybe the Pause state should be a sub-state of the Game state and not a state of its own.

Is it simply a matter of preference or is one of the approaches clearly superior for a different reason?

# Answer
> 2 votes
I generally try to have a single location where the state can change: from the `update()` method of the state. This allows to see quickly where one state can go from there. This means that even if you have an event (in `handleEvents`) that would make it change state, delay that until the `update()`.

And I generally use a hybrid method: delayed switch.

Once you know you have to change the state, instead of asking the state machine to change state immediately, you place a request to change the state to another state. This allows you to finish running `State1::update()`, and cleanly go to `State2`.

Something that I have not seen mentioned in the tutorial you've linked to: `onEnter` and `onExit` methods. Each state has some code that needs to be executed *once* when you enter it, and *once* when you exit it. For instance: the graphics/data that need to be loaded/unloaded for that state, etc. should be done in these methods. The `update()` method is there for what's done every frame. I call it the 'steady-state' (yeah, that's a lot of "state").

Here is what I usually do; first the classes:

and here's how they interact:

Your main loop is calling the update method of your state machine, which is calling the onUpdate method of the current state. If that state realizes that it has to go to another state, it requests a change of state to it's owning state machine. The state machine does not change the state now, but waits until the current state's update method is done to change the state.

But it does not just change the states. Before doing so, it calls the `onExit` method on the current state, *then* changes the state to the new requested one, then call the `onEnter` method on the new (now current) state. This way, the next frame will be in a 'steady-state': no initialization to do, no set-up to do, and your 'render' method will correctly display stuff that relates to the new state, even if no update has been done in this new state yet.

---
Tags: c++, architecture, state
---