# Question
Title: Enum or Inheritance for event-based interaction?
I am currently considering two possibilities to a centralised interaction system within my game.

Consider that you want to produce different results for different types of objects within the game world - you interact with a signpost and dialogue appears, or interact with an item on the ground and it gets added to your inventory with a notification.

Essentially, I cannot decide whether it would be more efficient to implement such functionality all within one centralised place or to spread each function out over separate events.

---

**Option 1: Centralised**

This is what I have started coding. One *Interact* class which contains several "Types" of possible events in my game.

When the player "interacts" with an object implementing this script, it will implement the functionality that it is set to in the Editor. This means I drag and drop this Event Script onto a prefab and can automatically tweak its functionality within a couple of seconds and have it ready to go in the game world.

I have simplified the general consensus of my code into this block for readability:

```
public string eventName;

public enum EventType
{
    Movement = 0,
    Dialogue = 1,
    NPC = 2,
    ItemCollect = 3,
    Teleport = 4,
    Cutscene = 5,
    Switch = 6,
    Custom = 7
}

public EventType eventType;

/*
* #############################
* ##@@## INITIALIZATION ##@@##
* #############################
*
*/

private void Awake()
{
    SetupEvent(eventType);
}

public void Activate(bool calledFromTrigger = false)
{
    if (autoTrigger && !calledFromTrigger)
        return;

    Debug.Log("Activated " + name + "!");
    StartEvent(eventType);

}

private void StartEvent(EventType type)
{
    switch (type)
    {
        case EventType.Movement:
            MovePlatform();
            break;
        case EventType.Dialogue:
            break;
        case EventType.NPC:
            break;
        case EventType.ItemCollect:
            break;
        case EventType.Cutscene:
            break;
        case EventType.Switch:
            break;
        case EventType.Custom:
            break;
    }
}

```

Resulting in:

---

**Option 2: Inheritance**

It is as if I have a little devil and angel on my shoulder, one tugging me towards the easy and half-finished code of the former example, and another urging me to redesign what I am doing into a much cleaner and abstracted approach.

In the previous example, all "event types" (Movement, Dialogue, Item Collection etc.) were handled by enums that were passed through a Switch statement to check which method should be executed based on the parameters inputted into the Unity Editor for that specific Game Object.

In this system, there would be a base "Interactible" class, which various classes would inherit from to implement functionality. The Activate() method would be overridden in the children for each specific class.

```
public class NPC : Interactible
{
    public override void Activate()
    {
        //NPC Code...
    }
}

```

The unfortunate downside to this is that I can't just use one prefab for all my events and change them based on the custom editor that I define.

I would have to create a custom editor for each possible child of the Interactible class, and instead of selecting which type of event I want it to be from a simple drop down, I will have to swap out different scripts for different functionality.

# Answer
I'd do neither of these. Instead, I'd apply Composition over Inheritance.

A quick sketch for now since I have to run:

* `IInteractionResponse` interface defines the pattern all components that can respond to these interactions will follow, eg. exposing an `Activate()` method. Then you can implement this on any number of unrelated types:

+ a `Dialogue` component for conversations and messages
    + a `ScriptedMovement` component for moving objects & bits of the scene around
    + an `ItemTransaction` component for adding/removing items in the player's inventory
    + etc...
* Any script that can start an interaction - say a `UsableItem` script or a `InteractableButton` or an `InteractionTrigger` can expose a public variable for the component it should fire when activated (or search for the first such component attached to its `GameObject`)
* If you give these interaction response components a public component `triggerNext`, then when one interaction component has done its job it can fire the next one in sequence. You can use this to snap-together complex interactions like LEGO bricks, to start a dialogue that then gifts an item then triggers some more dialogue then opens a gate to leave the area....

This lets each class in the setup stay small, simple, and self-contained. And you can remix them modularly, rather than being limited to single directional inheritance.
> 2 votes

# Answer
This question is quite opinion-based, but personally, I would clearly choose the Inheritance based solution (or I would use an Interface if you don't need any class variables in the `Interactible` class).

If you put all your logic in a single class, you clearly violate one of the SOLID principle : **Single responsibility principle**.

The code used to move a platform should not "know" how to start a cutscene. This does not make sense.

> The unfortunate downside to this is that I can't just use one prefab for all my events and change them based on the custom editor that I define.

I don't think using a single prefab would be a good idea anyway. Where do you attach the script? Using a specific script according to the event would allow you to attach it to the asset (or an empty parent), making more sense in my opinion.

> I would have to create a custom editor for each possible child of the Interactible class, and instead of selecting which type of event I want it to be from a simple drop down, I will have to swap out different scripts for different functionality.

Why would you need to create a custom editor for each child class? The `CustomEditor` tag has an additionnal parameter so that the custom editor can edit child classes:

```
public CustomEditor(Type inspectedType, bool editorForChildClasses);

```
> 0 votes

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


# Question
Title: Why is Vector3.MoveTowards only working on a single frame?
I have three laptops in my scene and I am trying to bring them to front when I click on them. I am able to recognize which laptop is clicked by using the code below, but it doesn't move to the focus position in a single click: it moves only one frame so I have to keep clicking it.

```
void Update () {
        if (Input.GetMouseButtonDown (0)) {
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);

            if (Physics.Raycast (ray, out hit)) {
                if (hit.transform.name == "Laptop 1") {

                    Debug.Log("Laptop 1 is clicked");
                    Laptop1Trans.position = Vector3.MoveTowards (Laptop1Trans.position, FocusPointTrans.position, moveSpeed);

                } else if (hit.transform.name == "Laptop 2") {
                    Debug.Log("Laptop 2 is clicked");
                } else if (hit.transform.name == "Laptop 3") {
                    Debug.Log("Laptop 3 is clicked");
                } else {
                }
            }
        }
    }

```

I tried moving the move part to a method but still same behaviour.

Are there any workaround?

# Answer
> 1 votes
It looks like you're trying to use MoveTowards in a fire-and-forget manner, like a tweening library: "Hey you, move over there gradually over the next several frames, without further supervision"

MoveTowards doesn't do that (It couldn't if it wanted to — it doesn't even know what object to move, all it has is some vectors). It's just a way to calculate *one* position: the place the object should be *this frame* after taking *one step* toward the destination.

To keep updating its position, you need a method that runs every frame until it reaches its destination, not just the frame you clicked. A Coroutine can do this quite well:

```
IEnumerator MoveTo(Transform mover, Vector3 destination, float speed) {
    // This looks unsafe, but Unity uses
    // en epsilon when comparing vectors.
    while(mover.position != destination) {
         mover.position = Vector3.MoveTowards(
             mover.position,
             destination,
             speed * Time.deltaTime);
         // Wait a frame and move again.
         yield return null;
    }
}

```

You can start this motion with:

```
StartCoroutine(MoveTo(clickedLaptop, FocusPointTrans.position, moveSpeed);

```

# Answer
> 0 votes
Use `Input.GetMouseButton` instead. `GetMouseButtonDown` only returns true on one frame when the button was pressed down, while `GetMouseButton` returns true while the button is held down.

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


# Question
Title: Changing coordinates of the object with velocity preservation
In Doodle jump, if a player jumps over one side of the screen he appears on another side with preserved velocity and other physical parameters.

I made two trigger colliders on the sides of the screen with OnTriggerEnter2D method.

```
private void OnTriggerEnter2D(Collider2D collision)
{
    collision.transform.position = new Vector3(collision.transform.position.x * -0.95f,
        collision.transform.position.y, collision.transform.position.z);
}

```

If I multiply collision.transform.position.x by -1f then on collision some glitching occurs. It gets stuck for a second. I believe this happens because when player is moved to the other side there is another collision detected and he is thrown back. Is there a more elegant way of handling this instead of multiplying by 0.95f?

---

Final solution:

```
[Tooltip("Controls where is the edge of the level where player is trasfered on the opposite side of the level.")]
[SerializeField]
private float xAxisMovementConstraints;

private void DetectBoundryCross()
{
    if (transform.position.x < (-xAxisMovementConstraints))
    {
        transform.position = new Vector2(transform.position.x + (xAxisMovementConstraints * 2f),
            transform.position.y);
    }
    else if (transform.position.x > xAxisMovementConstraints)
    {
        transform.position = new Vector2(transform.position.x - xAxisMovementConstraints * 2f,
            transform.position.y);
    }
}

```

# Answer
I haven't tested this, but my approach would be to not use colliders for this at all.

A simple script should be all you need.

```
using UnityEngine;
using System.Collections;

public class SideWrap : MonoBehavior {
    public float left_boundary = -5.0f;
    public float right_boundary = 5.0f;

    void Update()
    {
        float newX = transform.position.x;
        if(transform.position.x < left_boundary){
            newX = transform.position.x + (right_boundary - left_boundary);
            transform.position = new Vector2( newX, transform.position.y );
        }
        else if(transform.position.x > right_boundary){
            newX = transform.position.x - left_boundary;
            transform.position = new Vector2( newX, transform.position.y );
        }
    }
}

```

Attaching this to the player object should give your desired result.
> 1 votes

---
Tags: unity, 2d, physics, unityscript, scripting
---


# Question
Title: How can I dynamically switch between graphics APIs?
In games like the new "Doom", you have a console, from which you can use commands to reduce the game's quality or even to switch graphics API, from Opengl to Vulkan and viceversa.

How is this done? I think it reconstructs the window context based on the chosen graphics API (maybe?). How could this be implemented?

# Answer
A common way to approach this, assuming you actually want to (see postscript for why you may not), is to implement your game in terms of a rendering *interface* and simply implement that interface for all graphics API back-ends you want to support.

For example if your game is only capable of drawing colored squares:

```
struct IRenderer {
  virtual void Initialize() = 0;
  virtual void Shutdown() = 0;
  virtual void DrawSquare(int x, int y, const Color& color) = 0;
};

```

You then implement this interface for D3D and OpenGL (and anything else you want to support):

```
struct D3DRenderer : IRenderer { ...details... };
struct OpenGLRenderer : IRenderer { ...details... };

```

There's a huge spectrum of specific options you could use to do this, ranging from the direct approach to using PIMPL to hide the implementation, putting the implementation directly in the game versus shoving it off into a DLL in case the user never wants to switch, et cetera. The subject would make an interesting book.

Then, to swap at runtime, when the user issues the appropriate command, you call `Shutdown()` on the current renderer, initialize a new renderer and call `Initialize()` on it, and continue.

Rendering is a fundamental part of a game, so it's likely you will need to spend a non-trivial amount of time setting up the code to execute this handoff correctly. You're almost certainly going to have to close and re-open the underlying OS window, depending on the APIs you use, although you may be able to do some tricks there. But more importantly you're going to have to make sure every outstanding game object that has any kind of reference to some object in the rendering API gets that object swapped out with a replacement or otherwise knows how to handle this major bit of platform infrastructure being swapped out underneath it.

You can be as blunt about it as requiring the user to essentially terminate the gameplay session and restart from the main menu (this is probably the more common approach), or you can be as complex about it as trying to hot-reload everything so cleanly you preserve the precise state of everything's animation, et cetera. The latter is *way* harder. I'd recommend you look at techniques used for "hot reloading" general game assets to learn about the basic stuff you'd need to do there.

---

That said, I don't generally recommend people do this. Especially small teams or hobby developers. It takes a *lot* of effort, as you can hopefully see by even my rough sketch above. For that effort, you get *very* little payoff. It's an interesting technical achievement but the ability to hot-swap rendering systems in the middle of the game isn't usually a major selling feature.

If you are small or single-person team, I would generally recommend you support different rendering backends at *compile time* only, and only when necessary to get the "best" API for your supported platforms. If you're going to ship on Windows and macOS and want to support D3D12 and Metal so you can achieve optimal graphics quality and performance on each platform, great. But if you also want to include OpenGL and Vulkan on those same two platforms you've massively increased the workload for yourself and you're likely to end up with substandard implementations of everything instead of good implementations of a specifically chosen technology.
> 7 votes

---
Tags: c++, graphics-programming
---


# Question
Title: Is it possible to measure Used vs Unused time in a 60hz frame in Unity?
In custom engines I've often made a frame rate meter that shows how much of the each frame was actually used. In other words if the game is locked to 60fps using vblank I show a graph of how much of each frame was used for processing and how much was just waiting for the next vblank. This gives a visual indication of how much more can be added to a scene without hitting my frame rate budget.

Is this possible to do in Unity?

What I tried:

I made a script that creates a `System.Diagnostics.StopWatch` and starts it. I set that script's Script Execution Order to be the very first script.

In the script's `Update` I record the `ElapsedTicks` from the stopwatch as `startTicks`. In the scripts's `OnGUI` I compute a `deltaTicks` as in

```
long deltaTicks = m_stopWatch.ElapsedTicks - startTicks;

```

I can then compute how much of a 60fps frame was taken with

```
long ticksPerFrame = System.Diagnostics.Stopwatch.Frequency / 60;
float amountOfFrameUsed = (float)((double)deltaTicks / ticksPerFrame);

```

Note: I get that OnGUI is called multiple times per frame but the way I end up storing `amountOfFrameUsed` I only end up recording the time from the last time `OnGUI` is called that frame.

Anyway, this does give me a graph to look at but I have no idea if what it's slowing me is correct for Unity.

In my own engine I'd record the time at VBlank and then in my code, when all processing was done I'd compute the elapsed time since vblank.

Is what I'm doing correct? Is there a better or another way I should be doing this? (note: I have not used the profiler because I wanted to see this FPS meter in a production app, not in the Editor where there is tons of overhead).

# Answer
> 1 votes
Your method looks valid. If not a precise measure of used vs unused time, it will at least serve as a useful proxy, with values that climb when pre-render scripts or rendering workload take longer.

If you're not happy with the OnGUI approach, you could also try doing this in a Coroutine with:

```
 yield return new WaitForEndOfFrame().

```

This "waits until the end of the frame after all cameras and GUI is rendered, just before displaying the frame on screen."

For mobile games, you can also use the built-in profiler (on the device, not the editor profiler).

---
Tags: unity, frame-rate
---


# Question
Title: SerializationException: Type UnityEngine.MonoBehaviour in assembly UnityEngine,l is not marked as serializable
I am trying to save/persist some data between my scenes but I keep getting the error:

*SerializationException: Type UnityEngine.MonoBehaviour in assembly UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null is not marked as serializable.*

Here is my script:

```
public static void SaveState()
    {

        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Open(Application.persistentDataPath + "/EmpireGame", FileMode.OpenOrCreate);

        SaveClass sc = new SaveClass()
        {
            food = Player.food.amount,
            wood = Player.wood.amount,
            iron = Player.iron.amount,
            stone = Player.stone.amount,
            buildingList = new List<Building>(),

    };
        sc.buildingList = playerBuilt;

        Debug.Log("State Saved!");

        bf.Serialize(file, sc);
        file.Close();
    }
}

[Serializable]
class SaveClass
    {
        public int food, wood, iron, stone;
    public List<Building> buildingList;

}

```

I've narrowed it down to: **public List buildingList;** being the offending code, but I don't know how else to save this list. I think the MonoBehaviour part of it is the "" as it inherits from MonoBehaviour.

I've read:

Unity Docs: Serialization

Watched:

persistence-saving-and-loading-data

Saving Data In Unity

I've looked up so many Q&A's over this but still can't figure it out.

# Answer
> 1 votes
Remember when I suggested pulling out just the parts of the component you wanted to save, and putting them in a serializable struct? This is another reason why.

Unity's component types are not natively tagged with the `[System.Serializable]` attribute, so your `BinaryFormatter` doesn't know how to serialize & deserialize them properly. (Which makes sense, because correctly deserializing a list of `MonoBehaviour` components would require knowing which `GameObjects` in the scene to attach them to, and how to work with Unity to update the scene hierarchy - a .Net standard method that doesn't know anything about Unity can't do that for you.

Defining your own serializable type lets you control exactly what gets saved/loaded and how, to make sure it does the right thing for your game. You can also make your save files more robust against minor changes to your game. Say you change the sprite used for Farm buildings in a recent update. If your save file contained the whole GameObject serialized, then when you load the old save in the new version it could still be referencing an old texture (or no texture at all if it's been removed from the build). By serializing just the information that it's a "Farm-type building, of level L, at position X, Y" lets the updated version of your game spawn a correct, modern, up-to-date version of the farm with those properties, rather than getting clogged with legacy data.

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


title: Poisson Distribution and Traffic Flow

text:
# Question
Title: Poisson Distribution and Traffic Flow
I'm attempting to create a simulation of car traffic and to model the flow, it seems like Poisson Distribution would be useful here. I'm still trying to get my head around the variables I would incorporate, but at the moment I know what I want the arrival rate at a certain point to be, the speed limit, and the minimum gap (time) between cars.

Currently, cars spawn on one end of the road after a preset amount of time and accelerate to the speed limit, checking for cars in front and slowing down if necessary so as to keep at least a the minimum gap between the two of them.

I'm not sure how to incorporate variables such as acceleration into the Poisson Distribution. Does anybody have any experience implementing something similar?

# Answer
Unless cars are created or destroyed between the two ends of the road, your average arrival rate will be the same as your average creation rate. Therefore, all you need to do is adjust the parameters of your Poisson distribution to match your desired arrival rate.

The other variables you mention, such as acceleration, etc, aren't going to change the average arrival rate. These other variables may change the dynamics of traffic flow, and small details of the arrival, like bunching and other fluctuations about the average. But they won't change the average arrival rate.
> 2 votes

---
Tags: unity, simulations, probability
---


# Question
Title: Project 360 video on the inside of a iso sphere / polygon sphere
I'm creating a game in Unity. I have a iso sphere or polygon sphere, and I want to project a 360 video on the inside of the polygon sphere.

I've learned thow to put a 360 video on the inside of a sphere, following this thread, but how can I do it inside a polygon sphere, since the 360 video was created based on a sphere but not a polygon sphere?

```
Shader "Flip Normals" {
    Properties {
        _MainTex ("Base (RGB)", 2D) = "white" {}
    }
    SubShader {

        Tags { "RenderType" = "Opaque" }

        Cull Off

        CGPROGRAM

        #pragma surface surf Lambert vertex:vert
        sampler2D _MainTex;

        struct Input {
            float2 uv_MainTex;
            float4 color : COLOR;
        };

        void vert(inout appdata_full v) {
            v.normal.xyz = v.normal * -1;
        }

        void surf (Input IN, inout SurfaceOutput o) {
             fixed3 result = tex2D(_MainTex, IN.uv_MainTex);
             o.Albedo = result.rgb;
             o.Alpha = 1;
        }

        ENDCG

    }

      Fallback "Diffuse"
}

```

# Answer
The principle isn't really any different.

Inside the fragment shader you compute a latitude & longitude by converting the shaded point's offset from the center of the sphere from Cartesian to spherical coordinates.

Then you use that lat/long pair as the texture coordinate to look up into your video texture (assuming your video is in equirectangular projection - you'd use different formulas for other projections)

Even with a mesh that's already unwrapped in lat-long format, you should really do this mapping in the shader anyway - affine texture mapping alone can't handle the distortion at the poles of the sphere correctly.

You can see an example of this texture mapping distortion and how to fix it with a shader in one of my earlier answers on the subject.
> 1 votes

---
Tags: unity, 3d, textures, projection, 360-video
---


# Question
Title: Navigate multiple Units on a grid through a tight space with different directions
I just started learning about pathfinding algorithms.
Assume we have this scenario:
Blue and Green can move only on those tiles. They can also talk to each other.
Blue wants to go through the tunnel and green wants to go too, however both need to pass each other somehow. In case of a "basic" A\* pathfinding algorithm they will both get stuck in the tunnel.
To prevent this issue i had some Ideas:
\- Blue can tell green that he should move back first (give blue priority) when they both step next to each other (problems arise when there are more than 2)
\- A better algorithm, that calculates this like an automatic traffic regulator (one will wait till the other frees the path) --\> seems complicated
Now I am wondering if there are more efficient methods, how its done in general, if you have better ideas, if you can point me to some algorithms or some papers that adress this issue.

# Answer
> 1 votes
This is definitely a classic problem that can be seen if you play Red Alert or something.

What you might do is count squares that are in these congested areas as being impassible if a unit is moving across them in the near future (within x squares); and have your algorithm tell the other units to stop on squares just outside of "temporarily impassible" areas.

This would also naturally assist with the "piling up" of confused units all going the same direction, as who ever said they were going first would just go, block the path, and then another would follow in its wake.

To make sure you guard against an edge case, I think you should detect when a square "opens up" by seeing how many passable adjacent squares there are, allowing this solution to be effective no matter how long the "bridge" is.

*NOTE: I would only block squares "in front" of a unit moving across the "bridge", which allows the next unit in line behind it to cross the bridge. This means you "unblock" bridge squares as it crosses them and the next unit simply queue's up the new "block" on it.*

This solution is O(n) (might be considered O(1)) because each unit only uses as much calculation as it was going to to determine that the bridge is "blocked", where as units talking to eachother would be O(n^2) or worse. This is to say that it is highly efficient among the various solutions to may get.

For units that are "blocked" or "waiting", give them a new "moving" state that says as much, where they move to the nearest allowed square until they get priority; "remembering" but not acting on the rest of their move.

Lastly, as to who gets priority you'll probably want to keep it simply with "first come first serve" of who gets to cross first; after all this is a convenience to the player who didn't micro-manage his units (because they could basically do this by stationing the first group on one side and prioritizing the one that they care about.)

---

As a second solution, you could consider that units are allowed to temporarily occupy the same spot, giving you (essentially) two lanes. You see this a lot with infantry in old RTS, where they can pile up in a single spot for a moment but they eventually sort themselves into their positions.

---
Tags: collision-detection, algorithm, path-finding, grid, tiles
---


title: Optimize polygons renderization

text:
# Question
Title: Optimize polygons renderization
I'm developing a game (in Ogre3D) that, in short, consist in a vehicle that moves along a terrain and leaves a colored trail behind it. The trails are basically quads (**a**), these quads changes their color accordingly to the vehicle's speed. My challenge now is that I need to subdivide these quads into 5 (or more) sub-polygons (**b**) and each one of them should have a different color accordingly to others vehicle's properties. When moving around for a while these quads start to accumulate on screen and the render process starts to heavily lag and thus fps count is sub optimal.

Some considerations: \- All quads are appended to a single mesh that belongs to a single entity sharing the same material, so batching should be optimal. \- Tried adding LOD for this mesh but I had no luck to make it work in Ogre1.9.

So, my main question is how can I optimize the rendering of this polygons?? Can I delegate this task by somehow to the gpu via shader programming?

Edit: My goal would be to avoid having to draw each one of those sub-quads in (b) (only draw the big quad (a)) but by somehow being able to colorize each one of those sub-quads.

# Answer
NOTE: I am unfamiliar with Ogre3d but I do greatly enjoy optimizing things.

I would imagine that part of the issue is that you're going to be continually Allocating memory. What's worse, it sounds like you're appending this allocated memory to a structure you already have. What can happen is that as these accumulate you may be *rewriting* the structure as you append to it. If you're using a C# List, a C++ Vector, or many other datastructures, you could instead be requesting it allocate a contiguous block of size equal to double your current size, which will slowly cause it to fragment your memory and allocated giant chunks. Definitely look into how you're allocating your memory for this, and really consider how badly you need these to be truly a single mesh rather than simply adjacent to one another.

Secondly, it sounds as though you're trying to solve your problem with more Polygons when you don't need them. For instance, if you wrote a shader that took those properties and simply colored the original polygon in sections according to the data you want, you could easy save yourself the quin-tupling of quads you're experiencing.

Lastly, it also sounds as though you're possibly "rendering" things that aren't on screen, when this is unnecessary. If these things exist as a way to see the history of how your vehicle traveled, you can simply care about the ones that are in view. Be sure you're only rendering those that are on screen.

Without code I'm not sure there's anything else I could suggest. Hope this helps!
> 1 votes

# Answer
**Disclaimer**: I am not familiar with Ogre3D.

You can manage to do the effect you want via shaders.

Since I am only familiar with GLSL I will be using that...

First off all, whatever changes from quad to quad (for example the speed of the vehicle) you need to pass it as an attribute. I will assume we pass four such properties (based on the example image) and they dictate the intensity of the colors of the bands.

**Note**: I say quad, but there is no difference if you are using triangle primitives. I fact I tested this with triangles.

Now, how does the shader knows the positions to place those colors? Well, you need to pass an additional attribute for that. Sure, it can be standard texture coordinates, but it does not need to be. It makes no difference.

With that said, our vextex shader will be doing passthrough, so we can use the properties in the fragment shader:

```
#version 330

layout (location = 0) in vec3 VertexPosition;
layout (location = 1) in float prop1;
layout (location = 2) in float prop2;
layout (location = 3) in float prop3;
layout (location = 4) in float prop4;
layout (location = 5) in float pos;

smooth out float vprop1;
smooth out float vprop2;
smooth out float vprop3;
smooth out float vprop4;
smooth out float vpos;

void main()
{
    vprop1 = prop1;
    vprop2 = prop2;
    vprop3 = prop3;
    vprop4 = prop4;
    vpos = pos;
    gl_Position = vec4(VertexPosition, 1.0f);
}

```

OpenGl will interpolate the values for us. Thus, if we pass `pos=0` on one side of the quad and `pos=1` on the other, we get a gradient. That is what we will be using that on the fragment shader to place the colors.

The other attributes (`prop1`, `prop2`, `prop3`, `prop4`) are going to tell the intensity of the colors. The code I wrote for that uses a `vec4` to specify the color of each band and use scalar product.

Notice also that - with this shader code - OpenGL will also interpolate the values of the other attributes. This means that if you set the old values on the bottom of the quad and the new ones on the top you get a nice gradient.

This is the fragment shader I wrote for this:

```
#version 330

smooth in float vprop1;
smooth in float vprop2;
smooth in float vprop3;
smooth in float vprop4;
smooth in float vpos;

out vec4 FragColor;

void main()
{
    vec4 s =
          ((step(0.75, vpos) - step(1.00, vpos)) * vec4(0.0, 1.0, 1.0, 0.5) * vprop1)
        + ((step(0.50, vpos) - step(0.75, vpos)) * vec4(0.0, 0.0, 1.0, 0.5) * vprop2)
        + ((step(0.25, vpos) - step(0.50, vpos)) * vec4(0.0, 1.0, 0.0, 0.5) * vprop3)
        + ((step(0.00, vpos) - step(0.25, vpos)) * vec4(1.0, 1.0, 0.0, 0.5) * vprop4);
    FragColor = s;
}

```

Here the `step` function will give me hard edges for the colors. `((step(0.75, vpos) - step(1.00, vpos))` will be `1` when `vpos` is in the range from `0.75` to `1.00`, and it will be `0` otherwise. Similarly happens with the other terms. Yes, I have extra zeroes after the comma, for readability.

The code above puts alpha on `0.5`. Use whatever you need.

---

Aside from that, you are probably better off using an array to store your vertex, and use it as a circular buffer (once you get to the end, you start overwriting at the start). Using Triangles or Quads primitive type (but not strips or fans). Doing that you know it won't grow. *I do not know how permisive Ogre3D is about that.*

As, as I said, you can animate the quads fading away. You can add another attribute for the time when the quad was created, and pass the current time as a `uniform` to the shaders (Note: you do not need passthrough uniforms, you can use them directly in the fragment shader). That way the fragment shader knows how much time has passed since the Quad was created, and use that for setting alpha. *Figure out what do you need to do on Ogre3D to get alpha blending working properly for the transparency effect.*
> 0 votes

---
Tags: c++, shaders, textures, optimization, ogre
---


title: Random generation of a board

text:
# Question
Title: Random generation of a board
So I have four "boards" made of 16 sprites (4x4). Each board is parented to an empty GameObject. I would like to randomly generate their positions but I am not sure how. However, they should still be generated at the middle of the screen not like anywhere off. So basically each board can be placed at any position but must touch at least one of the boards. The sprite of one board should line up with the sprite of the other board. For example:

So yeah any help is appreciated!

# Answer
> 1 votes
Notice that for each side of a board there are 7 places to place another board. (To see all the possibilities place a board so that only one square touches the other board, then slide the first one along that side.)

So you can place the first board in the center to get started, then randomly choose a side and then choose one of the 7 positions. Now it gets a little tricky. We can randomly choose a board and then a side and then a position, but we don’t want overlaps so we need to check for those and pick again if the board would overlap.

You can use a `Dictionary<string, boolean>` to keep track of which spaces are taken by taking the integer coords and concatenating then together with a comma (or whatever separator), and storing `true` in the dictionary for all the taken spaces.

So if you do that, then you can generate a potential place to put a board, check if it is taken (that is, if any of the squares it would cover are already in the dictionary,) and if not, place it and add its squares to the dictionary. Otherwise try another place.

You may also want to keep track of the spaces you have already tried so you don’t end up trying them more than once.

---
Tags: unity, procedural-generation
---


# Question
Title: Should Unity lifecycle methods be annotated with the UsedImplicitly attribute?
Does annotating Unity lifecycle methods with the `UsedImplicitly` attribute improve the readability of your code?

For example:

```
public class Example : MonoBehaviour
{
    [UsedImplicitly]
    private void Awake()
    {
        DoSomething();
    }

    private void DoSomething()
    {
        // ...
    }
}

```

This blog post on "Structuring Your Unity MonoBehaviours" suggests this approach as a useful convention.

> 8. Annotate any Unity lifecycle methods (Start, Awake, Update, OnDestroy etc.), event methods, and other functions that are implicitly (or automatically) invoked in your code with the \[UsedImplicitly\] attribute. This attribute, although included in the UnityEngine.dll, is used by ReSharper to disable code cleanup suggestions for methods that are seemingly unreferenced. It also helps to make the code easier to read for people who are newer to Unity and your codebase, especially for events that are referenced via the inspector.

(Note: I don't think ReSharper shows code-cleanup suggestions for seemingly unreferenced Unity lifecycle methods, so that might be outdated advice.)

I agree with the above post that it could be helpful for those newer to Unity. I also think it could be useful to label those Unity lifecycle functions that are not used as frequently as `Awake`, `Start`, and `Update`. But I am wondering if this is actually a good convention for "clean code", or if it's just noise that reduces readability.

# Answer
> 10 votes
It depends on the target demographic.

In the example above, the target demographic is the ReSharper tool, which benefits from these attributes because it suppresses messages which aren't helpful to you. But if you don't feel the need to use ReSharper or a similar tool (although maybe you should, they have some valid critique from time to time), then you don't need to care about that demographic.

Anyone who ever did a basic Unity tutorial knows very well that `Start` and `Update` are used implicitly by the Unity engine, so it won't give them any new information. It might in fact confuse the heck out of them if you forget this once. What do you want to say with that? Is this maybe not actually a MonoBehaviour? Or is there some obscure reason why you must call it explicitly which I am not aware of?

It can, however, help if you are working with inexperienced developers who might not be familiar with the more esoteric Unity events like `Reset` (dangerous, because calling it explicitly might not do what you think it does). The `[UsedImplicitly]` attribute might then tell them that they don't need to look for the class which calls that method because the engine does. But again, this is only of value if you have the discipline to do this consistently. And if you have that amount of self-discipline, you could just as well agree on adding a comment.

# Answer
> 6 votes
**I argue that no you should not use it.**

The UsedImplicitly attribute is from the Jetbrains.Annotations namespace so the only case where it might apply is if everyone using the code will be using ReSharper.

ReSharper has a plugin for Unity which already handles this for you, making sure not just to remove warnings that they are not used but also marking them with a little Unity symbol so that anyone reading the code can see that they are called by Unity itself.

I'd also like to add an example when using them might go wrong. Assume you have a class inheriting from MonoBehaviour, but after a refactor it no longer has any inheritance. If you marked private methods with \[UsedImplicitly\] then you will not receive the correct warnings. If you use the Unity plugin for resharper it will notice that you no longer inherit from MonoBehaviour and will throw warnings as the methods indeed are no longer called.

# Answer
> 5 votes
I'd make the argument that it can't really hurt.

For somebody very familiar with Unity's workings, it probably doesn't add anything. Those people are already going to be pretty familiar with what Unity's runtime calls on your behalf.

But for somebody who isn't, like me, it might be helpful. Even if I didn't know what it meant offhand, I'd go look it up, and that would probably be sufficient to give me a better understanding of what was going on in the code.

Also, if one does use static analysis tools that are incorrectly warning about the methods, then you'll want to quiet those warnings somehow, because "ignorable" warning noise makes it harder to see the *real* warnings in any such output. It's usually better to ignore such warnings in a surgical, localized fashion (in this case by decorating the offending methods with attributes) than through broader measures like disabling that specific warning project-wide.

# Answer
> 2 votes
The problem with this approach is that it's incredibly error prone.

If it isn't reliable, the tags will fail to convey useful information, and their presence or absence will occasionally succeed at conveying false information, which is harmful.

If you decide to go with it, you **must** remove the human error, which isn't hard to do, but takes a good 2 hours of work if you haven't done something like this before. There are 2 approaches - each with their own advantages - you can use either one:

1. Verify and reject non-complying code on check in or automated build.
2. Automated edit of code to fix tags on check in or automated build.

Is it worth to have it? Yes. Is it worth 2 hours of your time? Your call.

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


title: How to draw a list of images?

text:
# Question
Title: How to draw a list of images?
I found an example with strings

```
...
List<String> inventory = new List<>(skin), sell = new List<>(skin);
inventory.setItems("Axe", "Fuel", "Helmet", "Flux Capacitor", "Shoes", "Hammer", "Trash Can", "The Hitchhiker's Guide To The Galaxy", "Cucumber");

Table table = new Table(skin);

table.add("Inventory");
table.add("Merchant").row();
table.add(inventory).expand().fill();
table.add(sell).expand().fill();
...

```

result:

https://bitbucket.org/dermetfan/somelibgdxtests/src/d787e98e84647d06ffbe9add3165e87bcabef7e3/core/src/net/dermetfan/someLibgdxTests/screens/DragAndDropTutorial.java?fileviewer=file-view-default

How to replace strings with images?

My code:

```
...
List<Image> inventory = new List<>(skin), sell = new List<>(skin);
inventory.setItems(Image(texture1), Image(texture2), Image(texture3));
...

```

Result:

# Answer
> 0 votes
You replace the text with an Image class e.g

```
table.add(new Image(new TextureRegionDrawable(texRegion)));

```

texRegion should be a TextureRegion you have already loaded

---
Tags: libgdx, kotlin
---


# Question
Title: How to move object on local space not object space in unity
I am watching ***this (game dev, space parenting & rotation)*** Sebastian Lague video and found that there are **three spaces** actually (not two) and these are world space, local space and object space.

1. World space: The static space (0,0,0)
2. Object space: related to the object space
3. Local Space: related to the parent of the object

I am amazed that i didn't find the distinction between these two spaces(local and object) on official unity forms but actually it exists. My question is that why there is no Space.Local? I found that there are Space. Self and Space.World. Space.Self is refer to object space. I can move my object to object space using this

```
    void Update () {
        transform.Translate(new Vector3(0,0,1) * Time.deltaTime * 2,Space.Self);
    }

```

And i can move my object to world space using this

```
void Update () {
    transform.Translate(new Vector3(0,0,1) * Time.deltaTime * 2,Space.World);
}

```

but there is no support for local space that i could move the object to local space (means move the object related to its parent object). There is a fair distinction between Local and Object space but unity didn't consider it i guess or i am wrong.

# Answer
I think that there is a bit of misunderstanding with these 3 spaces.

Basically you should focus on **two** spaces: World and Local. Object space has meaning when you take about vertices positions. Example, if an object has a **local position** of (1, 0, 0), if means its center is one unit away from the parent center on the x axis. but so what would an **object space position** of (1, 0, 0) mean? That the objects center is one unit away from itself? Only the object's vertices are given in object space (meaning, where is this vertex compared to the center of the object). Vertex shaders use this for example. But in your everyday use of Unity you don't use it.

**So why is there a Space.Self?**

Well, according to the doc, what it does is:

> Applies transformation relative to the local coordinate system.

So Space.World is world coordinate, and Space.Self is local coordinate.

In your example, you move the object in local space. Moving it in object space doesn't mean anything.

Finally note that you can also move in local space by editing `transform.localPosition` instead of `transform.position`, But this would be the same as a translation using Space.Self or Space.World respectively.

Hope this clears things up a bit
> 1 votes

# Answer
`transform.Translate` does something a little funny. The `Space` you select picks the directions that it moves the object, but doesn't scale the translation. The actual translation vector is always applied in worldspace, and you're just selecting whether to rotate the direction to match the object's local axes, or not.

Since an object might not have a parent at all to fetch a direction from, I'm guessing they skipped the extra conditional logic for this case because it doesn't come up in practice much that you want to move an object with respect to its parent while ignoring its parent's scale. More often, if we're doing parent-space positioning, we want to use something like:

```
transform.localPosition += translation;

```

which allows the parent's scale to affect the resulting position.

But, if you really want `transform.Translate` style behaviour and syntax for this case, we can add it as an extension method:

```
public enum Spaces {
    World,
    Parent,
    Self
}

public static class SpaceExtension {

    public static void Translate(this Transform transform, Vector3 translation, Spaces ralativeTo) {
        switch(relativeTo) {
          case Spaces.World:
              transform.position += translation;
              break;
          case Spaces.Self:
              transform.position += transform.rotation * translation;
              break;
          case Spaces.Parent:
              // Fall back on world space if there's no parent.
              Quaternion rotation = Quaternion.identity;
              if(transform.parent != null)
                   rotation = transform.parent.rotation;
              transform.position += rotation * translation;
              break;
        }
    }
}

```

This gives you a new overload of `transform.Translate` to use if you like, with the alternative Spaces enumeration to pass the parent space option.

I haven't tested it extensively to verify whether it handles non-uniform scales the same way the original `transform.Translate` does, though I'd caution that if you're using non-uniform scale in a parent hierarchy you're likely going to run into bigger troubles. ;)
> 0 votes

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


# Question
Title: Applying friction force not working correctly
I have a simple physics simulation I'm creating whilst following the Nature of Code tutorials on YouTube by Daniel Shiffman, at the moment I've just started learning about friction and have had a go at implementing in it my project.

But for some reason, applying friction doesn't work when placed directly in the update method. To elaborate, when I apply friction by holding down the space bar rather than just doing it every frame, the friction works as instead.

Another thing to note is that when I apply friction directly in the update method, the objects don't appear on the screen.

Below is the loop I have that iterates through all the rigid bodies in the scene:

```
        foreach (var body in this.bodies)
        {
            Vector2 wind = new Vector2(0.01f, 0.0f);;
            Vector2 gravity = new Vector2(0.0f, 0.1f * body.Mass);

            // Setup friction
            float c = 0.05f;
            var friction = body.Velocity;
            friction *= -1;
            friction.Normalize();
            friction *= c;

            if (Keyboard.GetState().IsKeyDown(Keys.Space))
            {
                // If I move this call to where I'm applying
                // all the other forces, the objects dissappear.

                // But if I apply force by pressing the space bar
                // the force is applied correctly.

                // Apply friction
                body.ApplyForce(friction);
            }

            // If I apply friction out here, it doesn't work
            // also, friction when printed to the screen is
            // NaN.

            // Apply wind and gravity
            body.ApplyForce(wind);
            body.ApplyForce(gravity);

            body.Update();
        }

```

and also, here is the source code that I'm following along with (essentially copying) in the video tutorials here

I feel as though I've supplied enough information, but if you need to know anything else please don't hesitate to do ask.

# Answer
> 3 votes
When velocity is 0, friction becomes a zero vector and you can't normalize it, that's why it becomes NaN

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


# Question
Title: What are some ways to make a scene without walls and infinite terrain visually appealing?
My Player Character is standing in the middle on flat infinite terrain. The player can see as far as the farplane of the camera. And there is nothing there which is... boring.

I wanted to Plant a couple of trees which move with the player (but not rotate with them).

But I would need tons of trees for that, and that would destroy performance.

Next I've thought about a "foggy-shadow", or a light or a cubemap with textures of things.

But those things are visually totally ugly.

Now I am in front of a hard decision and I dont know what to do.

Here are examples of infinite terrain so you guys know what I mean.

# Answer
> 1 votes
Like DMGregory said in the comments, trees wouldn't kill performance. I assume you wanted to place real highly detailed trees, which would of course drop performance.
Normally you use simplified meshes of trees with **MipMap** Textures. Maybe even just a plane. This works well because when something is far away and stationary it doesn't rotate relative to the player you have to only render it once. Check out **dynamic LOD** (Level of Detail
Sometimes **Parallax scrolling** can be added to give the **illusion** of distance. This is mostly used in 2D games however.
Another option would be to use a **skybox**. Lets say you are inside a wide environment (fields, desert, mountains etc) you also might not need the meshes for the mountains in the background, as the player movement relative to them is very small. A very good approximation.

---
Tags: unity, terrain
---


# Question
Title: Camera movement issue with pitch and yaw angles
I'm trying to implement a simple first person camera using pitch and yaw angles (no quaternions, I want a simple camera for debugging purposes). An Input class processes mouse input and translate the x and y position in the window into angles. Here's the code:

```
#define SENSITIVITY 0.01f

void Input::ProcessMouseInput(int x, int y, Camera &camera)
{
    /* pitch and yaw angles */
    static float pitch = 0;
    static float yaw = 0;

    /* initialize initial mouse position */
    static int prev_x = x;
    static int prev_y = y;

    int offset_x = x - prev_x;
    int offset_y = y - prev_y;

    pitch += offset_y * SENSITIVITY;
    yaw += offset_x * SENSITIVITY;

    /* compute transformation matrix */
    XMMATRIX pitchTransform = XMMatrixRotationX(pitch);
    XMMATRIX yawTransform = XMMatrixRotationY(yaw);
    XMMATRIX transform = XMMatrixMultiply(pitchTransform, yawTransform);    // fps-like
    //XMMATRIX transform = XMMatrixMultiply(yawTransform, pitchTransform);  // airplane-like

    /* transform camera direction - rotate camera */
    XMVECTOR oldDirection = XMVectorSet(0.0, 0.0, 1.0, 1.0);
    XMVECTOR newCameraDirection_ = XMVector3Transform(oldDirection, transform);
    XMMATRIX oldView = XMLoadFloat4x4(&camera.GetInitialViewMatrix());
    XMVECTOR det = XMMatrixDeterminant(oldView);
    XMMATRIX inverse = XMMatrixInverse(&det, oldView);
    XMVECTOR v = XMVector3TransformNormal(newCameraDirection_, inverse);
    XMFLOAT3 newCameraDirection;
    XMStoreFloat3(&newCameraDirection, v);
    camera.SetDirection(newCameraDirection);

    /* store current mouse position */
    prev_x = x;
    prev_y = y;
}

```

What I do is I calculate the direction vector in the view space and transform it with pitch/yaw rotations. Then I tranform the resulting vector in world space coordinates and update the camera direction. All works fine if the camera space x-z plane initial position is parallel to the world space x-z plane. If the camera is initially tilted downwards or upwards the movement is off (moving along the yaw direction causes a wobbling and the movement is incorrect). I can't find the problem as I think the calculations are correct (but they obviously aren't).

**EDIT**

what I mean with odd behaviour is that when I create a camera that has starting position with a pitch wich is not zero I get mixed movements (pitch when yawing and yawing when pitching)

# Answer
> 1 votes
This block of code here:

```
XMVECTOR det = XMMatrixDeterminant(oldView);
XMMATRIX inverse = XMMatrixInverse(&det, oldView);
XMVECTOR v = XMVector3TransformNormal(newCameraDirection_, inverse);
XMFLOAT3 newCameraDirection;
XMStoreFloat3(&newCameraDirection, v);
camera.SetDirection(newCameraDirection);

```

says "always rotate with regard to the initial camera orientation." That means if the initial camera orientation was inclined downwards, all future yaw should happen in that inclined horizontal plane - leading to the wobble you describe.

If you don't want that, I'd recommend not using the camera's initial orientation matrix as a basis for future updates. Instead, initialize your pitch & yaw to match the initial rotation so you start from the right place, and rotate with regard to the identity matrix instead.

---
Tags: c++, camera, directx11, matrix, transformation
---


# Question
Title: How can I properly add material textures to my model?
This is the first time I'm doing game development and I decided to pick Godot engine.

I downloaded some object on the internet for my initiation learning. There are four files:

1. throp\_srub.obj
2. normal.tga
3. diffuse.tga
4. throp\_srub.fbx

The fbx didn't appear on the sidebar, so I drag the object mesh and then add spatial material, add diffuse.tga texture to albedo and normal.tga into normal map.

However, it didn't appear as the preview given:

The object appears like this:

Why is that and how can I fix it?

# Answer
> 1 votes
Two things i see.
It looks to me like the alpha channel is either not there or not being recognized. Analyse your color Texture.
Second is, that normally the Normal texture should be a blue purple color. This is not the case in your picture. But thats just my experience. If the normals are fine don't worry about the second part.

---
Tags: textures, materials, godot
---


# Question
Title: How to rotate a parent object based on a child object's position so that it is now in front of the player?
So I have a car object and basically the player will select a part on it and be able to look at the description and other things. What I currently want to do is when the user clicks on one of these parts that the car rotates so that the part is looking at the player so to speak. My problem is I am terrible with Vector math lol. I have a script that basically gets the child(part) object, the parent(car) object, and the player/camera object when ever the user clicks on a part. I feel as though my math is wrong here but I just can't figure it out. What I am doing in the script below is making the positions into two dimensions because I only want to rotate on the y axis of the parent object.

```
Vector3 hitObjPos = new Vector3(hitObject.transform.position.x, 0, hitObject.transform.position.z);
Vector3 baseObjPos = new Vector3(baseObj.transform.position.x, 0, baseObj.transform.position.z);
Vector3 playerPos = new Vector3(transform.position.x, 0, transform.position.z);

Vector3 childHeading = hitObjPos - baseObjPos;
Vector3 playerHeading = playerPos - baseObjPos;

float angle = Vector3.Angle(childHeading, playerHeading);

if(angle > 75 || angle < -75)
    baseObj.transform.rotation = Quaternion.Euler(0, baseObj.transform.eulerAngles.y+ angle, 0);

```

There are a couple of problems, first off I guess I need to create some type of check on the angle requirement so that when I click on say an object that is already perpendicular to the player, like a car door when viewing from the side, that it doesn't rotate the `baseObj`. However, another problem I am having is the rear items rotate fine and I can see them great but, the front objects rotate away from the user and I am basically looking at the rear of the object.

# Answer
> 0 votes
Since i don't have enough Reputation i can't comment: Whats the problem? Since you didn't say what the problem actually is i can only guess. The part is on the wrong side? (180 degrees) Change

```
childHeading = hitObjPos - baseObjPos

```

to

```
childHeading = baseObjPos - hitObjPos

```

If you just don't know how to apply that angle, then you can put it into the transform as the rotation.

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


# Question
Title: License for a casino game with virtual money (chips)
Do I need a specific license for operating a casino game (lets say poker Hold'em or video slots) that players are supposed to play with virtual money (chips) only? I am speaking about games like Zynga poker, Poker Deluxe, Slotomania and the hundreds other similar games on iTunes or Google Play. Players start with a certain amount of chips and if they run out they can rebuy a bundle of coins to keep playing. The users may **not** exchange those collected virtual funds (chips) for products or services, or cash out for real money, but just keep on playing for a fun.

Do I need any license for operating such a game?

# Answer
I'm going to amend my answer a bit, as the situation is much more complex than I let on. The previous disclaimer (*i.e.*, this is not legal advice, and you should consult an attorney) still applies. I am an attorney, but this is not my area of law (and indeed, it is a complex area), so please consult with a professional.

This answer is focused on the United States. Laws differ by jurisdiction. And within the U.S. gaming law is primarily a product of state law, which is to say things differ across the states. Also note, laws are changing very quickly in this area.

A few more points of clarification: I'm taking your question to refer to casino games that are played with virtual (not real) money. You use the phrase "supposed to play with virtual money" which is a bit disconcerting. (Does that mean, in other words, that players are encouraged to not play with real money but somehow the system allows for real money play? If so, we're in a very different territory.) The games you're describing are generally known as Casino-Like Social Games.

You also mention that the users may not exchange the virtual funds for . . . "services," but I'm assuming you're defining services in a manner to exclude playing casino games on your software, which is arguably a service. (Software is sometimes treated as a good and sometimes as a service.)

The legal issues in this area fall into two main groups: Legality and Compliance. Many of the laws in this area were written long before the internet, and there's still a good deal of ambiguity how the laws apply to internet sites and services.

Most states define gambling and regulate it by prohibiting illegal lotteries. An illegal lottery generally consists of three elements:

1. Payment of some form of consideration by user
2. Result determined by chance
3. Award/prize, something of value

If any of these three elements are not present, the activity is normally not considered gambling. The games you're describing likely satisfy the first two elements, but remain legal by virtue of not providing any award or prize of value (step 3).

Note that alternative approaches to the "prize" can still run into trouble. In Japan, Japan's Consumer Affairs Agency gave notice to a number of game companies that "Kompu Gacha" would no longer be allowed, a system where players receive a valuable grand prize for completing a set of "gacha" prizes, which are awarded randomly. Prizes don't have to be money, e.g., a car or an iPad would still count. (In one case involving the NCAA lottery system for awarding tickets to Final Four games, a right to buy a set of tickets was not deemed to be a prize, but there's not much law on this.)

The more pertinent question for you is whether virtual currency constitutes received value? The answer to that is going to depend on a number of factors, such as whether the currency was acquired with real cash or earned through game play, what the player can do with the virtual currency (e.g., cash it out for real money or physical goods? or just use it for in game virtual goods?), with whom can the currency be used? (i.e., can it be spent on third parties?).

Some games try to reduce the risk on this issue by implementing a form of dual currency: one currency that is purchased, another form that is awarded through game play.

The consensus view among game developers who make these types of games (at the moment) is that they are generally in a safe zone with virtual-only currency, but, as I mentioned earlier, this is something you're going to want to discuss with a competent attorney in your jurisdiction. Indeed, many online gaming companies switched to virtual-currency-only for players within the United States in an effort to avoid prosecution on illegal gambling charges.

So far, this discussion has focused entirely on the legality, but your question was on compliance and licensing. The reason for this focus is because if it isn't gambling, you don't fall within the regulatory scheme for licensing gaming sites. If it is gambling, the short answer is yes, you need a gaming license, and you'd need to make sure your games comply with various gaming regulations. There are all kinds of them, things like the display of near-misses on slot-machines, etc. The licensing and compliance regulations are outside the scope of this answer.
> 3 votes

# Answer
If your game uses fun money (virtual money) you do not need a license. If your game uses fiat currency and in some cases cryptocurrency, you **will** need a license.

EDIT: I would not bother trying to sell virtual money and then allowing players to redeem them as this will get you into trouble.

Fortunately, getting a gambling license is not as hard as it used to be with GamblingTec.com who offer a gamble licensing as a service to game developers.

Basically, GamblingTec owns licensing and payment solutions etc. You simply integrate your game into the API and off you go.

Go check it out: Gambling Licensing for Game Developers

> DISCLAIMER: I work for GamblingTec.com which was designed specifically to help game developers. It is one of the few affordable solutions out there designed to help.
> -2 votes

---
Tags: legal, licensing, poker
---


title: Real cash gambling app

text:
# Question
Title: Real cash gambling app
I am making a cash game like deal or no deal for use as an android app, using adobe software.

The idea is player wagers 50 pence through Paypal plays the game wins, say, £10 pounds and then cash out.

How do I create a cash pay and play system probably with Paypal? I have done the art work and the basic flash script, i.e. actions and movie.

I will also need some sort of data feedback to prevent hacking of game, I think, and to be able to send updates and be able to remotely alter win percentages according to profits and losses.

Will the user need to be connected to a server?

Can someone help guide me through what the steps I need to do?

# Answer
> 4 votes
Well, the first thing you need to do is ensure that the game in question is legal in your jurisdiction, and whatever jurisdictions you plan to market it in:

Gambling is often heavily regulated, and I'm not sure if PayPal allows it at all.

---

As for the technical details, what you want to have is a client-server application, to prevent fraud.

The server must hold literally *all* state, and only send to the client what is absolutely necessary to display direct responses to the users actions.

Remember that any and all data you send to the client **must** be considered compromised, and every bit of information you receive from the client **must** be considered a malicious attempt to cheat.

---

As for altering win/loss rates to ensure that you stay in the black, that part is easy, once you have all state on the server side; at least if you know how your game works in terms of profit margins.

Consider, as an example, a slot machine game:

A naïve implementation might simply generate a set of random numbers for the reel positions, and hand that off to the client, along with the winnings it generates for the given bet.

A more sophisticated approach would be to keep track of *your* global winnings, setting aside a certain portion of your profits (say, 40 %) as prize money, and generate reel settings that ensure that you never go over the prize cap, distributing the winning spins between various players more or less evenly.

The same approach could be taken for a deal-or-no-deal type game: Rather than generating the entire layout of the prize boxes up front, you generate the order in which the prize boxes are opened, in order to give the desired amount of winnings for that game.

# Answer
> -1 votes
As a game developer, you can offer your game to licensed third parties who will operate the game under a gambling license and in the Jurisdiction of their choice. In general, they will have pre-existing payment solutions etc.

If you want to offer the game for real money plays directly, you would either need to get a gambling license (the UK is pretty easy to get one) or work with a company such ours: GamblingTec.com who offer a gambling licensing platform as a service.

> DISCLAIMER: I work for GamblingTec.com which was designed specifically to help game developers. It is one of the few affordable solutions out there designed to help.

---
Tags: android, game-design, flash, server
---


title: Can I use an animated gif as a texture?

text:
# Question
Title: Can I use an animated gif as a texture?
I want to have a plane that shows an animated Gif as it's texture, so essentially it will be a movie. Can I apply an animated Gif as a texture? If so, does it apply like a normal texture? *Note: I know about Movie Textures, but don't want to use them*

# Answer
> 8 votes
Short answer is no. You will need to convert the GIF to an atlased texture (a single 2D image that has all the GIF frames in it) and then cycle the UV coordinates on a textured quad to change which frame is currently visible. This is not particularly hard to do, and there are existing sprite animation packages for Unity that can do most of it for you (you'll likely have to create the atlas yourself, or at least split the GIF into separate PNG images for each frame to use an existing atlas creator).

# Answer
> 0 votes
I made this script. Just attach it to the gameobject, for example a plane and then just fill the frames array with all the frames of the gif in the inspector.

```
public class AnimGif : MonoBehaviour {

    [SerializeField] private Texture2D[] frames;
    [SerializeField] private  float fps = 10.0f;

    private Material mat;

    void Start () {
        mat = GetComponent<Renderer> ().material;
    }

    void Update () {
        int index = (int)(Time.time * fps);
        index = index % frames.Length;
        mat.mainTexture = frames[index]; // usar en planeObjects
        //GetComponent<RawImage> ().texture = frames [index];
    }
}

```

---
Tags: unity, animation, textures
---


# Question
Title: Child transform's position not updated as parent moves
I have a parent game object `Object1`. It has a child, which is simply an empty game object called `ReferencePoint`. `ReferencePoint` can be any arbitrary point on `Object1` itself.

I have another game object `Object2`. It has a public field called `RotationReference`, of type `Transform`. In the inspector, the `ReferencePoint` on `Object1` is assigned to the `RotationReference` field on `Object2`.

As `Object1` moves, I expect `ReferencePoint` to change its position as well. `Object2` is supposed to change its rotation to face its `RotationReference` -- in this case, the `ReferencePoint` on `Object1`:

```
public override void Rotate()
{
    Vector3 relativeRotationReferencePosition =
        this.RotationReference.position - this.transform.position;

    this.transform.rotation = Quaternion.LookRotation(relativeRotationReferencePosition);
}

```

However, I noticed that `Object2` is not rotating at all, even when `Object1` is moving. When I step through the call stack multiple times, I discover that `this.RotationReference.position` always has the same value, even though `Object1` is moving.

What am I missing here?

# Answer
> 1 votes
If the problem is that the position itself does not change, probably it is due to some mistake in assigning a value to rotationReference. Check that you do not change its value anywhere in the code. And it is "RotationReference = ReferencePoint" not the other way round and so on.

Also I don't see why you need referencePoint on object1 and not just use Object1 itself as the target. But maybe I just don't understand what you're trying to do.

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


# Question
Title: 2d Tower Defense - Projectile Prediction
For my map, it's very curvy and the node sizes aren't consistent. I have everything finished so that projectiles will actually fly at an enemy, however if a projectile is going too slow it will miss. I am wondering if I should just go the easy route, and just make the projectile homing, or if I could get help here on where to start. The enemy is changing directions, and moving around, although never changes speed.

# Answer
> 1 votes
I'm unsure if this is for the purposes of the look of the game, or if it's for balance.

* If it's for balance, I think projectile speed is totally fair as an attribute the user will have to consider. In this case, just don't worry about it and perform "real" hit detection. Some users (like myself) like this.
* If it's for looks and you don't want speed to be part of the balance, I think you could "predict" where something will be (after you've chosen your target so you don't waste tons of calculation time on objects you're not firing at) by (without displaying it) having the move function occur several times and the firing angle/time-to-target occur several times, then pick which one is a hit, then let the game use those values.

This would look something like: \`

```
Target = someCreatureObject
OldPosition = Target.Position

for (i=0; i<5; i++)
    Target.Move()
    if(Tower.FramesToTarget() == i)
        PositionToAimAt = Target.Position
        break
Target.Position = OldPosition
return PositionToAimAt

```

\` Where FramesToTarget would be some calculation of the speed vs. the distance. A note: you'll have to give yourself a way to know if none of the positions it could shoot would hit and then decide what to do from there.

This would make the coding a tiny bit easier, but I don't think the function I posted would be too hard.

I'll mention that one of the original Tower Defense games (my favorite of them) Flash Element TD had a mix of projectile speeds and I believe used homing (you can tell if you use the cannons.) This homing was virtually un-noticable.

NOTE: in all of the above cases, Area of Effect weapons should use real hit detection for the AOE damage after decided where the hit occurs.

# Answer
> 1 votes
Even if you could predict the enemy's movement, you mentioned they might change direction, so that would either not work or be too complicated.

My favourite way is to make the missile homing. Keep the enemy's position in the missile's code as target (careful, don't keep a copy of it, keep a reference of it, so you get enemy's new position). Every frame approach target in a linear fashion, depending on missile's speed. This could go wrong if you had a missile that has a speed lower than the enemy's speed.

A lot of games have done this in the past, including warcraft 3, and if I'm not wrong, dota2 still does this. It's the safest way to guarantee that once you fire a missile, you will eventually damage the enemy.

---
Tags: mathematics
---


title: DDS load texture and cubemaps

text:
# Question
Title: DDS load texture and cubemaps
I'm trying to render a skybox with a cubemap on it and to do so I'm using DDS Texture Loader from DirectXTex library. I use texassemble to generate the cubemap (texture array of 6 textures) into a DDS file that I load at runtime. I generated a cube "dome" and sample the texture using the position vector of the vertex as the sample coordinates (so far so good), but I always get the same face of the cubemap mapped on the sky. As I look around I always get the same face (and it wobbles a bit if I move the camera). My code:

```
//Texture.cpp:

    Texture::Texture(const wchar_t *textureFilePath, const std::string &textureType) : mType(textureType)
    {
        //CreateDDSTextureFromFile(Game::GetInstance()->GetDevice(), Game::GetInstance()->GetDeviceContext(), textureFilePath, &mResource, &mShaderResourceView);
        CreateDDSTextureFromFileEx(Game::GetInstance()->GetDevice(), Game::GetInstance()->GetDeviceContext(), textureFilePath, 0, D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, D3D11_RESOURCE_MISC_TEXTURECUBE, false, &mResource, &mShaderResourceView);
    }

// SkyBox.cpp:

void SkyBox::Draw()
{
    // set cube map
    ID3D11ShaderResourceView *resource = mTexture.GetResource();
    Game::GetInstance()->GetDeviceContext()->PSSetShaderResources(0, 1, &resource);

    // set primitive topology
    Game::GetInstance()->GetDeviceContext()->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

    mMesh.Bind();
    mMesh.Draw();
}

// Vertex Shader:

cbuffer Transform : register(b0)
{
    float4x4 viewProjectionMatrix;
};

float4 main(inout float3 pos : POSITION) : SV_POSITION
{
    return mul(float4(pos, 1.0f), viewProjectionMatrix);
}

// Pixel Shader:

SamplerState cubeSampler;
TextureCube cubeMap;

float4 main(in float3 pos : POSITION) : SV_TARGET
{
    float4 color = cubeMap.Sample(cubeSampler, pos.xyz);
    return color;
}

```

I tried both functions grom DDS loader but I keep getting the same result. All results I found on the web are about the old SDK toolkits, but I'm using the new DirectXTex lib.

# Answer
> 2 votes
I found my error. The vertex shader outputs the homogeneous clip coordinates with SV\_POSITION semantic before the model space position with POSITION semantic. The Pixel shader reads the input position from the first register so I was sampling the texture cube map using clip space coordinates, hence I was always facing the same direction. I was ignoring the warning from the compiler.

---
Tags: textures, directx11, loading, cubemap, skybox
---


title: GLFW- Help implementing glBufferedData

text:
# Question
Title: GLFW- Help implementing glBufferedData
Good Morning,

I've been trying to learn some OpenGL by following the tutorials on learnopengl.com and I've hit a bit of a snag. I'm trying to implement the same functionality as the "Hello Triangle" tutorial (learnopengl.com-\>Getting Started-\>Hello Triangle) except I'm trying to put it in its own class. Essentially it is the same code just moved around, The issue is coming from glBufferData(...). from my understanding this function is to essentially bind the data with the buffer object. When `glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);` is called in my main.cpp file the program operates how it should and it draws the square. But if i comment that out on Main.cpp and move it to BindBuffers on Window.cpp the program still runs but it does not render the square. Any input on why this is happening/ what im doing wrong?

**Main.cpp**

```
#include "Engine\Window.h"
#include <glad/glad.h>

#include <GLFW/glfw3.h>

#include <iostream>

int main()

{
    Window window;

// set up vertex data (and buffer(s)) and configure vertex attributes
// ------------------------------------------------------------------
float vertices[] = {
    0.5f,  0.5f, 0.0f,  // top right
    0.5f, -0.5f, 0.0f,  // bottom right
    -0.5f, -0.5f, 0.0f,  // bottom left
    -0.5f,  0.5f, 0.0f   // top left
};
unsigned int indices[] = {  // note that we start from 0!
    0, 1, 3,  // first Triangle
    1, 2, 3   // second Triangle
};

window.GenBuffers();

window.BindBuffers(vertices,indices);
//glBindVertexArray(window.GetVAO());
//glBindBuffer(GL_ARRAY_BUFFER, window.GetVBO());
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, window.GetEBO());
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);

glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
while (window.CheckClose())
{
    window.processInput();
    window.Begin();
    window.Render(window.GetVAO());
    window.End();
    window.Update();
}
window.~Window();
return 0;
}

```

**Window.cpp**

```
#include "Window.h"

Window::~Window() {
    glDeleteVertexArrays(1, &VAO);
    glDeleteBuffers(1, &VBO);
    glDeleteBuffers(1, &EBO);
    glfwTerminate();
}
Window::Window() {
/*** Creates window and intializes shader, if this is needed I can edit but I chopped it to save some room*/
}

void Window::Update() {
    glfwPollEvents();
}
void Window::Begin() {
    glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);
}
void Window::End() {
    glfwSwapBuffers(window);
}
bool Window::CheckClose() {
/*Checks if window was closed*/
}
int Window::GetShader() {
    return shaderProgram;
}
void Window::Render(unsigned int VAO) {
    // draw our first triangle
    glUseProgram(GetShader());
    glBindVertexArray(VAO); // seeing as we only have a single VAO there's no need to bind it every time, but we'll do so to keep things a bit more organized
                            //glDrawArrays(GL_TRIANGLES, 0, 6);
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
    // glBindVertexArray(0); // no need to unbind it every time
}
void Window::GenBuffers() {
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);
    glGenBuffers(1, &EBO);
}
void Window::BindBuffers(float vertices[],unsigned int indices[]) {
    glBindVertexArray(VAO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    //glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
}
unsigned int Window::GetVBO() {
    return VBO;
}
unsigned int Window::GetVAO() {
    return VAO;
}
unsigned int Window::GetEBO() {
    return EBO;
}

```

# Answer
> 0 votes
the issue is related to how sizeof behaves. It is a fully compile time construct that derives it's result only from the type information.

When an array is passed as a parameter it loses information about how many elements there are in it. So you need to pass that explicitly.

```
void Window::BindBuffers(float vertices[],unsigned int vertexCount, unsigned int indices[], unsigned int indexCount) {
    glBindVertexArray(VAO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices[0])*vertexCount, vertices, GL_STATIC_DRAW);
}

```

---
Tags: opengl, rendering, glfw
---


# Question
Title: Rotate player to a specific angle using Rigidbody2D
First of all, I'm an absolute beginner in unity and coding so please excuse my lack of knowledge and my mistakes. I didn't achieve to fix my issue with others posts.

I'm trying to do a little top-down 2D RPG in which you move your character using the keyboard.

---

## What I have for now:

* The player can go in 8 directions,

---

* The player rotation follows the directions smoothly using the rigidbody2D.rotation BUT although it works well for angle from 0° to 180° there is a problem with angle \> 180° or \< 0°. For example, the character is facing -135°, we want our character to go down which means 180°. Instead of going to -180 which is the same modulo 360° he turns the other way and do almost a full turn for just a 45° angle movement.

---

I tried another solution by using transform.rotation and quaternions but I also have an issue with that method. While the movements work great, the velocity of the character seems affected by the Quaternion.Slerp because when the Slerp finishes, the character slow down.

---

The 2 rotation codes I tested (i do not use them simultaneously if you were wondering):

```
void GetRotation()
    {
        myRigidbody.rotation = Mathf.Lerp((myRigidbody.rotation), angle, angleRotation);
    }

void GetRotation()
    {
        Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.forward);
        transform.rotation = Quaternion.Slerp(transform.rotation, rotation, angleRotation);
    }

```

---

My movement code for one direction:

```
if (// Get Inputs)
    {
        angle = 0f;
        GetRotation();

        myRigidbody.velocity = Vector2.up * speed * Time.deltaTime;
    }

```

---

How would you fix that or what could I read to understand what goes wrong ?

Thank you in advance!

# Answer
I finally found something that work for me :

```
void GetRotation()
    {
        if (myRigidbody.rotation <= -90 && angle >= 90)
        {
            myRigidbody.rotation += 360;
            myRigidbody.rotation = Mathf.Lerp(myRigidbody.rotation, angle, angleRotation);
        }

        if (myRigidbody.rotation >= 90 && angle <= -90)
        {
            myRigidbody.rotation -= 360;
            myRigidbody.rotation = Mathf.Lerp(myRigidbody.rotation, angle, angleRotation);
        }

        else
        {
            myRigidbody.rotation = Mathf.Lerp(myRigidbody.rotation, angle, angleRotation);
        }
    }

```
> 2 votes

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


# Question
Title: Problem when reloading unity scene(level)
I am using

`SceneManager.LoadScene(SceneManager.GetActiveScene().name);`

to reload my current scene in unity , but when i run the game ,in hierarchy lots of scene are appearing. Also if i do some editing, i can not save the scene any more. unity is giving and error "Overwriting the same path as another open scene is not allowed". I am new to game development. I would appreciate any help.

# Answer
This might be solution to your problem, but I can't say for certain.

This is what I usually do to prevent collisions from calling the same function multiple times:

```
bool dying = false;
bool dead = false;

void Update()
{
    if(dying && !dead)
    {
        dead = true;
        makeDead();
    }
}

void OnCollisionEnter2D(Collision2D coll)
{
    if (coll.gameObject.tag == "Enemy")
    {
        dying = true;
    }
}

```
> 1 votes

# Answer
Error: Multiples "loading or is not loaded" scenes in the editor hierarchy. Error: "Overwriting the same path as another open scene is not allowed".

Add **LoadSceneMode** parameter.

`SceneManager.LoadScene(SceneManager.GetActiveScene().name, LoadSceneMode.Single);`

Update: Better, but same issue. This could be a Unity bug. This image is after stop player:
> 0 votes

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


# Question
Title: XML, how to have two variables under the same node?
I have XML sheet that I use in my game. In my unity(C#) game, a game's monster can spawn at predetermined position or random position.

```
<monster delay="0.2" isRed = "true" position ="random"/>
<monster delay="0.3" isRed = "true" position ="10 20"/>

```

Right now I read value of position and if it is "random" then I assign random position for the monster.

If it is not "random" then I parse the value, separate them by a space bar then use the two numbers I obtain from the "position" as position of my monster.

I get this gut feeling what I am doing is probably really ugly and inefficient that there is probably better way to do this, but I am not sure.

# Answer
It's hard to avoid "ugly and inefficient" when serializing data as XML, but space- or comma- separated strings for coordinate data is okay. Alternatively, you can use two attributes or make position a child element, but I'm not sure these are better than what you already have.

```
<monster delay="0.3" isRed="true" position-x="10" position-y="20" />

<monster delay="0.3" isRed="true">
   <position x="10" y="20" />
</monster>

```
> 1 votes

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


# Question
Title: As an Independent Developer should I host my own official game servers
My small team is approaching initial closed alpha for testing, however that has brought up the question of whether it is a good idea to host our official game instances from my home office or not. I've run a few dedicated servers before on my home PC (have 3 active as a service at the moment actually) so I'm not unfamiliar with the process. However I'm looking into building a server PC specifically to fulfill that singular purpose. I have google fiber 1000mbps so I don't think I'll have bandwidth issues. But I wonder if any of you have advice and insight into what I should expect, dangers to avoid, etc.

Here's what I anticipate, am I missing anything?:

1. Masking home IP via dynamic DNS service - (pointing to a website to login rather than an IP)
2. Running multiple VMs on a single server to easily manage server resources
3. Initially testing with a few selected users
4. Eventually open up to more users once proven stable

# Answer
I once calculated the cost of buying a server and hosting it at home vs. renting an equivalent one from a cloud hoster for a couple years. I came to the conclusion that the hoster was in fact cheaper. Some things you might forget to account for:

There are also a few things you get by renting a server from a professional hoster which are hard to express in money:

* **Better physical security**. Ever heard of a game going offline because a burglar broke into a datacenter?
* **Better availability** (power outages, internet outages, etc.). Do *you* have an UPS and standby generator at home?
* **Better protection from denial-of-service attacks**. Yes, some people **do** get that angry when you ban them from your game. I've seen that more than once.
* It is **very easy to upgrade and downgrade** your hardware as needed (often with just a few clicks). This is especially useful when you can't yet estimate how much server capacity you will actually need.
* You can **pick the geographic location** (to a certain degree) to place the server closest to where your main player base is located.
> 2 votes

---
Tags: server, alpha, hosting
---


title: Where to store in app purchase data?

text:
# Question
Title: Where to store in app purchase data?
I'm making a game using unity. In the game I've a purchasable product "remove ads". Where should I store user purchase data? If I use player prefs data will restore after a reset or uninstall.

# Answer
> 1 votes
Player Prefs is fine, mostly. Consider, however, that it is fairly simple for a smart user to modify player prefs to remove ads on their own. You can instead rely on the in-app purchase system to track this for you.

In particular, on iOS, you can check the App Store Receipt (using classes in StoreKit, which only requires connecting to Apple to refresh the receipt once, if it’s not already downloaded), which includes information about all non-consumed in-app purchases. That is handled by Apple, and can be checked on each launch, and is pretty secure.

Similarly, when you initialize in-app billing on Google Play, you are given a list of products the user already owns that are not consumed.

Or you could just store it in player prefs. After a reset or uninstall that information goes away, but thats why apps usually have a "restore purchases" button which will get that information back from the app store/google play store.

---
Tags: unity, in-app-purchase
---


# Question
Title: Displaying a Text component for every wave and then disabling it
I want to display the wave number before every incoming wave of enemies. And after displaying this it should hide the text component. I tried to get this done with StartCoroutine() and Ienumerator but that does not seem to work as it runs only once. As in Wave 1 is displayed and nothing after wards.

Below is the script I am using for this:

```
public class WaveUpdateTextScript : MonoBehaviour
{

    [SerializeField]
    WaveSpawner spawner;

    private WaveSpawner.SpawnState currentState;
    private Text waveDisplay;

    // Use this for initialization
    void Start()
    {
        waveDisplay = GetComponent<Text>();

        StartCoroutine(WaveDisplaySwitch());

    }

    IEnumerator WaveDisplaySwitch()
    {

        switch (spawner.NextWave)
        {
            case 1:
                waveDisplay.text = "Wave 1 of 8 !!";
                yield return new WaitForSeconds(4f);
                gameObject.SetActive(false);
                break;
            case 2:
                gameObject.SetActive(true);
                waveDisplay.text = "Wave 2 of 8 !!";
                yield return new WaitForSeconds(4f);
                gameObject.SetActive(false);
                break;
            case 3:
                gameObject.SetActive(true);
                waveDisplay.text = "Wave 3 of 8 !!";
                yield return new WaitForSeconds(4f);
                gameObject.SetActive(false);
                break;
            default:
                Debug.Log("This be the meh wave...");
                break;
        }

    }
}

```

I know whats going on, on `start()` the coroutine is started once and then case 1 of `switch` works and then stops at `break`.

How would I solve this? or is this not the best way of achieving the desired result?

# Answer
> 1 votes
You've halfway got it. You've noticed that you kick off the coroutine but only evaluate it once, so you need to introduce a mechanism that will trigger multiple times.

There are two major ways to do this. You can either have your coroutine spin in an infinite loop, checking at regular intervals for a change in wave, or you can have a function that some other piece of code calls every time a new wave begins.

# Option 1:

```
public class WaveUpdateTextScript : MonoBehaviour
{

    [SerializeField]
    WaveSpawner spawner;
    private Text waveDisplay;

    void Start()
    {
        waveDisplay = GetComponent<Text>();
        StartCoroutine(WaveDisplaySwitch());
    }

    IEnumerator WaveDisplaySwitch()
    {
        int currentWave = -1;
        while(true)
        {
            if(currentWave != spawner.NextWave)
            {
                waveDisplay.text = "Wave " + spawner.NextWave + " of " + spawner.WaveCount + "!!";
                waveDisplay.gameObject.SetActive(true);
                yield return new WaitForSeconds(4f);
                waveDisplay.gameObject.SetActive(false);

                currentWave = spawner.NextWave;

                break;
            }
            //else if currentWave == spawner.NextWave, then the wave hasn't changed since the last check, so we do nothing.

            //Ends the infinite loop if we've hit the last wave
            if(currentWave == spawner.WaveCount)
                break;

            //This will make the loop check once per second, which can be adjusted as needed.
            yield return new WaitForSeconds(1.0f);
        }
    }
}

```

Note that this option assumes that NextWave is an integer of some kind, incremented by some other code that determines that the wave has completed. This also assumes that something else is managing spawner.NextWave, such as incrementing it whenever all enemies have despawned.

# Option 2:

```
public class WaveUpdateTextScript : MonoBehaviour
{

    [SerializeField]
    WaveSpawner spawner;
    private Text waveDisplay;

    void Start()
    {
        waveDisplay = GetComponent<Text>();
    }

    public void StartNewWave(int wave)
    {
        StartCoroutine(WaveDisplaySwitch(wave));
    }

    IEnumerator WaveDisplaySwitch(int wave)
    {
        waveDisplay.text = "Wave " + wave + " of " + spawner.WaveCount + "!!";
        waveDisplay.gameObject.SetActive(true);
        yield return new WaitForSeconds(4f);
        waveDisplay.gameObject.SetActive(false);
    }
}

```

This method is much simpler. Some other code has to manage the wave spawning anyway, right? So just have that code call `StartNewWave` in addition to incrementing the wave number and whatever other bookkeeping it has to do.

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


title: Unity aircraft physics

text:
# Question
Title: Unity aircraft physics
I want to make a simple aircraft controller, what looks like little realistic in unity. I watch some video from airplane physics. and make a simple script in unity, but if I start, my plane cant move or if I change drag to zero, it cant lift. I tried to use real data and get it from wiki(F22 Raptor). To my game object, I gave the rigidbody component mass = 19670 kg. Engine thrust = 2 * 116000.0f Newton.

```
    private void calculateEnginePower()
    {
        EnginePower = engineThrust * ThrottleInput;
    }

    private void calculateForces()
    {
        angleOfAttack = Vector3.Angle(Vector3.forward, rb.velocity);
        angleOfAttack = Mathf.Clamp(angleOfAttack, 0, 90);

        coefficient = Mathf.Pow(1225.04f * rb.velocity.magnitude, 2) - 1; //M^2-2 where: M is mach.

        if (coefficient > 0.0f)
            coefficientLift = (4 * angleOfAttack) / Mathf.Sqrt(coefficient);
        lift = 1.2754f * 0.5f * Mathf.Pow(rb.velocity.magnitude, 2) * coefficientLift * 78.04f; // densy1.2754 kg/m3, speed m/s , (F22)Wing area: 840 ft² (78.04 m²)

        coefficientDrag = 0.021f;
        rb.drag = coefficientDrag * 0.5f * Mathf.Pow(rb.velocity.magnitude,2) * 1.2754f * 78.04f;

        rb.AddForce(transform.up * lift);
        rb.AddForce(transform.forward * EnginePower);
    }

```

roll, pitch... inputs from keyboard and mouse, EnginePower, RollInput... are simple properties and I call the Move function in a controller inside void Update.

```

Move(float roll, float pitch, float yaw, float throttle)
{
// transfer input parameters into properties.s
RollInput = roll;
PitchInput = pitch;
YawInput = yaw;
ThrottleInput = throttle;
AirBrakes = false;
calculateEnginePower();
calculateForces();
calculateRotation();
}

```
used these formulas:

for Lift force: Lift formula for Lift coefficient: Cl formula for Drag: Drag formula and for Drag coefficient: I used data from wiki too (0.021f).

# Answer
## Introduction

Ah no, I'm afraid that this won't work. You decided to get to an intriguing yet difficult realm. Calculating accurately \\$C\_L\\$ and \\$C\_D\\$ is not easy (there wouldn't be aerodynamic tunnels if it was).

Also I would suggest to try modeling much older aircraft (of the Cold war era like F-86 or Mig-17). Getting aerodynamic information for fighters like F-22 is virtually impossible (they are classified). I've heard that for some few of the older jets some aerodynamic figures have been declassified but I can't find any information right now. You can search in Aviation SE or ask if it's not already asked.

Having said that, let's look into your problems:

## Why can't I accelerate

You are setting the value you calculated for the *aerodynamic drag* to `rb.drag`. That won't work. Unfortunately the documentation isn't clear as in what drag represents. As I get it is aerodynamic drag which is dimensionless. You set newtons there so I guess drag will be so high that your aircraft is trying to swim not fly. So you have 2 options:

1. Set `rb.drag` to zero and call

```
float drag = coefficientDrag * 0.5f * Mathf.Pow(rb.velocity.magnitude,2) * 1.2754f * 78.04f;
rb.AddForce(transform.forward * (EnginePower - drag));

```
2. or simply do `rb.drag = coefficientDrag;` and then let unity handle it.

The first gives you more control while the second relies on unity's computations that I am unfamiliar with.

## Why can't I takeoff

Well that's simpler: you use a formulae that applies to supersonic speeds

$$ C\_{L} = \frac{4α}{\sqrt{M^2 - 1}} $$

Clearly if \\$M \< 1\\$ then the radicand becomes negative and the root can't be calculated. Your code ignores it. So `coefficientLift` will be `0` (I guess, you don't show the initialization). That means that you won't get any lift until you get supersonic. Ouch. You need a big runway for that.

One thing you can do, is to create a text file (in a format of your preference) that will represent a "typical" \\$C\_L - AoA\\$ matching. One example you can use is from Wikipedia

You can have something like

```
#AoA  CL
-5    0
-3    0.25
-0.5  0.5
2     0.75

```

and so on, and then apply linear interpolation to get the values in between.

## Other remarks

You use rb.velocity.magnitude as both velocity and Mach number. You need to make conversions (from Wikipedia): $$ M = \frac{u}{c} $$

```
where:
M is the Mach number
u is velocity of the moving aircraft and
c is the speed of sound at the given altitude

```

Hope the above helps. Good luck with your game.
> 2 votes

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